Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

java - Spring Boot MockMVC returning empty body with statuscode 200 when unit testing

I'm trying to test my microservice endpoint Get Payees using MockMvc to perform the get request. I've already set the behavior with mockito.when(), so whatever ID used in the request, it should return my response.

I have this test:

@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"));
    }

And this is my 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 annotation:

/**
 * 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 {}

This is what my console shows:

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 = []

------EDIT--------

Adding the ApiInterface example on how I use RequestMapping

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

For some reason, I always get empty body even with 200 status code. If you guys could help me... i would appreciate it. Thanks in advance.

question from:https://stackoverflow.com/questions/65909403/spring-boot-mockmvc-returning-empty-body-with-statuscode-200-when-unit-testing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If I understood well, your

private GetPayeesModule module;

in

public class PayeesApiControllerGetPayeesTest {

should be annotated with

@MockBean

and not with

@Autowired

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...