Can any one explain in which case we use PowerMockito.when() and PowerMockito.doReturn()

huangapple go评论70阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年8月30日 18:40:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/63656573.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定