0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
ARP
  • 603
  • 1
  • 11
  • 23
  • 1
    in your `CredentialImpl ` class is `StorageManager.isExpired()` a *static access* or are you just ignoring [Java Naming Conventions](http://www.oracle.com/technetwork/java/codeconventions-135099.html)? – Timothy Truckle Oct 18 '17 at 13:29
  • 1
    The usage of `StorageManager` looks like it's supposed to have static methods but the posted code is not static. If it is static, [this](https://stackoverflow.com/questions/21105403/mocking-static-methods-with-mockito) might help. – Andrew S Oct 18 '17 at 13:30
  • StorageManager is a single ton class, which is injected via dagger module – ARP Oct 18 '17 at 13:43
  • Where is your `@Before public void setUp()` method ? Your tutorial or book should cover this – David Rawson Oct 19 '17 at 02:24

0 Answers0