I've been asked to set up continuous integration on Android Studio so I started with unit testing and mocking.
I feel I missunderstood the Mockito basis and working. I've found this kind of examples on the Internet:
@RunWith(MockitoJUnitRunner.class)
public class ExampleUnitTest {
MainActivity classToTest = new MainActivity();
@Mock
ClassIDontWantToTest classToMock;
/**
* Examples found a lot of times on the Internet
* My method is not tested at all
* I think it doesn't make sense to test Mockito but our own methods
* @throws Exception
*/
@Test
public void testMethodIDontWantToTest() throws Exception {
when(classToMock.methodIDontWantToTest()).thenReturn("Mocked result");
assertTrue(classToMock.methodIDontWantToTest().equals("Mocked result"));
}
}
This is my code:
public class MainActivity extends AppCompatActivity {
ClassIDontWantToTest classIWantToMock = new ClassIDontWantToTest();
/**
* Actual Method I want to test
* @return Return value
*/
public String methodIWantToTestButReturnsUnspectedValue() {
// (...) Code to test
return classIWantToMock.methodIDontWantToTest();
}
}
public class ClassIDontWantToTest {
public String methodIDontWantToTest() {
return "Actual result";
}
}
And this is how I understand it would have to be done:
@RunWith(MockitoJUnitRunner.class)
public class ExampleUnitTest {
MainActivity classToTest = new MainActivity();
@Mock
ClassIDontWantToTest classToMock;
/**
* Test I want to do and I think it makes sense, but it doesn't work
* @throws Exception
*/
@Test
public void testMethodIWantToTest() throws Exception {
when(classToMock.methodIDontWantToTest()).thenReturn("Mocked result");
assertTrue(classToTest.methodIWantToTestButReturnsUnspectedValue().equals("Mocked result"));
}
}
Obviously there's something I don't understand, but I don't know what it is. May anybody please tell me where I'm wrong?
Thank you very much!
Aucun commentaire:
Enregistrer un commentaire