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

xn1cxnb4  于 2021-07-16  发布在  Java
关注(0)|答案(1)|浏览(432)

我正在为控制器端点编写一个简单的测试。
当我做以下事情时,它工作得很好。

@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>应为: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());
    }
}
taor4pac

taor4pac1#

试着像这样创建一个例子,它是更好的测试。

@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注入。还记得你的回复。

相关问题