单元测试之实践四 Action的测试

来源:互联网 发布:网络推广文案 编辑:程序博客网 时间:2024/06/02 09:01
 Action的测试是比较辛苦的。因为它依赖与其他的环境(比如tomcat)。
在我的印象中,基于struts的测试是很麻烦的,因为对于execute方法,你必须mock两个对象进去。
还好。基于Webwork的测试相对简单些。
下面让我们来测试一个例子吧
java 代码
  1. Account account;
  2. IAccountService accountService;
  3. public void setAccount(Account account) {
  4. this.account = account;
  5. }

  6. public void setAccountService(IAccountService accountService) {
  7. this.accountService = accountService;
  8. }

  9. public String regist() throws Exception {
  10. if(account == null) {
  11. account = new Account();
  12. return INPUT;
  13. }

  14. if(!validForm(account))
  15. return INPUT;

  16. try {
  17. accountService.regist(account);
  18. } catch (ObjectExistsException e) {
  19. e.printStackTrace();
  20. return INPUT;
  21. }

  22. return SUCCESS;
  23. }

  24. private boolean validForm(Account e) {
  25. if(e.getName() == null || e.getName().trim().equals(""))
  26. return false;
  27. if(e.getPassword() == null || e.getPassword().trim().equals(""))
  28. return false;
  29. return true;
  30. }

有经验的程序员见到上面的代码应该就知道怎么测试了。
我们只需setAccount,跟setAccountService即可,
而Account本身来讲就是是个po,所以可以自己new一个
AccountService则可以mock一个。真是太完美了,我太喜好mock,它总是给我惊喜
java 代码
  1. package org.wuhua.action;

  2. import junit.framework.TestCase;

  3. import org.easymock.MockControl;
  4. import org.wuhua.exception.ObjectExistsException;
  5. import org.wuhua.model.Account;
  6. import org.wuhua.service.IAccountService;

  7. import sms.king.AccountManager;

  8. import com.opensymphony.xwork.Action;

  9. public class AccountActionTest extends TestCase {
  10. private MockControl control;
  11. IAccountService accountService;
  12. protected void setUp() throws Exception {
  13. control = MockControl.createControl(IAccountService.class);
  14. accountService = (IAccountService) control.getMock();

  15. }

  16. public void testRegistOk() throws Exception {
  17. Account employee = new Account("name");
  18. employee.setPassword("password");




  19. accountService.regist(employee);
  20. control.setVoidCallable(1);

  21. control.replay();

  22. AccountAction action = new AccountAction();
  23. action.setAccount(employee);
  24. action.setAccountService(accountService);

  25. assertEquals(Action.SUCCESS, action.regist());

  26. control.verify();
  27. }

  28. public void testRegistNameExists() throws Exception {
  29. Account employee = new Account("name");
  30. employee.setPassword("password");




  31. accountService.regist(employee);
  32. control.setThrowable(new ObjectExistsException(""));

  33. control.replay();

  34. AccountAction action = new AccountAction();
  35. action.setAccount(employee);
  36. action.setAccountService(accountService);

  37. assertEquals(Action.INPUT, action.regist());

  38. control.verify();
  39. }
  40. }

ok,一个测试的例子就好了。
 
原创粉丝点击