CodeGym/Java Course/Module 3. Java Professional/Popular scenarios for working with Mockito

Popular scenarios for working with Mockito

Available

6.1 Mocking the static method mockStatic()

And one more important point is mocking and verification of static methods. “What’s wrong with that?” you ask. Yes, static, but methods are the same. And you will be wrong.

Remember where we started learning about mock objects? Since these objects are artificially created through the DynamicProxy. And static methods are not bound to any objects and DynamicProxyit is impossible to intercept calls to them through . That's all.

But the creators of Mockito were able to dodge here too - they wrote their own class loader and with its help they were able to replace classes on the fly. A big and difficult job, but they still managed to do it.

You will need to add an additional library to pom.xml:

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-inline</artifactId>
    <version>4.2.0</version>
    <scope>test</scope>
</dependency>

Here's how to work if you need to mock a static method.

1 Create a special mock class object:

MockedStatic<ClassName>managerObject = Mockito.mockStatic(ClassName.class);

2 Add operation rules to this object:

To this object of the rule it is necessary to cling in other ways.

managerObject.when(ClassName::method name).thenReturn(result);

3 Be sure to wrap the use of this object intry-with-resources so that the object is immediately deleted and Mockito can clear the rules associated with it.

Example:

@Test
void givenStaticMethodWithNoArgs () {
    try (MockedStatic< StaticUtils> utilities =  Mockito.mockStatic( StaticUtils.class)) {
        // add rule
         utilities.when(StaticUtils::name).thenReturn("Hello");

        // check if the rule works
        assertEquals("Hello", StaticUtils.name());
    }
}

Not as beautiful as with annotations @Mockand @Spy, but very practical. It was very difficult to write tests when it was impossible to mock a simple static method that was used inside the methods under test.

Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet