IDEA中单元测试

Intellij IDEA中添加JUnit单元测试

springboot(16)Spring Boot使用单元测试

Spring Boot 进行测试提示 TestContextAnnotationUtils 错误

创建存放测试文件的目录

需要在project下新建一个文件夹,用于存放自动生成的测试.java文件,比如 Factorial.java类对应的 FactorialTest.java文件的存放位置
这里我新建一个目录,和scr目录同级,如图
image-20200410001446930

接下来需要将这个文件夹,设置为存放生成测试文件的目录
打开项目设置
image-20200410001551607

image-20200410001659216

使用JUnit

当想要为当前类添加测试代码,只需要在当前类中使用Alt+inset(或者导航栏中点击Code-Generator)快捷键,选择JUnit-JUnit4,就会自动生成当前类的测试类:

插件默认会测试所有方法,使用快捷键Ctrl+Shift+T可以选择性的测试部分方法,非常的方便:

在输出路径中就可以看到自动生成的测试类,含有需要测试的方法,接下来就可以编写代码对类进行测试啦

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
package com.dudu.service;
import com.dudu.domain.LearnResource;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.hamcrest.CoreMatchers.*;

@RunWith(SpringRunner.class)
@SpringBootTest
public class LearnServiceTest {

    @Autowired
    private LearnService learnService;

    @Test
    public void getLearn(){
        LearnResource learnResource=learnService.selectByKey(1001L);
        Assert.assertThat(learnResource.getAuthor(),is("嘟嘟MD独立博客"));
    }
}

如果运行报错,去掉jar包的版本号:

Spring Boot 进行测试提示 TestContextAnnotationUtils 错误

Spring Boot 进行测试提示 TestContextAnnotationUtils 错误

原文地址:https://www.cnblogs.com/libin6505/p/15701458.html