在Spring 5中使用JUnit单元测试

1.在pom.xml中添加依赖

        <!--添加spring-test依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </添加dependency>
        <!--junit依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

2.编写Max.java

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.为Max配置Bean

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

4.创建单元测试

在Max类的声明的后面按“ctrl+shift+t”,选择“Create Test”,勾选JUnit4,并勾选待测方法getMax(),点击OK


image.png

5.之后自动创建MaxTest类

import org.apache.log4j.Logger;
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 static org.junit.Assert.assertEquals;

@RunWith(SpringJUnit4ClassRunner.class)//运行环境
@ContextConfiguration(locations = {"/applicationContext.xml"})//指定文件配置
public class MaxTest {
    private static Logger log = Logger.getLogger(MaxTest.class.getClass());
    @Autowired
    private Max max;
    @Test
    public void getMax() {
        log.debug("test by mqxu");
        assertEquals(5, max.getMax());
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1 在pom文件中添加依赖 2 编写待测程序Max.java 3 配置Max的bean 4 创建单元测试代码 在M...
    陶然然_niit阅读 1,104评论 0 1
  • Eclipse常用快捷键 1几个最重要的快捷键 代码助手:Ctrl+Space(简体中文操作系统是Alt+/)快速...
    山不转人自转阅读 1,490评论 0 10
  • 搜索 Eclipse常用快捷键 编辑 查看 窗口 导航 文本编辑 文件 项目 源代码 运行 重构 其他Eclips...
    CarlosLynn阅读 1,719评论 0 7
  • 1.配置Junit依赖 将下面这段代码添加到项目的pom.xml文件的<dependencies>标记中 2.新建...
    山下_26阅读 341评论 0 3
  • 1.在pom文件中添加依赖 2.编写待测程序Max.java 3.配置Max的bean 4.创建单元测试代码 在M...
    嗯哼65阅读 581评论 0 1