英文:
Can any one explain in which case we use PowerMockito.when() and PowerMockito.doReturn()
问题
我在为我的服务类编写测试用例,但我不确定何时使用PowerMockito.when()
和PowerMockito.doReturn()
,因为它们的行为在我看来很相似。
英文:
I was writing test case for my service class but i m not sure when to use PowerMockito.when()
and PowerMockito.doReturn()
as both behavior looks similar to me.
答案1
得分: 0
从我的理解来看,doReturn()
和 when()
几乎是相同的,但我发现在 when()
中,在编译时会对返回的值进行类型检查,而在 doReturn()
中,在编译时不会对返回的值进行类型检查。
例如:
案例1:
PowerMockito.when(mongoTemplate.getCollection(Mockito.eq("testdoc"))).thenReturn(mongoCollection);
案例2:
powerMockito.doReturn(mongoCollection).when(mongoTemplate).getCollection(Mockito.eq("test-doc"));
在案例1中,mongoCollection
的类型在编译时会进行检查,而在案例2中,mongoCollection
的类型在编译时不会被检查。
英文:
From my understanding doReturn() and when() are almost equal ,but the difference which i found in when() type-checking of the value that you're returning at compile time where as
in doReturn() there is no type-checking of the value that you're returning at compile time
For Example:
case1:
PowerMockito.when(mongoTamplate.getCollection(Mockito.eq("testdoc"))).thenReturn(mongoCollection);
case2:
powerMockito.doReturn(mongoCollection).when(mongoTamplate).getCollection(Mockito.eq("test-doc"))
In case 1 type of mongoCollection is checked at compile time where as in case2 type of mongoCollection is not checked at compilation
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论