mercredi 28 octobre 2015

Unit-Tests | When to use when ... | Mocktio

So I am currently writing Unit-Tests with JUnit and Mockito.

So let's say I have following testclass setup:

@Mock(name="myService")
private myServiceClass myService;

@InjectMocks
private myClassIWantToTest classUnderTest;

final myModelClass myModel = new myModelClass();

@Before
private void setUp(){
    MockitoAnnotiations.initMocks(this);

}

@Test 
private void testSomething(){
    myModel.setCode("someCode");

    final MyDataClass myData = new MyDataClass();
    myData.setCode("someCode");

    doReturn("someCode").when(myModel.getCode());
    doReturn(myModel).when(myService.getModelByCode("someCode"));

    assertEquals(classUnderTest.getDataByCode(eq("someCode")), myData);
    verify(myService.getModelByCode(eq("someCode")), atLeastOnce());
}

The method getDataByCode from my classUnderTest converts the Model into Data and it should have the same Code.

So what is a bit blurry for me is, that Unit-Tests should encapsule the classUnderTest from all dependencies. But now I have a problem. I use the setter-methods myData and myModel to set a Code. The thing is I put a DoReturn in there for myModel, but the problem is, that it's not a injected Mock. The method I try to test unfortunately doesn't have a field, it initializes this inside the method, so I can't really address it.

And the main thing is, when the set-Method of for example myModel doesn't work anymore or so, my Test as shown above, wouldn't work anymore.

So I guess I have three questions:

1.) So how hard do I need to isolate the testclass? Don't I need to use the set-method for the assertEquals?

2.) Is there another way to deal with objects, which are initialized inside a method I want to test? What is the best way to approach such a matter?

3.) Also, what would be a good pattern for structuring this? I currently initialize my expected myData result inside a Test-method. The thing is, that this is a rather short and easy example, but I have classes, where I have tons of objects and methods.

Thanks!

Aucun commentaire:

Enregistrer un commentaire