I have a regular JUnit Test Case that tests non-android method logic. The method uses TextUtils for things like TextUtils.isEmpty().
It doesn't make sense to me to make it an AndroidTestCase just to pull in TextUtils class. Is there a better way to instrument this unit test? Like add an android.jar to the test project or something?
Similar situation with another test where I want to mock a Context object. I can't mock it without making it extend AndroidTestCase. What is the best practice in these situations where I'm just trying to test non-android logic and don't want it to run on an emulator, yet it touches some android classes?
Thank you
You have two options to run tests for your Android code. First is the instrumented testing option where you can test your code by connecting a adb to your system.
The second and more functional way is JUnit Testing, where just your Java class is tested and all the other Android related stuff are mocked.
Use PowerMockito
Add this above your class name, and include any other CUT class names (classes under test)
@RunWith(PowerMockRunner.class)
@PrepareForTest({TextUtils.class})
public class ContactUtilsTest
{
Add this to your @Before
@Before
public void setup(){
PowerMockito.mockStatic(TextUtils.class);
mMyFragmentPresenter=new MyFragmentPresenterImpl();
}
This will make PowerMockito return default values for methods within TextUtils
For example let's say your implementation is checking whether a string is empty or not then, in your @Test
when(TextUtils.isEmpty(any(CharSequence.class))).thenReturn(true);
//Here i call the method which uses TextUtils and check if it is returning true
assertTrue(MyFragmentPresenterImpl.checkUsingTextUtils("Fragment");
You would also have to add the relevant gradle depedencies
testCompile "org.powermock:powermock-module-junit4:1.6.2"
testCompile "org.powermock:powermock-module-junit4-rule:1.6.2"
testCompile "org.powermock:powermock-api-mockito:1.6.2"
testCompile "org.powermock:powermock-classloading-xstream:1.6.2"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With