May 11, 2021 08:46 pm GMT
Original Link: https://dev.to/adaendra/mock-static-methods-with-mockito-java-unit-testing-189
Mock static methods with Mockito - Java Unit Testing
One of the most frustrating element when I am doing the Unit tests in Java is to not be able to mock static methods.
Sure, during a long time we got PowerMock. But, since JUnit5, PowerMock wasn't compatible and we were unable to continue with it.
But now, we have this feature included in Mockito!
Dependencies
First, you have to add the mockito-inline library. (You can use any version up to 3.4.0)
Here is an exemple with Maven
<dependency> <groupId>org.mockito</groupId> <artifactId>mockito-inline</artifactId> <version>3.9.0</version> <scope>test</scope></dependency>
Writing test
To mock a static method, you have to create a mockStatic of the class with the static method, and declare the event you want to apply to your mock.
example
@Testpublic void test() {try (MockedStatic<LoggerFactory> loggerFactoryMock = Mockito.mockStatic(LoggerFactory.class)) { loggerFactoryMock.when(() -> LoggerFactory.getLogger(any(Class.class))).thenReturn(loggerMock);... verify(loggerMock, times(1)).error("Err message test");... } }
Then, you just have to run your tests!
I hope it will help you!
Original Link: https://dev.to/adaendra/mock-static-methods-with-mockito-java-unit-testing-189
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To