Date-05-springs中使用Junit

一.IDEA 创建 JUnit

IDEA 下创建 JUnit,需要首先安装JUnit插件,步骤如下:
【File -> settings -> Plugis -> Browse repositories ->输入JUnit ->选择JUnit Generator V2.0 安装 ->重启IDEA】


image.png

二.JUnit的使用

1.在程序中引入spring-test.jar

<!--junit测试依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.0.10.RELEASE</version>
      <scope>test</scope>
    </dependency>

2.建一个类生成构造方法

public class Max {
    private int a;
    private int b;

    public Max(int a, int b) {
        this.a = a;
        this.b = b;
    }
    public int getMax(){
        return a>b?a : b;
    }
}

3.在bean配置文件中添加依赖注入

   <bean id="max" class="com.spring.quickstart.Max">
        <constructor-arg name="a" value="5"/>
        <constructor-arg name="b" value="3"/>
    </bean>

4.IDEA中ctrl+shift+T选择create new Test,Test_library选择Junit4,勾选需要测试的方法然后ok
image
5.在生成的测试类外添加注解
  • 注:@RunWith:用于指定junit运行环境,是junit提供给其他框架测试环境接口扩展,为了便于使用spring的依赖注入,spring提供了org.springframework.test.context.junit4.SpringJUnit4ClassRunner作为Junit测试环境
    @ContextConfiguration({"classpath:applicationContext.xml","classpath:spring/buyer/applicationContext-service.xml"})
    导入配置文件,这里我的applicationContext配置文件是根据模块来分类的。如果有多个模块就引入多个“applicationContext-service.xml”文件。如果所有的都是写在“applicationContext.xml”中则这样导入:
    @ContextConfiguration(locations = "classpath:applicationContext.xml")
//指定单元测试环境
@RunWith(SpringJUnit4ClassRunner.class)
//指定配置文件路径
@ContextConfiguration(locations = {"/spring.xml"})
public class MaxTest {
    //自定注入Max
    @Autowired
    private Max max;

    @Test
    public void getMax() {
        assertEquals(5,max.getMax() );
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容