Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you look closely at your code you'll see that the <code>second</code> property in your test is still an instance of <code>Second</code>, not a mock (you don't pass the mock to <code>first</code> in your code).</p> <p>The simplest way would be to create a setter for <code>second</code> in <code>First</code> class and pass it the mock explicitly.</p> <p>Like this:</p> <pre><code>public class First { Second second ; public First(){ second = new Second(); } public String doSecond(){ return second.doSecond(); } public void setSecond(Second second) { this.second = second; } } class Second { public String doSecond(){ return "Do Something"; } } .... public void testFirst(){ Second sec = mock(Second.class); when(sec.doSecond()).thenReturn("Stubbed Second"); First first = new First(); first.setSecond(sec) assertEquals("Stubbed Second", first.doSecond()); } </code></pre> <p>Another would be to pass a <code>Second</code> instance as <code>First</code>'s constructor parameter.</p> <p>If you can't modify the code, I think the only option would be to use reflection:</p> <pre><code>public void testFirst(){ Second sec = mock(Second.class); when(sec.doSecond()).thenReturn("Stubbed Second"); First first = new First(); Field privateField = PrivateObject.class. getDeclaredField("second"); privateField.setAccessible(true); privateField.set(first, sec); assertEquals("Stubbed Second", first.doSecond()); } </code></pre> <p>But you probably can, as it's rare to do tests on code you don't control (although one can imagine a scenario where you have to test an external library cause it's author didn't :))</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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