springboot的测试

测试代码

以下是1.3版本的测试

1
2
3
4
5
6
7
8
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class)
public class BaseTest {
}

以下是1.4.0 版本的测试

1
2
3
4
5
6
7
8
9
10
11
12
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import javax.servlet.ServletContext;
@RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持!
@SpringApplicationConfiguration(classes = App.class) // 指定我们SpringBoot工程的Application启动类
@WebAppConfiguration
public class BaseTest {
}

MockMVC测试

调用方法之前,获取登录后session。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
private MockHttpSession session;
@Before
public void setupMockMvc() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
getLoginSession("hfy", "111111");
}
// 获取登入信息session
private void getLoginSession(String name, String pwd) throws Exception {
MvcResult result = this.mockMvc
.perform(post("/index.action")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("loginname", name)
.param("password", pwd))
.andReturn();
Assert.assertEquals("main/index", result.getModelAndView().getViewName());
this.session = (MockHttpSession) result.getRequest().getSession();
}
@Test
public void testPerson() throws Exception {
MockHttpServletRequestBuilder builder = post("/person/editPerson.action")
.param("personId", "1")
.param("name", "xx").session(session);
MvcResult mvcResult = mockMvc.perform(builder).andReturn();
System.out.println(mvcResult.getResponse().getContentAsString());
Map map = new ObjectMapper().readValue(mvcResult.getResponse().getContentAsString(), Map.class);
Assert.assertEquals("success", map.get("result"));
}

参考

Spring Boot应用的测试——Mockito
Spring MVC 测试 | 模拟提交表单
Junit测试Controller(MockMVC使用),传输@RequestBody数据解决办法
sonar + jacoco + mockMvc 模拟session 用户登录 配合SpringSecurity 权限 快速测试代码覆盖率

文章目录
  1. 1. MockMVC测试
  2. 2. 参考
|