【问题标题】:EasyMock test case failed saying method called incorrectlyEasyMock 测试用例失败说方法调用不正确
【发布时间】:2015-06-16 13:21:13
【问题描述】:

有人知道下面所示的 EasyMock 测试用例失败中的数字 5b40c281 和 78a1d1f4 是什么意思吗?

它们本质上是指向两个不同 PdlPrintJob 实例的指针吗?

有人知道为什么会发生这种故障吗?

在主代码中,PdlPrintJob 被构造(使用 new PdlPrintJob())并作为参数传递给方法 printer.executePrintJob()。

在测试用例中,PdlPrintJob 被构造(使用 new PdlPrintJob())并作为参数传递给 mockPrinter.executePrintJob()。

感谢您的建议,

最好的问候

詹姆斯

junit.framework.AssertionFailedError:
Unexpected method call executePrintJob(com.canon.cel.meap.jobs.PdlPrintJob@5b40c281, EasyMock for interface com.canon.meap.security.AccessControlToken):
executePrintJob(com.canon.cel.meap.jobs.PdlPrintJob@5b40c281, EasyMock for interface com.canon.meap.security.AccessControlToken): expected: 0, actual: 1
executePrintJob(com.canon.cel.meap.jobs.PdlPrintJob@78a1d1f4, EasyMock for interface com.canon.meap.security.AccessControlToken): expected: 1, actual: 0

【问题讨论】:

标签: unit-testing junit easymock


【解决方案1】:

因为你在你的测试课上做过这样的事情。

EasyMock.expect(executePrintJob(new PdlPrintJob(),....))'

但实际上它应该是一个你应该作为参数传递的模拟对象。

你需要做这样的事情

PdlPrintJob pdlPrintJob=Easymock.createNiceMock(PdlPrintJob.class);
Powermock.expectNew(PdlPrintJob).andReturn(pdlPrintJob).anyTimes(); //this will return the mocked instance of PDlPrintJob class wherever 'new' operator is used for this class
EasyMock.expect(executePrintJob(pdlPrintJob,.....)).andReturn(anythingYouWantToReturn).anyTimes(); // have added '.....' in case there are other parameters to this method
EasyMock.replay(pdlPrintJob);
Powermock.replayAll();

您遇到了这个问题,因为 Easymock 是一个严格的模拟框架,您要求它只期望具有特定对象类型的特定方法 (its like tightly binding method expectation to a single object),并且在执行期间使用 new 运算符,方法期望失败,因为对象参数没有符合 Easymock 的期望,导致这个异常。

我总是喜欢为方法期望做这样的事情

如果我要测试的方法是

public String compress(String str, Integer intr, double ch){}

我希望easymock中的这种方法如下:

EasyMock.expect(compress(EasyMock.anyObject(String.class),EasyMock.anyObject(Integer.class),EasyMock.anyDouble())).andReturn("Done compressing").anyTimes();

所以通过这种方法,我的方法预期适用于在测试用例执行期间传递给我的 compress() 方法的任何有效参数。

希望有帮助!

祝你好运!

【讨论】:

  • 如果将mock传递给方法期望不起作用,您可以尝试第二种方法,它肯定有效!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-12
  • 2021-12-21
  • 2010-12-30
  • 1970-01-01
  • 2021-12-22
相关资源
最近更新 更多