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

8. 在Spring 5中使用JUnit单元测试

作者: 叶小慈呀 | 来源:发表于2019-03-04 21:49 被阅读0次

1.在pom.xml中添加依赖

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

2.编写待测试程序Max

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="2"/>
        <constructor-arg name="b" value="4"/>
    </bean>

4.编写测试程序

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

相关文章

网友评论

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

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