使用Junit的顺序
1.添加依赖
2.编写待测程序
3.编写单元测试程序
实例演练
定义User类,封装account和password属性,提供getter/setter,重载构造方法,重写toString()方法
1、定义UserLogin类,封装User属性,提供getter/setter,并定义public boolean userLogin(User user);方法,判定某个用户能否登陆成功,指定账号为“admin”,密码为“111”
2、写配置文件,通过构造器注入创建一个User对象并传值,通过setter注入创建UserLogin对象并传值
3、 写单元测试,测试某用户能否登陆成功
一、添加依赖
在porm.xml文件中添加依赖:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
二、编写待测程序
User类:
package com.spring.IoC;
public class User {
private String account;
private String password; //封装属性
public User(String account, String password) {
this.account = account;
this.password = password;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public User() {
}
@Override
public String toString() {
return "User{" +
"account='" + account + '\'' +
", password='" + password + '\'' +
'}';
}
}
UserLoginTest类:
package com.spring.IoC;
public class UserLogin {
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public boolean userLogin(User user){
boolean flag=false;
if(user.getAccount().equals("admin")&&
user.getPassword().equals("111")){
flag=true;
}
return flag;
} //判断账户和密码是否正确
}
Spring.xml类
<bean id="user" class="com.spring.IoC.User">
<constructor-arg name="account" value="admin"></constructor-arg>
<constructor-arg name="password" value="111"></constructor-arg>
</bean> //通过构造器传值
<bean id="userLogin" class="com.spring.IoC.UserLogin">
<property name="user" ref="user"></property>
</bean> //通过setter传值
三、编写单元测试程序
-
选中要测试类的类名,并按alt+enter键
创建测试类
点击ok
测试类内容如下:
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.*;
//指定单元测试环境
@RunWith(SpringJUnit4ClassRunner.class)
//指定配置文件路径
@ContextConfiguration(locations={"/spring.xml"})
public class UserLoginTest {
// 自动注入
@Autowired
private UserLogin userlogin;
@Test
public void userLogin() throws Exception{
assertEquals(true,userlogin.userLogin(userlogin.getUser()));
}
}
运行结果:
测试通过
网友评论