Spring Boot进阶之Web 2-7
****地址
单元测试
目录
- 测试service
- 测试API
测试service
- 测试代码如下
package com.imooc;
import com.imooc.domain.Girl;
import com.imooc.service.GirlService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author wdh
*/
@RunWith(SpringRunner.class)
//由于低层使用Junit测试需要加上如**解
@SpringBootTest
public class GirlServiceTest {
//注入需要测试的service
@Autowired
private GirlService girlService;
//测试方法上需要加上@Test注解
@Test
public void findOneTest() {
Girl girl = girlService.findOne(73);
//使用断言
Assert.assertEquals(new Integer(13), girl.getAge());
}
}
如何运行测试用例
当然可以利用idea更方便的创建测试方法
想测试那个方法就勾选哪个
生成的代码
package com.imooc.service;
import org.junit.Test;
/**
* @author wdh
*/
public class GirlServiceTest {
@Test
public void findOne() throws Exception {
}
}
测试API
在这里插入代码片package com.imooc.controller;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
/**
* API测试
* @author wdh
*/
@RunWith(SpringRunner.class)
@SpringBootTest
//需要使用MockMvc所以要加上这个注解
@AutoConfigureMockMvc
public class GirlControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void girlList() throws Exception {
//对/girls地址进行get方法调用andExpect后面加上期望返回的结果andExpect期望返回的Exception
mvc.perform(MockMvcRequestBuilders.get("/girls"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string("abc"));
}
}
当测试用例过多的时候(mvn)
可以再他会在打包的时候自动运行单元测试。
mvn clean package
打包的时候跳过单元测试
mvn clean package -Dmaven.test.skip=true