简单使用流程:
1、依赖引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2、编写测试基础类
import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringRunner.class)
@SpringBootTest
//由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration。
@WebAppConfiguration
public class El3kjTests {
@Before
public void init() {
System.out.println("开始测试-----------------");
}
@After
public void after() {
System.out.println("测试结束-----------------");
}
}
3、编写功能测试类
public class CkpddTest extends El3kjTests{
@Autowired
private ICkpddService pandianService;
@Test
public void testSearchIndex() throws Exception {
Assert.assertSame("判断位置为首位",1,pandianService.detailSearch(new Term()));
}
}
点@Test 下一行前面的箭头就可以进行测试了
功能整理:
1、打包测试(将多个测试类打包成一个测试类)
@RunWith(Suite.class)
@Suite.SuiteClasses({EntFileTest.class,EntFileTest2.class})
public class TestSuits {
//不用写代码,只需要注解即可
}
2、忽略测试
@Ignore("not ready yet")
或者
@Disabled("该测试用例不再执行,直到编号为 43 的 bug 修复掉")
3、异常测试
@Test
void factIllegalArgumentLambda() {
assertThrows(IllegalArgumentException.class, () -> {
Factorial.fact(-2);
});
}
4、条件测试
1)操作系统不同
@Test
@EnabledOnOs(MAC)
void onlyOnMacOs() {
// ...
}
@TestOnMac
void testOnMac() {
// ...
}
@Test
@EnabledOnOs({ LINUX, MAC })
void onLinuxOrMac() {
// ...
}
@Test
@DisabledOnOs(WINDOWS)
void notOnWindows() {
// ...
}
2)JRE不同
@Test
@EnabledOnJre(JAVA_8)
void onlyOnJava8() {
// ...
}
@Test
@EnabledOnJre({ JAVA_9, JAVA_10 })
void onJava9Or10() {
// ...
}
@Test
@EnabledForJreRange(min = JAVA_9, max = JAVA_11)
void fromJava9to11() {
// ...
}