TestNG系列:
TestNG和Junit4的参数化测试对比
TestNG运行指定测试套件
TestNG整合ReportNG
TestNG参数化测试实战
TestNG+Spring/Spring Boot整合
使用TestNG替代Junit作为单测框架,如何和Spring/Spring Boot整合?
Spring+TestNG+Maven整合:
1.引入spring依赖:
spring-core/spring-context/spring-beans/spring-test
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
2.引入testng依赖:
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.8</version>
<scope>test</scope>
</dependency>
3.测试类增加1条注解
@ContextConfiguration(locations = "classpath:applicationContext.xml")
并继承AbstractTestNGSpringContextTests
,范例如下:
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class BaseTest extends AbstractTestNGSpringContextTests{
@Test
public void testMethods()
{
......
}
}
4.如果spring的配置没有使用xml,而是通过代码配置,第3步需要做下调整:
- 举例通过代码配置spring(效果和xml配置是相同的):
@Configuration
public class SpringConfig {
@Bean(name = "xxxBean", initMethod = "init")
public XxxBean xxxBean() {
......
}
}
- 代码配置spring情况下,没有xml配置文件,测试类:
@ContextConfiguration(classes = {SpringConfig.class})
public class BaseTest extends AbstractTestNGSpringContextTests{
@Test
public void testMethods()
{
......
}
}
Spring换成Spring Boot:
Spring Boot对Junit4的支持比TestNG更好,但是如果坚持用TestNG的话可以参考spring-boot-sample-testng
1.引入spring-boot依赖:
引入测试依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
2.引入TestNG依赖:
<!--TestNG-->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<scope>test</scope>
</dependency>
3.测试代码添加@SpringBootTest注解
@SpringBootTest
public class SampleTestNGApplicationTests extends AbstractTestNGSpringContextTests {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void testHome() throws Exception {
......
}
}
@SpringBootTest
可以通过classes属性指定Spring配置类,如果不指定,会自动查找有@SpringBootApplication
或者SpringBootConfiguration
的类作为Spring配置类。
@SpringBootTest(classes = {Application.class})
public class SampleTestNGApplicationTests extends AbstractTestNGSpringContextTests {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void testHome() throws Exception {
......
}
}
@SpringBootApplication(scanBasePackages = {"xxx.xxx.xxx"})
public class Application{
}