java.lang.RuntimeException:android.text.TextUtils中的方法isEmpty未被模拟

时间:2018-06-18 14:35:19

标签: android mockito

loginUnit.java(测试文件)

@RunWith(MockitoJUnitRunner.class)
public class loginUnit {
    @Mock
    TextUtils mMockTextUtils;

    @Test
    public void checkStringEmpty(){

        String empty = "";
        when(mMockTextUtils.isEmpty(empty)).thenReturn(true);
        assertThat(LoginActivity.isStringEmpty(empty),is(equalTo(true)));
    }

来自LoginActivity的UUT(受测试单元)

public static boolean isStringEmpty(String s){
        return TextUtils.isEmpty(s);
}

我总是得到android.text.TextUtils没有模拟错误,请帮帮我?

2 个答案:

答案 0 :(得分:2)

在你的src / test / java文件夹中,添加android.text包并创建TextUtils.java

public class TextUtils {
  public static boolean isEmpty(CharSequence str) {
    return str == null || str.length() == 0;
  }
}

详细信息:https://medium.com/@okmanideep/dont-create-that-stringutils-to-unit-test-your-android-class-8ab32af34e84

答案 1 :(得分:0)

http://tools.android.com/tech-docs/unit-testing-support#TOC-Method-...-not-mocked.-

android {
  // ...
  testOptions { 
    unitTests.returnDefaultValues = true
  }
}