有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

junit JAVA获取空的MockHttpServletResponse:body。。不过是200

I have written unit test cases for a spring rest controller but I'm getting blank response body.

下面是我的控制器类

@RestController
@RequestMapping("/v2")

public class controller {

@Autowired

Service service;

@RequestMapping(value="/health",method=RequestMethod.POST)

public String postRequest(@RequestHeader @NotNull@NotBlank String 
transID) {

 return service.getTest(transID); }
}

下面是我的服务课

 @Component
 public class Service {

 public String getTest(@NotNull String transid) {

 return "Hello World Test";
  } }

下面是我的单元测试课。我已经使用mockito编写了这个方法的单元测试用例

 class UnitTest {
 @InjectMocks

 controller controllerUse;
 @Mock

 Service service;
 @Autowired

  MockMvc mockMvc;

  @BeforeEach

  public void test() {

  MockitoAnnotations.initMocks(this);

  mockMvc=MockMvcBuilders.standaloneSetup(controllerUse).build();

   }

   @Test

   public void confirmTest() throws Exception {

   mockMvc.perform(post("/v2/health")

   .header("transID","ABC"))

   .andExpect(status().isOk())

   .andDo(print())

   .andReturn();   }

    }

输出:

MockHttpServletResponse:

Status = 200

Error message = null

Headers = []

Content type = null

Body =

Forwarded URL = null

Redirected URL = null

Cookies = []

我得到的回复代码是200。但是得到一个空白的身体。我错过了什么?这是为SpringRest控制器编写单元测试用例的标准方法吗


共 (1) 个答案

  1. # 1 楼答案

    因为您正在注入mockbean服务,所以需要使用预期的响应来模拟方法

    下面是使用JUnit5和Spring引导测试工件的示例代码,但您也可以使用标准Spring测试模块实现相同的功能

    @WebMvcTest(SampleController.class)
    class SampleControllerTest {
    
        @MockBean
        Service service;
        @Autowired
        private MockMvc mockMvc;
    
        @Test
        public void confirmTest() throws Exception {
    
            when(service.getTest("ABC")).thenReturn("Hello World");
    
            mockMvc.perform(post("/v2/health")
    
                                .header("transID", "ABC"))
    
                   .andExpect(status().isOk())
                   .andDo(print())
                   .andReturn();
        }
    }