0

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

2 Answers 2

1

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());
Sign up to request clarification or add additional context in comments.

1 Comment

thank you @Guts ! this one really helped me, I found another approach which worked for me but your way is definitely more general. (upvoted but i guess i'm too new)
0

@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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.