假设您有三个A , B和C类,其中A调用B和B调用C并且每个类都有一些内部状态,这些状态会影响类的方法给出的结果。 描述如何使用Mockito可以大大减少A类测试用例的数量。
我是mockito新手。 我得到了mockito的概念,但偶然发现了上述问题,我没有答案。 有人可以向我解释答案吗?
谢谢
Assume you have three classes A, B, and C where A calls B and B calls C and every class has some number of internal states that influence the result given by the class' methods. Describe how using Mockito can considerably reduce the number of test cases for class A.
I am new to mockito. I sort of got the concept of mockito but stumbled upon above question for which I do not have an answer. Can some one please explain to me the answer?
Thanks
最满意答案
Mockito可以帮助你隔离一个班级的行为,而不必知道一个合作班级的内部运作情况。
假设C看起来像这样:
public class C { private B b; public C (B b) { this.b = b; } public boolean isLargerThanTen() { return b.getSomeCalculation() > 10; } }现在假设你正在测试C.isLargerThanTen() 。 如果不嘲笑,你将不得不知道如何构造B以使getSomeCalculation()返回这样一个数字。 例如:
A a = new A(); a.setSomething(1); a.setSomethingElse(2); B b = new B(a); b.setAnotherThing(999); b.setYetAnotherThing(888); C c = new C(b); assertTrue(c.isLargerThanTen());这在两条战线上存在问题 - 首先,这很麻烦。 其次,它让你知道B的内部运作(在这种情况下, A也是B依赖的)。 如果B要改变它的实现, C的测试将会中断,尽管C没有什么问题,只是用它的测试设置的(坏)方式。
相反,如果你使用模拟,你可以模拟你关心的行为的唯一部分,而不需要理解B的内部实现细节:
B b = Mockito.mock(B.class); Mockito.when(b.getSomeCalculation()).thenReturn(11); C c = new C(b); assertTrue(c.isLargerThanTen());Mockito can help you isolate a class' behavior without having to know the internal workings of a collaborating class.
Assume C looks like this:
public class C { private B b; public C (B b) { this.b = b; } public boolean isLargerThanTen() { return b.getSomeCalculation() > 10; } }Now suppose you're testing C.isLargerThanTen(). Without mocking, you'll have to know how exactly to construct B so that its getSomeCalculation() returns such a number. E.g.:
A a = new A(); a.setSomething(1); a.setSomethingElse(2); B b = new B(a); b.setAnotherThing(999); b.setYetAnotherThing(888); C c = new C(b); assertTrue(c.isLargerThanTen());This is problematic on two fronts - first, it's cumbersome. Second, it makes you know the internal workings of B (and in this case, A, which B depends on too). If B were to change its implementation, C's test would break, even though there's nothing wrong with C, just with the (bad) way its test is set up.
Instead, if you use mocking, you could just simulate the only part of the behavior you care about, without the hassle of understanding the internal implementation details of B:
B b = Mockito.mock(B.class); Mockito.when(b.getSomeCalculation()).thenReturn(11); C c = new C(b); assertTrue(c.isLargerThanTen());更多推荐
发布评论