二、編寫SpringJunit(依賴包:spring-test-3.0.4.RELEASE.jar,junit4,以及其他的spring核心包),還是以User為例子,我們編寫UserTestUnit來驗(yàn)證我們后臺(tái)的方法,如下:
/**
* @author fisher
* @description 用戶業(yè)務(wù)測(cè)試
*/
// 使用springJunit4
@RunWith(SpringJUnit4ClassRunner.class)
// spring配置文件加載(locations為文件路徑)
@ContextConfiguration(locations = {
"classpath:spring/application-hibernate.xml",
"classpath:spring/application-common-service.xml",
"classpath:spring/application-sys-service.xml" })
public class UserTestJunit {
@Autowired
UserService userService;// 自動(dòng)注入userService
/**
* @description 測(cè)試查詢用戶
* @throws Exception
*/
@Test
public void query() throws Exception {
List result = userService.getAllEmployee();
Assert.notEmpty(result);
}
/**
* @description 測(cè)試用戶添加
* @throws Exception
*/
@Test
public void save() throws Exception {
User user = new User();
user.setUsrCode("test001");
user.setUsrName("test");
user.setPassword("123");
user.setIdCard("513029198503140026");
user.setEmail("
aaa@sina.com");
User u = userService.save(user);
Assert.notNull(u);
org.junit.Assert.assertEquals("test", user.getUsrName());
}
/**
* @description 測(cè)試用戶更新
* @throws Exception
*/
@Test
public void update() throws Exception {
User user = new User();
user.setUsrCode("test001");
user.setUsrName("test");
user.setPassword("123");
user.setIdCard("513029198503140026");
user.setEmail("
aaa@sina.com");
User u = userService.update(user);
Assert.notNull(u);
org.junit.Assert.assertEquals("test", user.getUsrName());
}
/**
* @description 測(cè)試用戶刪除
* @throws Exception
*/
@Test
public void del() throws Exception {
User user = new User();
user.setUserId("1");
User u = userService.delete(user);
Assert.notNull(u);
org.junit.Assert.assertEquals("1", user.getUserId());
}
}
【總結(jié)】單元測(cè)試不于此,靈活性比較大,要結(jié)合實(shí)際進(jìn)行編寫,上面兩種測(cè)試是按照我們項(xiàng)目中規(guī)范編寫,大家可以作為參考,自我覺得還是比較實(shí)用而且用注解方式比較方便。