使用 Mockito 测试时为空控制器

Null controller when test with Mockito

我正在测试需要自动连接服务的控制器。

我看了很多地方(例如Mockito: How to test my Service with mocking?)我需要这样做

@RunWith(JUnitPlatform.class)
public class AdminControllerTest {

  @Mock
  private AdminService service;

  @InjectMocks
  private AdminController adminController;

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

但它失败了,我看到是因为 adminController 为空

相反,如果我像这样创建控制器

AdminController adminController = new AdminController();

它有效,但我可以注入模拟。

也许我忘记了什么

根据 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.

因此,要么:

  1. 在测试 运行 或
  2. 之前的某处调用 openMocks(this)
  3. 在 class
  4. 上使用 @RunWith(MockitoJUnitRunner.class)