如何模拟/测试返回 void 的方法,可能在 Mockito 中
我遇到了一个问题,但找不到优雅的解决方案。
所以问题出在 Selenium Web 驱动程序的模拟上,我不知道应该如何测试/模拟 void 方法。
public void clickAndWait(String locator) {
if(isElementPresent(locator) == false) throw some exception;
selenium.clickAndWait(); //a problematic delegating call to selenium
}
所以我要问的是,如何正确测试这样的方法,一个测试是抛出异常,但是如何正确地测试我委托给的 void 方法?
I came across a problem and I can't find an elegant solution.
So the problem is with a mock of Selenium web driver, and I dont know how should I test/mock void methods.
public void clickAndWait(String locator) {
if(isElementPresent(locator) == false) throw some exception;
selenium.clickAndWait(); //a problematic delegating call to selenium
}
So what I am asking is, how to properly test such a method, one test would be for exception being thrown, but how properly make test of that void method I delegate to?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
以下代码示例来自此 Mockito 文档 说明了如何模拟 void 方法:
The following code sample from this Mockito documentation illustrates how to mock a void method:
前面的答案一直强调在每次调用时执行某些操作(可能抛出异常)。这样,当您执行类似 : 的操作
,然后调用类似 : 的存根服务(或逻辑)
时,它将生成异常。如果您想测试方法的正常运行,可以编写积极的测试用例,该怎么办?对于这种情况,可以通过以下方式模拟 void 返回方法:
这意味着,由于您为
mockedList
模拟存根了clear()
方法,因此您可以确定该方法是不会影响单元的逻辑,并且您仍然可以检查流程的其余部分而不会生成异常。The previous answers have been stressing on doing something (throwing an exception possibly) at every call. This way when you do something like :
and then call the stubbed service (or logic) like :
it will generate an exception. What if you want to test for a proper functioning of method maybe writing positive test case. Mocking a void returning method for such case could be done by :
which means that since you stubbed the
clear()
method formockedList
mock, you can be sure that this method is not going to effect the logic of the unit and still you can check the rest of the flow without generating an exception.您还可以使用:
You can also use:
您可以在方法调用上抛出异常,这里有一个小示例,说明如何执行此操作:
然后调用
mockedList.clear();
模拟方法将抛出异常。或者您可以计算您的方法被调用的次数,这是一个如何执行此操作的小示例:
You can trow an exception on your method call, here is a small example how to do it:
then you call
mockedList.clear();
mocked method will throw an exception.Or you can count how many times your method was called, here is a small example how to do it:
在 Java 8 中,这可以变得更清晰
return null;
很重要,如果没有它,编译将失败并出现一些相当模糊的错误,因为它将无法为找到合适的覆盖>做答案
。In Java 8 this can be made a little cleaner
The
return null;
is important and without it the compile will fail with some fairly obscure errors as it won't be able to find a suitable override fordoAnswer
.