簡體   English   中英

Spring 引導 MockMVC 在單元測試時返回空體,狀態碼為 200

[英]Spring Boot MockMVC returning empty body with statuscode 200 when unit testing

我正在嘗試使用 MockMvc 測試我的微服務端點 Get Payees 來執行獲取請求。 我已經用 mockito.when() 設置了行為,所以無論請求中使用什么 ID,它都應該返回我的響應。

我有這個測試:

@ControllerTest
@AutoConfigureMockMvc
public class PayeesApiControllerGetPayeesTest {

    private static final String ACCOUNTS_URI = "/payees";
    
    @Autowired
    private MockMvc mvc;
    @Autowired
    private GetPayeesModule module;
    
    @Test
    public void testGetPayees() throws Exception {
        when(module.execute(
                anyString(),
                anyInt(),
                anyInt(),
                anyString(),
                anyString(),
                anyString(),
                anyString(),
                anyString(),
                anyString()))
                .thenReturn(
                        ResponseEntity.ok()
                                .header(X_V_HEADER, X_V_VERSION)
                                .header(X_FAPI_INTERACTION_ID_HEADER, UUID.randomUUID().toString())
                                .body(
                                        new ResponsePayee()
                                                .data(
                                                        new PayeeData()
                                                                .addPayeesItem(
                                                                        new PayeeDetails()
                                                                                .id(35L)
                                                                                .type(PayeeType.DOMESTIC)
                                                                                .fullName("Robert Doe")
                                                                                .description("My brother")
                                                                                .bsb("010-147")
                                                                                .accountNumber("123456789")))));
        
        mvc.perform(
                get(ACCOUNTS_URI)
                        .param("userId", "1")
                        .accept(MediaType.APPLICATION_JSON)
                        .header(X_V_HEADER, X_V_VERSION)
                        .with(jwtWithAccountsBasicReadPermissionAndBankClientRole()))
                .andExpect(status().isOk())
                .andExpect(content().string("DOMESTIC"));
    }

這是我的 Controller:

@Controller
@Validated
@RequiredArgsConstructor
public class PayeesApiController implements PayeesApiInterface {

  private final GetPayeesModule getPayeesModule;
  private final CreatePayeesModule createPayeesModule;

  @Override
  public ResponseEntity<ResponsePayee> getPayees(
      String userId,
      Integer page,
      Integer pageSize,
      String xRequestId,
      String xCorrelationContext,
      String xCorrelationId,
      String xFapiAuthDate,
      String xFapiCustomerIpAddress,
      String xCdsClientHeaders) {
    return getPayeesModule.execute(
        userId,
        page,
        pageSize,
        xRequestId,
        xCorrelationContext,
        xCorrelationId,
        xFapiAuthDate,
        xFapiCustomerIpAddress,
        xCdsClientHeaders);
  }

@Controller 注解:

/**
 * Meta-annotation (annotation of annotations) to group Spring's annotations for testing web slice.
 */
@WebMvcTest()
@ActiveProfiles("test")
@Import(ControllerTestConfiguration.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface ControllerTest {}

這是我的控制台顯示的內容:

2021-01-26 18:56:58.010  INFO 17428 --- [           main] c.m.s.o.HttpServletLogService            : REQUEST m:[GET], p:[/payees], q:[null], h:[{empty}], b:[{empty}]

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /payees
       Parameters = {userId=[1]}
          Headers = [Accept:"application/json", x-v:"1"]
             Body = <no character encoding set>
    Session Attrs = {}

Handler:
             Type = com.marlo.payees.api.PayeesApiController
           Method = com.marlo.payees.api.PayeesApiController#getPayees(String, Integer, Integer, String, String, String, String, String, String)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

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

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [X-Correlation-Id:"f7d29ced-1ddc-4788-93fb-ba6655da412d", 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 = []

- - - 編輯 - - - -

添加關於我如何使用 RequestMapping 的 ApiInterface 示例

@RequestMapping(
      value = "/payees",
      produces = {"application/json"},
      method = RequestMethod.GET)
  default ResponseEntity<ResponsePayee> getPayees

出於某種原因,即使有 200 個狀態碼,我也總是得到空的身體。 如果你們能幫助我...我將不勝感激。 提前致謝。

如果我理解得很好,你的

private GetPayeesModule module;

public class PayeesApiControllerGetPayeesTest {

應該用

@MockBean

而不是

@Autowired

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM