SpringMVC测试

Spring提供了测试MVC的框架。

服务端测试(Server-Side Tests)

主要分为几个步骤:

  • 需要注解@WebAppConfiguration

  • 注入WebApplicationContext

  • MockMvc初始化

  • 执行Request请求

  • 定义期望值



@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration("src/main/webapp")
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
public class BaseControllerTest {
    @Autowired
    private WebApplicationContext wac;
    private MockMvc mockMvc;
    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
        //初始化具体某个controller
//        this.mockMvc = MockMvcBuilders.standaloneSetup(new CashierOrderController()).build();
    }
    @Test
    public void testBase() throws Exception {
        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/api/")
                .accept(MediaType.APPLICATION_JSON)
                .param("foo", "bar"))
                .andExpect(status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
    }
}

客服端测试(Client-Side REST Tests)

目标是模拟一下响应response, 定义期望值


public class SampleTests {
    private MockRestServiceServer mockServer;
    private RestTemplate restTemplate;
    @Before
    public void setup() {
        this.restTemplate = new RestTemplate();
        this.mockServer = MockRestServiceServer.bindTo(this.restTemplate).ignoreExpectOrder().build();
    }
    @Test
    public void performGet() throws Exception {
        String responseBody = "{\"name\" : \"Ludwig van Beethoven\", \"someDouble\" : \"1.6035\"}";
        this.mockServer.expect(requestTo("/composers/42")).andExpect(method(HttpMethod.GET))
            .andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON));
        @SuppressWarnings("unused")
        Person ludwig = this.restTemplate.getForObject("/composers/{id}", Person.class, 42);
        // We are only validating the request. The response is mocked out.
        // hotel.getId() == 42
        // hotel.getName().equals("Holiday Inn")
        this.mockServer.verify();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值