JUnit单元测试

2019-03-04  本文已影响0人  青柠_efca

1. 在pom文件中添加依赖

        <!--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="5"/>
        <constructor-arg name="b" value="3"/>
    </bean>

4. 创建单元测试代码

将光标放在Max类的声明的后面按“Ctrl+Shift+t",选择“Create Test”,勾选JUnit4,勾选待测方法getMax(),OK,在Test包下,会自动创建一个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 T");
        assertEquals(5, max.getMax());
    }
}

上一篇 下一篇

猜你喜欢

热点阅读