首页 文章

使用MockMvc进行集成和单元测试

提问于
浏览
0

根据文档,有两种方法可以做到这一点:

第一:

@RunWith(SpringRunner.class)
@WebAppConfiguration
@ContextConfiguration("my-servlet-context.xml")
public class MyWebTests {

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    // ...

}

此表单使用应用程序的实际上下文 .

第二种方式:

public class MyWebTests {

    private MockMvc mockMvc;

    @Mock
    private MyService myService;

    @InjectMocks
    private MyController myController;

    @Before
    public void setup() {
        // Process mock annotations
        MockitoAnnotations.initMocks(this);
        this.mockMvc = MockMvcBuilders.standaloneSetup(myController)
                .setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver()).build();
    }

    @Test
    public void testsForPost() throws Exception {

        Foo foo = new Foo();

        //given
        given(myService.findById(Matchers.anyLong())).willReturn(foo);

        //when
        this.mockMvc.perform((post("/foo")))
        //then
        .andExpect(status().isMethodNotAllowed())
        .andDo(print());
    }   
    ...
}

使用此方法,我不使用应用程序上下文 .

我的问题是,我可以将第一种形式视为集成测试吗?而第二次作为单元测试?

否则,什么是进行SpringMVC单元测试的最佳解决方案 .

1 回答

  • 1

    我也会考虑第一次集成测试,第二次是单元测试 .

    我认为编写良好的MVC控制器应该包含集成测试而不是单元测试 . 控制器应该只编排对映射器,服务,存储库等的调用 . 由于映射器,服务,存储库等应该用自己的单元测试来覆盖,因此通过单元测试控制器不会获得太多收益 .

    在这种情况下,集成测试更有 Value ,因为它测试控制器与其协调的组件之间的整个交互 . 使用像DBUnit这样的工具,写起来并不困难 .

相关问题