I'm new to Unit testing concept, and would like to test the following scenario.
public interface CredentialService{
String getAuthToken();
}
Following implements the service
public class CredentialImpl implements CredentialService{
@Override
public String getAuthToken(){
if(StorageManager.isExpired()) {
return StorageManager.getToken();
} else {
return "Some error";
}
}
Storage logic it's a singleton class
public class StorageManager{
public void setToken(String token) {
//stores into the prefs
}
public String getToken(){
//get token from prefs
}
public boolean isExpired(){
return false;
}
}
Here I would like to test CredentialImplTest and following is my test class
@Config(constants = BuildConfig.class, sdk = TestConfig.SDK)
@RunWith(RobolectricGradleTestRunner.class)
public class CredentialImplTest extends TestCase {
CredentialServiceImpl mSubject = new CredentialServiceImpl();
StorageManager mStorageManager = mock(StorageManager.class);
String mTestToken = "abcd";
@Test
public void getAccessToken_noError_expectToken(){
mStorageManager.setAccessToken(mTestToken);
when(mSubject.getAuthToken())
.thenReturn(mTokenUtils.getAccessToken());
assertEquals(mTestToken, mSubject.getAccessToken());
}
}
If I try to execute the above test the Android Studio throwing E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, you naughty developer!
Is my approach to test getAuthToken()
method right, and if not please suggest me the right one?