三、整合Junit单元测试

1、导入依赖jar包

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.2.0.RELEASE</version>
        <scope>test</scope>
    </dependency>
    
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>

<scope>test</scope>表示打包时不会加入这些jar包

2、注解

  • @RunWith:用于指定Junit运行环境,时Junit提供给其他框架测试环境接口扩展,为了便于使用spring的依赖注入,spring提供了SpringJunit4ClassRunner作为Junit测试环境
  • @ContextConfiguration导入配置文件,支持xml,JavaConfig配置类
    具体配置代码如下:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.neuedu.service.TestService;
import com.neuedu.test.Appconfig;

@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(locations= {"classpath:applicationContext.xml"})
@ContextConfiguration(classes=Appconfig.class)
public  class TestController {
    @Autowired
    private TestService testService;

    public void setTestService(TestService testService) {
        this.testService = testService;
    }
    @Test
    public void test() {
        testService.test();
    }
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容