【问题标题】:How can I mock the service class in my Controller Test in Micronaut using JUnit5?如何使用 JUnit5 在 Micronaut 的控制器测试中模拟服务类?
【发布时间】:2019-10-20 06:08:57
【问题描述】:

我正在为我的 micronaut 应用程序中的控制器编写 JUnit 测试用例。控制器有一个 GET 端点,它调用我的服务类中的一个方法。我收到了NullPointerException,所以我假设我的服务类可能没有被正确地模拟,但是我不确定。我正在使用 @Mock (Mockito) 来提供服务。

我是否使用正确的注释来模拟服务层?我试图在谷歌上搜索,但它并没有给我太多的研究。谢谢。

@MicronautTest
public class FPlanControllerTest {

private static final String url = "dummy_url";

@Inject
FPlanService fplanService;

@Inject
@Client("/")
RxHttpClient client;

@Test
public void testGetLayout() {
    FPlanUrl expectedFPlanUrl = new FPlanUrl(url);
    when(fplanService.getLayoutUrl(Mockito.anyString(), Mockito.anyString()))
                .thenReturn(expectedFPlanUrl);
        FPlanUrl actualFPlanUrl = client.toBlocking()
                .retrieve(HttpRequest.GET("/layout/1000545").header("layoutId", "7"), FPlanUrl.class);
        assertEquals(expectedFPlanUrl , actualFPlanUrl);
    }

@MockBean(FPlanService.class)
    FPlanService fplanService() {
        return mock(FPlanService.class);
    }
}

我收到以下错误。

java.lang.NullPointerException at com.apartment.controller.FPlanControllerTest.testGetLayout(FPlanControllerTest.java:44)

【问题讨论】:

    标签: junit5 micronaut


    【解决方案1】:

    使用@MockBean (io.micronaut.test.annotation.MockBean)。

    文档 - https://micronaut-projects.github.io/micronaut-test/latest/guide/#junit5

    【讨论】:

    • 我尝试了“@MockBean”,但收到一条错误消息,指出此位置不允许使用注释。在指南中,当服务实现接口时使用了“@MockBean”。我的服务类没有实现任何接口。
    • 在纠正空指针异常后,我不得不使用“@MockBean”来注入我的服务层,因为它给了我一个缺少的 methodInvocationException。谢谢!
    【解决方案2】:

    我知道出了什么问题。这给出了一个NullPointerException,因为HTTP 响应期待一个String 而不是FPlanUrl 对象。正确的代码如下:

    @Test
    public void testGetLayout() {
        FPlanUrl expectedFPlanUrl = new FPlanUrl("http://dummyurl.com");
        when(fplanService.getLayoutUrl(Mockito.anyString(), Mockito.anyString()))
                .thenReturn(expectedFPlanUrl);
        Assertions.assertEquals("{\"url\":\"http://dummyurl.com\"}", client.toBlocking().retrieve(HttpRequest.GET("/layout/123").header("layoutId", "7"), String.class);
        verify(fplanService).getLayoutUrl("123","7");
    }
    

    【讨论】:

      【解决方案3】:

      试着模拟如下:-

      @MockBean(MyService.class)
      MyService myService() {
          return mock(MyService.class);
      }
      

      现在可以将服务注入为:-

      @Inject
      private MyService myService;
      

      在你的测试方法中使用:-

      @Test
      public void myServiceTest() {
          when(myService.foo(any())).thenReturn(any());
      
          MutableHttpResponse<FooResponse> response = controller.bar(new 
          MyRequest());
          Assertions.assertNotNull(response);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-03
        • 2013-04-16
        • 2021-12-23
        • 2018-08-12
        • 1970-01-01
        • 1970-01-01
        • 2016-01-09
        • 2019-10-31
        相关资源
        最近更新 更多