美文网首页
在Spring 5中使用JUnit单元测试

在Spring 5中使用JUnit单元测试

作者: 国王兔子 | 来源:发表于2019-03-04 21:26 被阅读0次

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());
    }
}

相关文章

网友评论

      本文标题:在Spring 5中使用JUnit单元测试

      本文链接:https://www.haomeiwen.com/subject/dzuwuqtx.html