我有一个类UiUtils
,其方法如下:
public static String getEditTextValue(final EditText editText) {
if(editText == null) return null;
final Editable text = editText.getText();
if(text == null) return null;
return text.toString();
}
然后我想将单元测试添加到该类。我正在创建一个简单的单元测试,但这是失败的。我已经做到了:
@RunWith(MockitoJUnitRunner.class)
public class UiUtilsTest {
@Mock
EditText editText;
@Test
public void getEditTextValue_ReturnsValueString() {
final String value = "text";
editText.setText(value);
Assert.assertEquals(value, UiUtils.getEditTextValue(editText));
}
}
正如您所看到的,我创建了一个模拟的EditText
,然后我setText
并希望获得相同的值。但由于某种原因,editText.getText()
方法始终返回null
。这里发生了什么?我错过了什么?
答案 0 :(得分:0)
试试这个:
@RunWith(MockitoJUnitRunner.class)
public class UiUtilsTest {
@Mock
EditText editText;
@Test
public void getEditTextValue_ReturnsValueString() {
final String value = "text";
Mockito.doCallRealMethod().when(editText).setText(value);
Mockito.doCallRealMethod().when(editText).getText();
editText.setText(value);
Assert.assertEquals(value, UiUtils.getEditTextValue(editText));
}
}
答案 1 :(得分:0)
嘿我遇到了同样的问题,请试试这个:
@Before
public void init() {
MockitoAnnotations.initMocks(this);
when(rootView.findViewById(R.id.button_logout)).thenReturn(buttonLogout);
when(rootView.findViewById(R.id.button_unlock)).thenReturn(buttonUnlock);
when(rootView.findViewById(R.id.ScreenLock_PasswordTextField)).thenReturn(passwordField);
when(passwordField.getText()).thenReturn(Editable.Factory.getInstance().newEditable("asd"));
when(application.getPassword()).thenReturn("asd");
sut = new ScreenLockPresenterImpl(application, rootView, screenLockListener,
logoutButtonClickListener);
}
@Test
public void testOnClickWhenOk() {
sut.onClick(null);
verify(passwordField).getText();
verify(screenLockListener).unLock();
}
我认为这就是你要找的东西: 的当(passwordField.getText())thenReturn(Editable.Factory.getInstance()newEditable( “ASD”)。); 强>