Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Having a class constructor that requires a ton of dependent objects (singleton static at runtime, etc.) is always a pain when creating mock tests. The best way I can think of is to use some combination of the <code>Powermockito.whenNew()</code> call, and the <code>Mockito.any(Class.class)</code> call. This way, when your constructor is called, you can hook in the objects that are needed. If you follow a similar singleton pattern on your dependent objects, you can mock those classes <code>getInstance()</code> calls to return you a copy of a mock you instantiate in the tests.</p> <p>Example: </p> <pre><code>Dependency dependMock = PowerMockito.mock(Dependency.class); PowerMockito.whenNew(Dependency.class).withNoArguments().thenReturn(dependMock); </code></pre> <p>OR, if the <code>Dependency</code> needs args passed in for your 2nd level dependency:</p> <pre><code>Dependency dependMock = PowerMockito.mock(Dependency.class); PowerMockito.whenNew(Dependency.class) .withArguments(Mockito.any(LevelTwoDependency.class)).thenReturn(dependMock); </code></pre> <p>Note, that when using the <code>whenNew</code> you need to have a hook for the class you are testing, so that code gets fired off. This can be done by adding some mock annotations for the test class.</p> <pre><code>@RunWith(PowerMockRunner.class) @PrepareForTest({ClassYouAreTesting.class}) public class ClassTest{ // code } </code></pre> <p>This allows you to have full control over your 2nd level dependency objects with Mocks. By removing them from logic (by providing Mocked functionality), you get to the core of your tests, which ends up testing the pure functionality of your class in question. By removing any odd behavior from these dependent classes, you remove the risk of having bugs in that code, which would end up breaking and giving false test results for any class using those dependency classes.</p> <p>By chainging together these Mocks, you can basically mock the main dependent class and all its sub-dependency classes using other mocks. It can get a little messy depending on how the constrcutors work and you you setup private variables for these objects. </p>
    singulars
    1. This table or related slice is empty.
    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.
 

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