我有一个类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
。这是怎么回事?我错过了什么?
试试这个:
@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));
}
}
嘿,我遇到了同样的问题,请试试这个:
@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));