Need help to write a unit test for the below code using Mockito and JUnit4,
public class MyFragmentPresenterImpl {
public Boolean isValid(String value) {
return !(TextUtils.isEmpty(value));
}
}
I tried below method: MyFragmentPresenter mMyFragmentPresenter
@Before
public void setup(){
mMyFragmentPresenter=new MyFragmentPresenterImpl();
}
@Test
public void testEmptyValue() throws Exception {
String value=null;
assertFalse(mMyFragmentPresenter.isValid(value));
}
but it returns following exception,
java.lang.RuntimeException: Method isEmpty in android.text.TextUtils not mocked. See http://g.co/androidstudio/not-mocked for details. at android.text.TextUtils.isEmpty(TextUtils.java) at ....
Use PowerMockito
Add this above your class name, and include any other CUT class names (classes under test)
Add this to your @Before
This will make PowerMockito return default values for methods within TextUtils
You would also have to add the relevant gradle depedencies
I was able to solve this error by running the test class with the following.
@RunWith(RobolectricGradleTestRunner.class) public class MySimpleTest { .....a bunch of test cases }
This wiki page explains in greater detail https://github.com/yahoo/squidb/wiki/Unit-testing-with-model-objects
You should use Robolectric:
And then
I replaces everywhere in my project
TextUtils.isEmpty(...)
with this:add this line in your gradle file in case of Android Studio.
Because of JUnit TestCase class cannot use Android related APIs, we have to Mock it.
Use
PowerMockito
to Mock the static class.Add two lines above your test case class,
And the setup code
That implement
TextUtils.isEmpty()
with our own logic.Also, add dependencies in
app.gradle
files.Thanks
Behelit
's andException
's answer.