目录
2、在src/test/java目录下创建MyTest.java:
1、引入test的starter依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2、在src/test/java目录下创建MyTest.java
:
@RunWith(SpringRunner.class)//JUnit运行使用Spring的测试支持。
@SpringBootTest(classes = {Application.class})// SpringApplication创建上下文并支持Spring Boot特性,指定启动类
@Slf4j
public class MyTests {
@Autowired
private Person person;
@Autowired
private HelloService helloService;
/**
* 测试注入
*/
@Test
public void test2() {
log.info("test hello 2");
// 使用断言
Assert.assertEquals(1, 1);
}
/**
* 测试注入
*/
@Test
public void test3() {
log.info("person={}", person);
log.info("helloService.getVal()={}", helloService.getVal());
}
@Before
public void testBefore() {
System.out.println("before");
}
@After
public void testAfter() {
System.out.println("after");
}
}
tip:断言核心方法
assertArrayEquals(expecteds, actuals) 查看两个数组是否相等。
assertEquals(expected, actual) 查看两个对象是否相等。类似于字符串比较使用的equals()方法
assertNotEquals(first, second) 查看两个对象是否不相等。
assertNull(object) 查看对象是否为空。
assertNotNull(object) 查看对象是否不为空。
assertSame(expected, actual) 查看两个对象的引用是否相等。类似于使用“==”比较两个对象
assertNotSame(unexpected, actual) 查看两个对象的引用是否不相等。类似于使用“!=”比较两个对象
assertTrue(condition) 查看运行结果是否为true。
assertFalse(condition) 查看运行结果是否为false。
assertThat(actual, matcher) 查看实际值是否满足指定的条件
fail() 让测试失败
异常处理
1、报错:java.lang.IllegalStateException Unable to find a @SpringBootConfiguration
解决方案:
将包名改为与其他分支一样的路径。
2、报错:@Test is not an annotation type
测试类为Test.java,因为这个Test类导致了冲突,只要把这个类名改成其他的就好了
参考:https://blog.youkuaiyun.com/liubenlong007/article/details/85398181