文章目录
1. 添加Controller
新建Spring Boot工程,新建IndexController.java:
/**
* Author: Huchx
* Date: 2021/2/3 11:00
*/
@RestController
public class IndexController {
@RequestMapping("/")
public String index(){
return "Hello World";
}
}
1. MockMvc
新建测试类:
/**
* Author: Huchx
* Date: 2021/2/3 11:01
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MockMvcIndexTest {
@Autowired
MockMvc mockMvc;
@Test
public void index() throws Exception {
this.mockMvc.perform(get("/")).andExpect(status().isOk())
.andExpect(content().string("Hello World"));
}
}
2. WebTestClient
2.1 添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
2.2. 测试类:
/**
* Author: Huchx
* Date: 2021/2/3 11:36
*/
@RunWith(SpringRunner.class)
@SpringBootTest(properties = "spring.main.web-application-type=reactive")
@AutoConfigureWebTestClient
public class WebClientIndexTest {
@Autowired
private WebTestClient webTestClient;
//或者可以绑定到Controller
//private WebTestClient webClient = WebTestClient.bindToController(IndexController.class).build();
@Test
public void index() throws Exception {
this.webTestClient.get().uri("/").exchange().expectStatus().isOk()
.expectBody(String.class).isEqualTo("Hello");
}
}
3. Random Port
添加注释@SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
以随机端口启动服务器。
编写测试类:
/**
* Author: Huchx
* Date: 2021/2/3 13:41
*/
@RunWith(SpringRunner.class)
@SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = "spring.main.web-application-type=reactive")
@AutoConfigureWebTestClient
public class RandomPortIndexTest {
@Autowired
private WebTestClient webTestClient;
@Autowired
private TestRestTemplate restTemplate;
// @LocalServerPort 注入实际使用的端口
@LocalServerPort
int port;
@Before
public void beforeTest(){
System.out.println("------------实际使用的端口为:"+port+"-----------");
}
@Test
public void indexByWebClient(){
this.webTestClient.get().uri("/").exchange().expectStatus().isOk()
.expectBody(String.class).isEqualTo("Hello World");
}
@Test
public void indexByRestTemplate(){
String str = this.restTemplate.getForObject("/",String.class);
assertThat(str).isEqualTo("Hello World");
}
}
启动服务后,端口号如图:
4. JsonTest
- 新建Pojo类
/**
* Author: Huchx
* Date: 2021/2/3 14:57
*/
public class UserPojo {
private String name;
private int age;
public UserPojo() {
}
public UserPojo(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
- 新建测试类
/**
* Author: Huchx
* Date: 2021/2/3 14:54
*/
@RunWith(SpringRunner.class)
@JsonTest
public class JsonObjTest {
private JacksonTester<UserPojo> json;
@Before
public void setup() {
ObjectMapper objectMapper = new ObjectMapper();
JacksonTester.initFields(this, objectMapper);
}
@Test
public void testWriteJson() throws IOException {
UserPojo object = new UserPojo("huchx",26);
//判断是否存在字段,@.name不知道什么写法
assertThat(json.write(object)).hasJsonPathStringValue("@.name");
//判断值是否包含某项
assertThat(json.write(object)).extractingJsonPathStringValue("name")
.isEqualTo("huchx");
}
@Test
public void testParseJson() throws IOException {
String jsonStr = "{\"name\":\"huchx\",\"age\": 26}";
assertThat(json.parseObject(jsonStr)).isEqualTo(new UserPojo("huchx",26));
assertThat(json.parseObject(jsonStr).getName()).isEqualTo("huchx");
}
}
5. WebMvcTest
- Controller
/**
* Author: Huchx
* Date: 2021/2/3 15:41
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService;
@RequestMapping("info")
public UserPojo info(){
return userService.detail();
}
}
- Service
/**
* Author: Huchx
* Date: 2021/2/3 15:43
*/
@Service
public class UserService {
public UserPojo detail(){
return new UserPojo("huchx",26);
}
}
- Test
/**
* Author: Huchx
* Date: 2021/2/3 15:56
*/
@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class MyWebMvcTest {
@Autowired
MockMvc mockMvc;
@MockBean
UserService userService;
@Test
public void userInfo() throws Exception {
given(userService.detail()).willReturn(new UserPojo("huchx",25));
MvcResult result = this.mockMvc.perform(get("/user/info"))
.andExpect(status().isOk())
.andReturn();
Assert.assertNotNull(result.getResponse().getContentAsString());
}
}
6 Data JPA Test
代码:https://github.com/huiyiwu/spring-boot-simple/spring-boot-data-jpa
配置好Spring Data JPA,文档参考Spring Boot Data JPA
新建测试类:
/**
* Author: Huchx
* Date: 2021/2/8 9:44
*/
@RunWith(SpringRunner.class)
@DataJpaTest
//引入需要使用的配置类,此处不知道为什么导入主类就可以,其他类就报异常了
@ContextConfiguration(classes = DataJpaApp.class)
//使用真实数据库进行测试
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class UserTest {
@Autowired
TestEntityManager entityManager;
@Autowired
UserDao userDao;
@Before
public void setUp(){
MUserEntity userEntity = new MUserEntity(108,"DataJpaTest",1);
userDao.save(userEntity);
}
@Test
public void testUser(){
Optional<MUserEntity> mUserEntity = userDao.findById(108);
assertNotNull(mUserEntity.get());
}
}
7. JDBC Test
代码:https://github.com/huiyiwu/spring-boot-simple/spring-boot-jdbctemplate
关于JDBCTemplate的配置可参考Spring Boot JDBCTemplate
/**
* Author: Huchx
* Date: 2021/2/8 9:44
*/
@RunWith(SpringRunner.class)
@JdbcTest
@ContextConfiguration(classes = JdbcTemplateApp.class)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class UserTest {
JdbcTemplate jdbcTemplate;
@Before
public void setUp(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/spring_boot?serverTimezone=UTC");
dataSource.setUsername("root");
dataSource.setPassword("123456");
this.jdbcTemplate = new JdbcTemplate(dataSource);
// String sql = "insert into m_jdbc_template (id,name) values (null ,?)";
// jdbcTemplate.update(sql,"JdbcTest");
}
@Test
public void testUser(){
String sql = "Select name from m_jdbc_template where id=120";
String userName = jdbcTemplate.queryForObject(sql,String.class);
assertNotNull(userName);
}
}