springboot(六):单元测试

1、引入依赖

pom.xml添加依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

在test/java目录下创建测试类:

2、创建启动类

在src/test/java下创建启动类ApplicationTest.java

package com.szl;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @author szl
 * @data 2018年6月30日 下午10:42:19
 *
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTest {

	@Test
	public void contextLoads(){
		
	}
}

3、Service测试

创建测试类,通过@Test进行单元测试,利用断言判断测试结果

package com.szl.service;

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;

import com.szl.entity.Customer;
import com.szl.service.CustomerService;

/**
 * 测试Service
 * @author szl
 * @data 2018年6月30日 下午10:32:10
 *
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class ServiceTest {

	@Autowired
	private CustomerService customerService;
	
	@Test
	public void getCustomerByMobileTest(){
		Customer customer = customerService.getCustomerByMobile("18829281000");
		Assert.assertEquals("信仰", customer.getCustomerName());
	}
}

4、接口测试

创建controller测试类,接口测试不同于Service测试,需要引入@AutoConfigureMockMvc,利用MockMvc进行测试
package com.szl.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;

/**
 * @author szl
 * @data 2018年6月30日 下午10:55:06
 *
 */
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ControllerTest {

	@Autowired
	private MockMvc mvc;
	
	@Test
	public void getCustomerByMobile() throws Exception{
		mvc.perform(MockMvcRequestBuilders.get("/customer/getCustomer?mobile=18829281000"))
		.andExpect(MockMvcResultMatchers.status().isOk());
//		.andExpect(MockMvcResultMatchers.content().string("abc"));
	}
}

5、总结

可以运行每一个测试方法,或者运行一个测试类,执行类中的所有测试方法
项目打包的时候会执行所有单元测试:mvn clean package
跳过测试:mvn clean package -D maven.test.skip=true

猜你喜欢

转载自blog.csdn.net/ynzz123/article/details/81007798