Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In order to replace the actual B with your own using Mockito (or any other mocking framework) you'll <em>have</em> to be able to inject B either manually by creating a constructor</p> <pre><code>public A(B b) { localB = b; } </code></pre> <p>by creating a method</p> <pre><code>public void setB(B b) { localB = b; } </code></pre> <p>or by using some automatic injection framework.</p> <p>However, If B is completely encapsulated and hidden and that cannot be changed then you can write tests against B. to show that given known inputs B returns the expected outputs</p> <p>And then tests against A i.e. given known inputs does A.calculate() give the expected outputs.</p> <p>If you can show that B behaves as expected and A behaves as expected then you don't need to show that A calls B correctly explicitly since you're testing it implicitly.</p> <hr> <p>EDITED because @david wallace has less coffee or more sleep than me!</p> <p>You don't <em>have</em> to inject a <strong>mock</strong> B. If it helps you can inject the actual B but first <a href="http://mockito.googlecode.com/hg-history/1.5/javadoc/org/mockito/Mockito.html" rel="nofollow">create a spy</a> <code>a.getB();</code> </p> <pre><code>B spyB = spy(new B()); //maybe stub the method return here A a = new A(spyB); a.calculate(); verify(spyB).complicatedThingForCalculate("a", "lot", "of", "specified", "parameter"); </code></pre> <p>Further edit: As pointed out in the comments you're much better off using a Mock than a spy. From the documentation:</p> <blockquote> <p>Real spies should be used carefully and occasionally, for example when dealing with legacy code.</p> </blockquote> <p>So I included it here as you say you don't want / have the freedom to change A and B.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload