我的问题:如何创建一个模拟对象并通过构造函数或设置器注入属性?
我收到意外的调用错误。我正在@Before 中对我的模拟对象进行设置,以设置我的BAPI 的名称属性。当我执行测试时,我的 setName 方法出现意外调用错误。但是,我真的不想测试这种方法。我只是插入它,所以当我的代码执行方法 checkParm(b) 时值就在那里。
如果我没有对 mocked 的 setter 增加任何期望,我会得到意想不到的调用。但是,如果我将此代码添加到期望中,我仍然会得到意外的调用。
ignoring(mockAdapter).setName(BAPI_NAME);
inSequence(sequence);
这是我的@Before 方法
@Before
public void setUp() throws Exception {
objectUnderTest = new ApoSAPExtractor();
mockAdapter = context.mock(BapiAdapter.class);
mockAdapter.setName(BAPI_NAME);
apoResults = new ApoResults();
apoParameterBean = new ApoParameterBean();
}
然后我的测试方法:
@Test
public final void testExtract() throws Exception {
final Sequence sequence = context.sequence(SEQUENCE);
context.checking(new Expectations() {{
atLeast(1).of(mockAdapter).getName();
will(returnValue(new String()));
inSequence(sequence);
oneOf(mockAdapter).activate();
inSequence(sequence);
oneOf(mockAdapter).getImportTableParameter(IM_PARMS);
inSequence(sequence);
will(returnValue(JCoTable.class));
oneOf(mockAdapter).execute();
inSequence(sequence);
oneOf(mockAdapter).getExportTableAdapter(EX_PO_APO);
inSequence(sequence);
will(returnValue(new TableAdapter(with(any(JCoTable.class)))));
}});
objectUnderTest.extract(mockAdapter, apoParameterBean);
context.assertIsSatisfied();
}
我正在嘲笑的班级:
public class ApoSAPExtractor implements SAPExtractor<ApoResults, ApoParameterBean> {
private final static Logger logger = Logger.getLogger(ApoSAPExtractor.class);
public List<ApoResults> extract(BapiAdapter b, ApoParameterBean pb) throws JCoException, Exception {
checkParm(b);
List<ApoResults>list = new ArrayList<ApoResults>();
try {
b.activate();
JCoTable itp = b.getImportTableParameter(APOConstants.BAPI_IM_PARMS);
itp.appendRow();
JCoTable t = itp.getTable(APOConstants.BAPI_DOC_TYPES);
Utils.appendParm(t, pb.getDocTypes());
b.execute();
TableAdapter ta = b.getExportTableAdapter(APOConstants.BAPI_EX_PO_APO);
for (int i = 0; i < ta.size(); i++) {
ApoResults ar = new ApoResults();
... lots of setters ...
list.add(ar);
ta.next();
}
} catch (Exception e) {
logger.info(String.format("Program %s failed.",this.getClass().getSimpleName(), "failed"));
e.printStackTrace();
throw e;
}
return list;
}