前提:新建SpringBoot项目

1、Service测试

Service层测试就是常规测试,例如现在有一个HelloService:

@Service
public class HelloService {
    public String sayHello(String name){
        return "Hello " + name + " !";
    }
}

在idea工具中创建测试类快捷键Ctrl+Shift+T,具体测试代码如下:

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloServiceTest {

	@Autowired
	HelloService helloService;
	@Test
	public void contextLoads() {
		String hello = helloService.sayHello("Chen");
		Assert.assertThat(hello, Matchers.is("Hello Chen !"));//判断测试是否正确,绿色结果正确,黄色则是表示结果值错误
	}

}

运行测试类结果:

黄色表示期望值和实际值不匹配

2、Controller测试,这里需要使用到Mock测试

例如有如下Controller

@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello(String name){
        return "Hello "+ name+ " !";
    }
    @PostMapping("/book")
    public String addBook(@RequestBody Book book){
        return book.toString();
    }
}

涉及到的实体类:

public class Book {
    private Integer id;
    private String name;
    private String author;
    ...(get、set方法省略)
}

测试类代码:

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloControllerTest {

    @Autowired
    HelloService helloService;

    @Autowired
    WebApplicationContext wac;//模拟ServletContext环境
    MockMvc mockMvc;//声明MockMvc对象

    @Before
    public void before() {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();

    }

    @Test
    public void test1() throws Exception {
        MvcResult mvcResult = mockMvc.perform(
                MockMvcRequestBuilders
                        .get("/hello")//get请求方法
                        .contentType(MediaType.APPLICATION_FORM_URLENCODED)//请求内容类型
                        .param("name","Chen"))//参数
                .andExpect(MockMvcResultMatchers.status().isOk())//期望返回状态200
                .andDo(MockMvcResultHandlers.print())//指定打印信息
                .andReturn();//返回值
        System.out.println(mvcResult.getResponse().getContentAsString());
    }
    @Test
    public void test2() throws Exception {
        ObjectMapper om = new ObjectMapper();
        Book book = new Book();
        book.setAuthor("羅貫中");
        book.setName("三國演義");
        book.setId(1);
        String s = om.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());
    }
}

 

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐