spring-boot-单元测试参数数
简单案例
@RunWith(Parameterized.class)
public class ParameterTest {
// 2.声明变量存放预期值和测试数据
private String firstName;
private String lastName;
//3.声明一个返回值 为Collection的公共静态方法,并使用@Parameters进行修饰
@Parameterized.Parameters
public static List<Object[]> param() {
// 这里我给出两个测试用例
return Arrays.asList(new Object[][]{{"Mike", "Black"}, {"Cilcln", "Smith"}});
}
//4.为测试类声明一个带有参数的公共构造函数,并在其中为之声明变量赋值
public ParameterTest(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// 5. 进行测试,发现它会将所有的测试用例测试一遍
@Test
public void test() {
String name = firstName + " " + lastName;
System.out.println(name);
assertThat("Mike Black", is(name));
}
}
参数化在 测试controller 中的应用
@RunWith(Parameterized.class)
@SpringBootTest
public class LearnController14Test {
@Autowired
private WebApplicationContext wac;
private MockMvc mvc;
private MockHttpSession session;
public Long id;
public String title;
public LearnController14Test(Long id, String title) {
super();
this.id = id;
this.title = title;
}
/**
* 这些参数,都会测试一遍
*
* @return
*/
@Parameterized.Parameters
public static List<Object[]> data() {
return Arrays.asList(new Object[][]{{999L, "Black"}, {997L, "Smith"}});
}
@Before
public void setupMockMvc() throws Exception {
//借助TestContextManager来实现上下文注入
TestContextManager testContextManager = new TestContextManager(getClass());
testContextManager.prepareTestInstance(this);
//初始化MockMvc对象
mvc = MockMvcBuilders.webAppContextSetup(wac).build();
//构建session
session = new MockHttpSession();
User user = new User("root", "root");
//拦截器那边会判断用户是否登录,所以这里注入一个用户
session.setAttribute("user", user);
}
/**
* 获取教程测试用例
* <p>
* get 请求
*
* @throws Exception
*/
@Test
public void qryLearn() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/learn/resource/" + id + "?title=" + title)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.accept(MediaType.APPLICATION_JSON_UTF8)
.session(session)
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print());
}
}
博客所有内容仅供自已学习和学习过程的记录,如有侵权,请联系我删除!!!