简体   繁体   English

Spring 启动集成测试返回空结果

[英]Spring boot intergration test returns empty result

I am trying to make intergration tests for my webflux controller, but the test are failing either on not set content-type or on empty content.我正在尝试为我的 webflux controller 进行集成测试,但测试在未设置内容类型或空内容时失败。 Controller class: Controller class:

@RestController
@RequiredArgsConstructor
@SecurityRequirement(name = "bearerAuth")
@Log4j2
public class OnboardingController {
    private final Service service;

    @GetMapping(value = "/organizationQuotas", produces = MediaType.APPLICATION_JSON_VALUE)
    public Flux<OrganizationQuota> getOrganizationQuotas() {
        return service.getAllOrganizationQuotas();
    }
}

Service class is a simple flux-returning service.服务 class 是一项简单的磁通返回服务。 Test class:测试 class:

@WebMvcTest(OnboardingController.class)
@RunWith(SpringRunner.class)
public class OnboardingControllerIT {

    @MockBean
    Service service;
    private EasyRandom easyRandom = new EasyRandom();

    @Autowired
    private MockMvc mockMvc;

    @Test
    @WithMockUser(authorities = {"..."})
    @DisplayName("Should List All organization quotas when GET request to /organizationQuotas")
    public void shouldReturnOrganizationQuotas() throws Exception {
        when(service.getAllOrganizationQuotas())
                .thenReturn(Flux.fromStream(easyRandom.objects(OrganizationQuota.class, 5)));

        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/organizationQuotas").accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isOk())
//                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(jsonPath("$.*", isA(ArrayList.class)))
                .andReturn();
    }
}

At this state the output looks like this:在这个 state output 看起来像这样:

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /organizationQuotas
       Parameters = {}
          Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json"]
             Body = null
    Session Attrs = {SPRING_SECURITY_CONTEXT=org.springframework.security.core.context.SecurityContextImpl@d1e9b4bb: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@d1e9b4bb:...}

Handler:
             Type = controller.OnboardingController
           Method = controller.OnboardingController#getOrganizationQuotas()

Async:
    Async started = true
     Async result = [OrganizationQuota{allowPaidServicePlans=true, ...}]

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

and it ends with exception它以异常结束

No value at JSON path "$.*"
java.lang.AssertionError: No value at JSON path "$.*"
...

I have these dependencies我有这些依赖项

    testImplementation 'org.jeasy:easy-random-randomizers:5.0.0'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.security:spring-security-test'

    testCompile 'io.projectreactor:reactor-test'

Security should work ok.安全应该可以正常工作。 I can see the async result that is correct but my matchers are not working with it.我可以看到正确的异步结果,但我的匹配器没有使用它。 The content type is not returned as well.也不返回内容类型。 Is it because of the async character of request?是因为请求的异步特性吗? How can I make it evaluate?我怎样才能让它评估? Thanks for help.感谢帮助。

I found it at howToDoInJava that testing async controller is different:我在howToDoInJava发现测试异步 controller 是不同的:

I had to use asyncDispatch method.我不得不使用asyncDispatch方法。 Form the referenced page, here is the example:形成引用的页面,这里是示例:

      @Test
      public void testHelloWorldController() throws Exception 
      {
            MvcResult mvcResult = mockMvc.perform(get("/testCompletableFuture"))
                              .andExpect(request().asyncStarted())
                              .andDo(MockMvcResultHandlers.log())
                              .andReturn();
             
            mockMvc.perform(asyncDispatch(mvcResult))
                        .andExpect(status().isOk())
                        .andExpect(content().contentTypeCompatibleWith("text/plain"))
                        .andExpect(content().string("Hello World !!"));
      }

now it works correctly.现在它可以正常工作了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM