SpringBoot-junit单元测试

目录

1、引入test的starter依赖

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.csdn.net/liubenlong007/article/details/85398181

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值