首先,springboot框架在搭建的时候默认引入的是junit包,所以在所有的@Test使用的是junit下的,相比较我个人而言,更习惯与使用testng,testng使用@DataProvider在进行接口测试时候更加方便我们去处理和测试的数据,在执行测试类和方法中提供更多的注解,使用起来更加灵活和方便
image.png
一:在pom.xml下引入我们testng相关jar包
<!--TestNG-->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.14.3</version>
<scope>test</scope>
</dependency>
执行我们的测试类
package com.think.springboard.service;
import com.think.springboard.entity.Url;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
public class Testng {
@Autowired
UrlService urlService;
@Test
public void test(){
Url url=null;
List<Url> list=urlService.getUrls("1");
if (list!=null) {
url = list.get(0);
System.out.println(url.getUrlPlace());
}
}
}
在执行这段断码的时候可以会发现控制台报错,无法正常输出结果,拨错信息如下
image.png
报错可以发现,引入testng框架后默认是按照testng来执行的,但是我们在上段代码中依然是引入的junit下的测试方法,于是我们修改我们的test方法的引入类,如下
image.png
确保你的@Test是从这个包引入,对应import也是正确的,然后在执行你的测试代码
image.png
这个时候发现代码执行依然是报错的
我们的解决方案就在我们这个测试类上继承AbstractTestNGSpringContextTests类
image.png
继承该类后,可以正常使用testng执行我们的测试方法
AbstractTestNGSpringContextTests:springboot在集成testng时候,测试类只有继承了该类才拥有注入实例的能力
官方文档说明:https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/testing.html