Why Unit Tests?
Categories of tests in Android
Local Unit Tests
Instrumented Test
Local Unit Tests
Intrumented Tests
What is a Unit Test?
A unit test verifies in isolation the functionality of a certain component.
Mocking dependecies
It might happen that a class eg.Presenter doesn’t stand in isolation- it also requires a View that updates UI and a Repository, where data is stored.
We dont care about the concrete impleemntation of the View and Repository, at this point, we only want to make sure that Presenter behaves as expected.
So, instead of relying on actual implementations of these dependecies we can use Mock Objects to test our class.
Mocking is creating objects that simulate the behaviour of real objects
One popular framework for mocking on Android is MOCKITO.
Mockito
Mockito uses RUNTIME CODE GENERATION techniques to build implementations of mocks.
For ex:
ArrayList mock = mock(ArrayList.class)
Mockito is building a new generatoed class that extends ArrayList, but has 'mock' implementation that can be configured by you. When your Java process running the test exits, the generated types vanish. They live, only at runtime.
Test doubles
Test double is a generic term used for indicating some kind of dependency substitution for the test purposes
Test doubles are:
- STUB uses STATE verification while
- MOCK uses BEHAVIOR verification.
- SPY is a STUB, that use BEHAVIOR verification
Difference between Mock and Stub
WHAT IS and WHEN TO USE MOCK?
WHAT IS and WHEN TO USE STUB?
WHEN TO USE SPY?
Difference between Mock and Spy
Example
@Mock
Dependecy mockDep;
ObjUnderTest objUnderTest;
@Before
init(){
objUnderTest = new ObjUnderTest(); // real instance
MockitoAnnotations.initMocks(this);
}@Test
testSomething(){
objUnderTest.testSomething();
verify(mockDep).methodToBeCalled();
}UI Testing Android
UI Automator - allows many system stuff, as example turn on/off wifi, notification, access to any application
Espresso -allows you test many things inside your application, simulating user interactions.
Steps to manually test UI with Espresso
onView(ViewMatcher)
.perform(ViewAction)
.check(ViewAssertion);