尝试通过 AutoConfigureMockMvc 自动配置时集成测试失败

2023-12-19

我正在为控制器端点编写一个简单的测试。

当我执行以下操作时效果很好。

@SpringBootTest
@ContextConfiguration(classes = {
        HomeController.class,
        HomeControllerTest.class
})
class HomeControllerTest {

    @Autowired
    private WebApplicationContext webApplicationContext;

    private static final String URL = "/a";
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Test
    public void test() throws Exception {

        MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();

        Request request = new Request();

        mockMvc.perform(post(URL)
                .contentType("application/json")
                .content(objectMapper.writeValueAsString(request))
                .andExpect(status().isOk());
    }
}

但我不想创建 mockMvc 并关注 webApplicationContext。
因此,尝试使用@AutoConfigureMockMvc而是如下。
但这行不通。因以下错误而失败。

java.lang.AssertionError:预期状态: 但为: 预期 :200 实际 :403

我究竟做错了什么?

我的尝试引发了上述错误。

@SpringBootTest
@AutoConfigureMockMvc // using this annotation instead
@ContextConfiguration(classes = {
        HomeController.class,
        HomeControllerTest.class
})
class HomeControllerTest {

    // wiring mockMvc instead
    // no webApplicationContext autowired
    @Autowired
    private MockMvc mockMvc;

    private static final String URL = "/a";
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Test
    public void test() throws Exception {

        Request request = new Request();

        mockMvc.perform(post(URL)
                .contentType("application/json")
                .content(objectMapper.writeValueAsString(request))
                .andExpect(status().isOk());
    }
}

尝试像这个例子一样创建测试,效果更好。

 @SpringBootTest
 @AutoConfigureMockMvc
 public class HomeControllerTest 

    private ObjectMapper mapper;
    private MyControler myController;
    private ServiceInSideConttroler service;
    add your atributes
    
    @Before
    public init(){
    this.mapper = new ObjectMapperConfiguration().mapper();
    this.service = mock(ServiceInSideConttroler.class);
    this.myController = new MyController(service);
    }

    @Test
    public void test() throws Exception {
          // exemple how mock reponse from any service or repository.
         when(service.findById(any(Long.class)))
          .thenReturn(Optional.of(budget));

       Object resp =  myController.save(mockben());
         ...... 
         aserts(resp)
    }
}

请记住,要进行这样的测试,不要在属性中使用 @Authwired,只能在用 @service、@componet、@controller 等注释的类的构造函数中使用。也就是说,任何由 Spring 控制的类将使用dependecia注射。还要记住断言你的回应。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

尝试通过 AutoConfigureMockMvc 自动配置时集成测试失败 的相关文章

随机推荐