NullPointerException when doNothing() is called on Junit Mockito

Viewed 47

I am writing a my unit test using Mockito but I am facing some error stubbing a method in the same class as my test class.

So basically, I am testing my service class MyService.class(Subject being tested) and this is how I am declaring my Mocks and @InjectMocks.

I am facing a null pointer whenever i hit the checkUserBackground() method when I am using doNothing() because the method returns void. I have also tried using verify() but I am getting error saying "Wanted but not invoked".

How do I get pass this error? Been stuck for 13 hours, appreciate some help thanks!

@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = "Strictness.LENIENT")
class MyServiceTest {

@InjectMocks
private MyService myService;



@Test
void testCreateUser() {
  User user = new User();
  user.setAge(25);
  user.setName(Jack);


  Mockito.doNothing().when(myService).checkUserBackground(user.getName(), true); 
  assertEquals(myService.createUser().getName(), "Jack");
}
}

This is the actual Service class:

class MyService() {
 public static void createUser(User user) {

  checkUserBackground(user.getName(), true);      //Null Pointer here

}

public void checkUserBackground(String name, Boolean newUser){

 //some logic which doesnt matter
}

}

1 Answers

Annotation @InjectMock is for dependency injection - its real class bean. But later in method you try mock method of injected bean. In your case will be enougth when you add method instead annotation:

@Before
public void init() {
    myService = Mockito.mock(MyService.class)
}
Related