单元测试
一、向pom.xml文件中添加相关依赖包
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
二、编写测试程序
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;
}
}
public class MaxApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("/bean.xml");
Max max = (Max) context.getBean("max");
System.out.print(max.getMax());
}
}
三、在bean.xml文件中配置Max类的bean
<bean id="max" class="com.spring.Ioc.Max">
<constructor-arg name="a" value="5"/>
<constructor-arg name="b" value="3"/>
</bean>
四、创建单元测试
-
在Max类的声名后面,按Alt + Enter键或者Ctrl + Shift + t或者在类的方法体右击点击Generate,然后点击test,勾选要测试的方法,点击OK会在包下自动生成Maxtest类的测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/bean.xml"})
public class MaxTest {
@Autowired
private Max max;
@Test
public void getMax() throws Exception {
assertEquals(5,max.getMax());
}
}
- 注解:
- @RunWith:表示指定运行的环境
- @ContextConfiguration:表示指定配置文件路径