Issue
I'm trying to build a test for activity with JUnit and espresso.
But I faced a problem. my activity depending on a previous activity which was supposed to load user data from a database.
I store the user data in a private variable (to prevent any unwanted changes) and the only way to apply a value to it, is to use a loadFromDatabase
method.
But I can't use this method while testing, because it has a callback listener (it sends a request to a server) and I need to load this data immediately in order to load the activity
public User {
private static User mCurrentUser = ...;
public static void loadFromDatabase() { ... }
}
public MainActivityTest {
public MainActivityTest() {
// load the data
User.loadFromDatabase({
// on complete callback
})
// load the activity
activity = new ActivityTestRule(MainActivity.class)
}
}
public MainActivity extends Activity {
public void onCreate() {
// needs the user data
User.mCurrentUser...
}
}
How can I handle this kind of problem without making mCurrentUser
public?
Is there a way to create methods in the regular classes just for testing?
Thanks.
Solution
You can mock it. For mocking you can use mocking libraries like Mockito & PowerMockito.
Create a method in User to return the value and mock that method. If you want this method exclusively for testing then mark it with @VisibleForTesting to restrict access to it. eg;
public class User{
private static User mCurrentUser;
public static User getCurrentUser(){
return mCurrentUser;
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(User.class)
public MainActivityTest{
@Test
public void testCurrentUser{
User probableUserDataFromDB = Mockito.mock(User.class); // Create a mock instance of User class with some expected behaviour for testing purpose
Mockito.when(probableUserDataFromDB.getUserName).thenReturn("my unique name");
PowerMockito.mockstatic(User.class); // Readying the static methods for mocking
Mockito.when(User.getCurrentUser).thenReturn(probableUserDataFromDB);// mock static method and return a mocked user instance with some expected behaviour
//continue with your test.................
}
Also read about pros & cons :).
Answered By - NIPHIN
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.