問題描述
在使用 Mockito 和 JUnit4 為以下代碼編寫單元測試時需要幫助,
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));
}
}
我嘗試了以下方法:MyFragmentPresenter mMyFragmentPresenter
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));
}
但它返回以下異常,
java.lang.RuntimeException: android.text.TextUtils 中的方法 isEmpty沒有被嘲笑.有關詳細信息,請參閱 http://g.co/androidstudio/not-mocked.在android.text.TextUtils.isEmpty(TextUtils.java) at ....
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 ....
推薦答案
由于JUnit TestCase類不能使用Android相關的API,我們不得不Mock它.
使用 PowerMockito
模擬靜態類.
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
{
}
還有設置代碼
@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);
}
});
}
用我們自己的邏輯實現 TextUtils.isEmpty()
.
That implement TextUtils.isEmpty()
with our own logic.
另外,在 app.gradle
文件中添加依賴項.
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"
感謝 Behelit
和 Exception
的回答.
Thanks Behelit
's and Exception
's answer.
這篇關于需要幫助來使用 Mockito 和 JUnit4 編寫單元測試的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!