我的问题:如何通过构造函数或setter创建模拟对象并注入属性?
我收到意外的调用错误。我正在@Before中的模拟对象上设置一个set来为我的BAPI设置name属性。当我执行测试时,我的setName方法出现意外的调用错误。但是,我真的不想测试这种方法。我只是插入它,所以当我的代码执行方法checkParm(b)时,值就在那里。
如果我没有对模拟器的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;
}
答案 0 :(得分:1)
你不能把东西注入模拟,你可以设置它的期望
而不是这个(它给你意想不到的例外):
mockAdapter.setName(BAPI_NAME);
你可能会按照你的期望这样做:
atLeast(1).of(mockAdapter).getName();
will(returnValue(BAPI_NAME));