在pom.xml添加test依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring-text依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
以Max类比较大小为例
Max类
package com.spring.IoC;
/**
* Created by User on 2019/3/4.
* 待测程序,求两个数的较大值
*/
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;
}
}
bean
<!--配置一个Max的bean-->
<bean id="max" class="com.spring.IoC.Max">
<constructor-arg name="a" value="5"/>
<constructor-arg name="b" value="3"/>
</bean>
将光标放在public class Max一行 快捷键“alt+enter” 选择 Creat Test
image image选择如图:
image自动生成MaxTest
package com.spring.IoC;
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.*;
/**
* Created by User on 2019/3/4.
*/
//指定单元测试环境
@RunWith(SpringJUnit4ClassRunner.class)
//指定配置文件路径
@ContextConfiguration(locations = {"/spring.xml"})
public class MaxTest {
// 自动注入max(仓库管理给斧头)
@Autowired
private Max max;
@Test
public void getMax() throws Exception {
assertEquals(5,max.getMax());
}
}
网友评论