Home > other >  Null controller when test with Mockito
Null controller when test with Mockito

Time:11-09

I'm testing a controller that needs a Autowired Service.

I read in many place (example Mockito: How to test my Service with mocking?) I need to do it like this

@RunWith(JUnitPlatform.class)
public class AdminControllerTest {

  @Mock
  private AdminService service;

  @InjectMocks
  private AdminController adminController;

  @Test
  public void registerUser() {
    Boolean resultReal = adminController.registerUser();
    assertTrue(resultReal);
  }
}

But it's fail and I see is because the adminController is null

Instead, if I create the controller like this

AdminController adminController = new AdminController();

It works, but then I can inject the mock.

Maybe I'm forgotten something

CodePudding user response:

Per the documentation for InjectMocks:

MockitoAnnotations.openMocks(this) method has to be called to initialize annotated objects. In above example, openMocks() is called in @Before (JUnit4) method of test's base class. For JUnit3 openMocks() can go to setup() method of a base class. Instead you can also put openMocks() in your JUnit runner (@RunWith) or use the built-in MockitoJUnitRunner.

Thus, either:

  1. call openMocks(this) somewhere before the test is run or
  2. Use @RunWith(MockitoJUnitRunner.class) on the class
  • Related