day03 spring中使用Junit

2019-03-04  本文已影响0人  山下_26
1.配置Junit依赖

将下面这段代码添加到项目的pom.xml文件的<dependencies>标记中

<!--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
5.在生成的测试类外添加@@RunWith()和@ContextConfiguration()注解

类中自定义注入id,然后在方法中进行断言,运行方法

//指定单元测试环境
@RunWith(SpringJUnit4ClassRunner.class)
//指定配置文件路径
@ContextConfiguration(locations = {"/spring.xml"})
public class MaxTest {
    //自定注入Max
    @Autowired
    private Max max;

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

(locations指向你创建的bean配置文件)

上一篇 下一篇

猜你喜欢

热点阅读