在测试函数中可以使用多少个 “Mockito.when”?

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

How many "Mockito.when" can be used in a test function?

问题

我是JUnit的新手。我尝试编写一些测试代码,但我对使用"Mockito.when"有疑问。我知道测试方法只能有一个断言。在一个测试方法中我可以多次使用"Mockito.when"吗?如果我多次写"Mockito.when",这是否是不好的做法?

英文:

I am new at Junit. I try to write some test codes but I have a question about using "Mockito.when". I know that a test method must has just one assertion. Can I use "Mockito.when" more than once in a test method ? Is it bad practice if I write "Mockito.when" down more than once?

答案1

得分: 1

使用框架来模拟依赖关系已经是一种“不太好”的做法。这意味着你的代码没有分解为使用存根进行测试。
但在实际情况下,我们几乎总会有一些代码是“不太好”的。这就是为什么使用像Mockito这样的框架是完全可以的:与其试图使其永远完美,不如测试现有的代码更好。
所以答案很简单:在你的测试变得易于阅读和维护的同时,你可以自由地进行任意数量的“when”(甚至是“assert”)语句。只要确保每个测试专注于一个测试案例。

英文:

Well, using frameworks to mock dependencies is already "not-so-good" practice. It means, that your code is not decomposed to use stubs for testing.
But in practice we almost always have some code that is "not-so-good". That is why using frameworks like mockito is completely fine: it is much better to test existing code than trying to make it perfect forever.
So the answer is simple: you are free to make any number of "when" (or even "assert") statements while your tests are easy to read and maintain. Just make sure that every test is focused on just one test-case.

huangapple
  • 本文由 发表于 2020年10月27日 05:25:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/64545204.html
匿名

发表评论

匿名网友

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

确定