我的问题:如何通过构造函数或setter创建模拟对象并注入属性?
我收到意外的调用错误。我正在对@Before中的模拟对象进行设置,以设置BAPI的name属性。执行测试时,我的setName方法收到意外的调用错误。但是,我真的不想测试这种方法。我只是插入它,所以当我的代码执行checkParm(b)方法时,该值在那里。
如果我对模拟的设置器没有任何期望,则会得到意外的调用。但是,即使我将此代码添加到期望中,我仍然会得到意外的调用。
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;
}
最佳答案
您不能将事物注入到模拟中,您可以对其设定期望
而不是这样(这会给您带来意外的异常):
mockAdapter.setName(BAPI_NAME);
您可以按照自己的期望执行此操作:
atLeast(1).of(mockAdapter).getName();
will(returnValue(BAPI_NAME));
关于java - 如何将值注入(inject)到模拟对象的构造函数中或通过 setter ?正在收到意外的调用错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11661556/