版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lhc_makefunny/article/details/79541769
之前对一个方法是否执行正确的判断上,总是凭自己的感觉或等到最后调用并执行的时候才可以看出开。今天使用junit完成了对方法的测试,现对该方法进行记录,希望可以帮助到你们。
- 添加相关测试依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework-version}</version>
<scope>test</scope>
</dependency>
- 这里以我的一个简单项目来演示
- 在对应的包下选择并创建测试用例
- 填写测试用例名称并选择类中的相关方法,并点击Finish完成测试用例的创建
- 在对应的包下选择并创建测试用例
- 在测试类中添加相关注解
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:root-context.xml", "classpath*:servlet-context.xml" }) //引入两个配置文件
@TransactionConfiguration(defaultRollback = true, transactionManager = "transactionmanager") //使用事务,避免运行测试对数据的影响
@Transactional
4 .再次就完成了测试类的创建和配置
5. 注入所需要的bean
package com.example.oa.test;
import static org.junit.Assert.*;
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 org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
import com.example.oa.domain.Employee;
import com.example.oa.service.EmployeeService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:root-context.xml", "classpath*:servlet-context.xml" })
@TransactionConfiguration(defaultRollback = true, transactionManager = "transactionmanager")
@Transactional
public class EmployeeTest {
@Autowired
private EmployeeService employeeService; //注入所需的bean(记得要在实现类上添加相关注解)
@Test
public void testIsUser() {
boolean hasuser = employeeService.getuserByUPR("890", "7987", 0);
assertEquals(true, hasuser);
}
@Test
public void testForgetPassword() {
Employee e = new Employee();
e.setEmployee_account("6");
e.setRole(0);
e.setPassword("555");
boolean isupdate = employeeService.updatePassword(e);
assertEquals(true, isupdate);
}
@Test
public void testDeleteEmployee() {
Employee e = new Employee();
e.setEmployee_id(7);
boolean isdelete = employeeService.deleteEmployee(e);
assertEquals(true, isdelete);
}
@Test
public void testAddEmployee() {
Employee e = new Employee();
e.setEmployee_account("555");
e.setUsername("555");
e.setPassword("666");
e.setAge(45);
e.setAddress("四川省成都市");
e.setDepartmentid(2);
e.setRole(0);
boolean isadded = employeeService.addEmployee(e);
assertEquals(true, isadded);
}
}
- . 运行测试
*. 项目结构: