1.创建springboot项目
引入spring web依赖就行
2.service的测试
编写service
@Service
public class HelloService {
public String sayHello(String s){
return "hello "+ s;
}
}
编写测试调用service
@Autowired
HelloService helloService;
@Test
void contextLoads() {
String s = helloService.sayHello("chenyp");
}
3.controller测试
1.编写2个controller分别返回string和json对象
@GetMapping("/hello")
public String sayHello(String name){
return "hello "+name;
}
@PostMapping("/book")
public Book sayHello2(@RequestBody Book book){
return book;
}
2.编写book类
private Integer id;
private String name;
private String author;
//get set方法
//tostring
3.测试方法
@Autowired
WebApplicationContext wac;
MockMvc mockMvc;
@BeforeEach
void before(){
mockMvc= MockMvcBuilders.webAppContextSetup(wac).build();
}
返回string的方法
@Test
void test1() throws Exception {
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.get("/hello")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("name", "chenyp"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
System.out.println(mvcResult.getResponse().getContentAsString());
}
返回json对象方法
@Test
void test2() throws Exception {
Book book=new Book();
book.setId(9);
book.setAuthor("罗贯中");
book.setName("三国演义");
String s=new ObjectMapper().writeValueAsString(book);
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.post("/book")
.contentType(MediaType.APPLICATION_JSON)
.content(s))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
System.out.println(mvcResult.getResponse().getContentAsString());
}
4.json测试
//在test类同级文件下写入json文件
{"id": 9,"name": "三国演义","author": "罗贯中"}
<resources>
<resource>
<directory>src/test/java</directory>
<includes>
<include>**/*.json</include>
</includes>
</resource>
</resources>
测试
@JsonTest
class Test2ApplicationTests {
@Autowired
JacksonTester<Book> jacksonTester;
//序列化
@Test
void contextLoads() throws Exception {
Book book=new Book();
book.setId(9);
book.setAuthor("罗贯中");
book.setName("三国演义");
Assertions.assertThat(jacksonTester.write(book))
.isEqualToJson("book.json");
System.out.println("三国演义");
}
//反序列化
@Test
void testDeserialize() throws IOException {
String content ="{\"id\": 9,\"name\": \"三国演义\",\"author\": \"罗贯中\"}";
Assertions.assertThat(jacksonTester.parseObject(content).getName())
.isEqualTo("三国演义");
}
}