Need help to write a unit test using Mockito and J

2019-03-23 03:45发布

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 ....

9条回答
老娘就宠你
2楼-- · 2019-03-23 04:10

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

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"
查看更多
一夜七次
3楼-- · 2019-03-23 04:11

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

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-03-23 04:15

You should use Robolectric:

testImplementation "org.robolectric:robolectric:3.4.2"

And then

@RunWith(RobolectricTestRunner::class)
class TestClass {
    ...
}
查看更多
Bombasti
5楼-- · 2019-03-23 04:19

I replaces everywhere in my project TextUtils.isEmpty(...) with this:

/**
 * Util class to be used instead of Android classes for Junit tests.
 */
public class Utils {

    /**
     * Returns true if the string is null or 0-length.
     * @param str the string to be examined
     * @return true if str is null or zero length
     */
    public static boolean isEmpty(@Nullable CharSequence str) {
        return str == null || str.length() == 0;
    }
}
查看更多
Rolldiameter
6楼-- · 2019-03-23 04:28

add this line in your gradle file in case of Android Studio.

android{
....
 testOptions {
        unitTests.returnDefaultValues = true
 }
}
查看更多
走好不送
7楼-- · 2019-03-23 04:30

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,

@RunWith(PowerMockRunner.class)
@PrepareForTest(TextUtils.class)
public class YourTest
{

}

And the setup code

@Before
public void setup() {
    PowerMockito.mockStatic(TextUtils.class);
    PowerMockito.when(TextUtils.isEmpty(any(CharSequence.class))).thenAnswer(new Answer<Boolean>() {
        @Override
        public Boolean answer(InvocationOnMock invocation) throws Throwable {
            CharSequence a = (CharSequence) invocation.getArguments()[0];
            return !(a != null && a.length() > 0);
        }
    });
}

That implement TextUtils.isEmpty() with our own logic.

Also, add dependencies in app.gradle files.

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"

Thanks Behelit's and Exception's answer.

查看更多
登录 后发表回答