为了测试需要(使用StrutsTestCase,jMock)调整旧的系统,大家给点意见

系统使用了Struts,在Action中调用业务层的类,准备更改结构便于使用StrutsTestcase,jmock,easymock等来写单元测试
调用关系如下:

AAction->BizA-->BizHelper
|
|--->BizB

public class AAction extends AuthBaseAction
{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception
{
OutInfoListForm outForm = null;
String forwardKind = null;
AForm inForm = (AForm)form;

//call Bussiness logic
BizA bizA = new BizA();
outForm = bizControlA.searchInfo(inForm);
if(outForm == null){
throw new NullPointerException("aaa");
}
DispatchControl comnControl = new DispatchControl();
forwardKind = comnControl.getForwardKind(outForm);
return mapping.findForward(forwardKind);
}
}

bussiess class BizA

public class BizA {
public OutInfoListForm searchInfo(AForm inForm) throws Exception {
try{
OutInfoListForm outForm = new OutInfoListForm();
String receiveTelegram=null;
BizHelper bizHelper= new BizHelper();
receiveTelegram = bizHelper.formatMessage(inForm)

BizB bizB=new BizB();
outForm = bizB.sendMessage(receiveTelegram);
if(outForm.getError())
{
throw new MyException("aaaa");
}
}catch(exception e){
throw new MyException("aaaa");
}
return outForm
}
}


更改以后代码如下:
1,增加一个接口
InterfaceBizA,

public Interface InterfaceBizA{
public OutInfoListForm searchInfo(AForm inForm) throws Exception;
public void setBizHelper(BizHelper bizHelper);
public void setBizB(BizB bizB);

}

public class BizA implement InterfaceBizA {
private BizHelper bizHelper;
private BizB bizB;

public void setBizHelper(BizHelper bizHelper){
this.bizHelper= bizHelper;
}

public void setBizB(BizB bizB){
this.bizB= bizB;
}

public OutInfoListForm searchInfo(AForm inForm) throws Exception {
try{
OutInfoListForm outForm = new OutInfoListForm();
String receiveTelegram=null;
receiveTelegram = bizHelper.formatMessage(inForm)

outForm = bizB.sendMessage(receiveTelegram);
if(outForm.getError())
{
throw new MyException("aaaa");
}
}catch(exception e){
throw new MyException("aaaa");
}
return outForm
}
}


更改以后使用jMock进行测试就可以进行了,比如在写单元测试,
测试BizA的时候可以使用jMock来隔离BizHelper类和BizB类调用带来的影响。

更改完毕以后感觉结构还是不太好,一旦业务中要调用很多的外部类,那要增加很多的
私有变量,而且在调用这个业务类前要做很多的调用setXXX的操作,不太方便。
大家给点建议。

>一旦业务中要调用很多的外部类,那要增加很多的
私有变量,而且在调用这个业务类前要做很多的调用setXXX的操作,不太方便。

哈哈,这就是现代基于Ioc编程的一个特点,你只要使用一个Ioc容器:Spring/Jdon/Hivemind,只要你提供setXXX操作,至于如何实现就不必你关心,Ioc容器自动照顾,这样测试和运行无需做改动,一步到位啦。

使用JMock的时候,是不是需要有Mock对象的一个接口?假如需要测试的代码中没有那个接口,是不是就不能实现Mock Object了?

以前用过Parasoft 的JTest的stub机制,不过需要花钱,比较不爽