Home > OS >  How can I test Json.parser is not called with mockito java?
How can I test Json.parser is not called with mockito java?

Time:11-10

I want to verify Json.parse is never called in a function using unit test but i'm not using mockito correctly. would appreciate some help.

tried -

  1. when(Json.parse(wsResponse.getBody())).thenThrow(new Exception("error msg"))

but got an error - java.lang.RuntimeException: java.lang.NullPointerException although method signature includes throws Exception.

  1. tried to use verify and never but verify waits for a function

something like this -

verify(Json.parse(wsResponse.getBody()),never());

but got an error - org.mockito.exceptions.misusing.NotAMockException: Argument passed to verify() is of type ObjectNode and is not a mock!

src I looked at -

https://www.baeldung.com/mockito-exceptions ** How can I test that a function has not been called? ** How to verify that a specific method was not called using Mockito? ** mockito testing verify with 0 calls

CodePudding user response:

The Json.parse method is a static method. In order to mock it and test you will need powermockito. So please add those dependencies:

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>1.6.4</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito</artifactId>
    <version>1.6.4</version>
    <scope>test</scope>
</dependency>

After adding those you can run tests with powermockito by including those lines:

@RunWith(PowerMockRunner.class)
@PrepareForTest(fullyQualifiedNames = "com.test.*")

Then if you want to mock a static method you do it like this:

PowerMockito.mockStatic(Json.class);

Then you need to call the method under test:

underTest.testMethod();

In the end you need to tell powermockito that we want this method to be never called:

PowerMockito.verifyStatic(Mockito.never());
Json.parse(Mockito.any());

CodePudding user response:

@Guts answer is more general but requires PowerMockito (another lib), it is still good in my opinion.

This one also worked for me - I mock the wsResponse and checked if the returned body is not a type of json or csv. it gives me the same result (in my specific case), although it is not as general.

when(wsResponse.getBody()) .thenReturn("{}") .thenReturn("Version Id,Version Name");

  • Related