2016-10-21 7 views
2

I는 다음과 같은 방법으로 클래스 UiUtils 있습니다. 나는 간단한 단위 테스트를 만들고 있었지만 실패했다. 당신은 내가 조롱 EditText를 만드는거야 볼 수 있듯이 나는이 setText과 같은 값을 얻을 것으로 예상테스트 글고 gettext에이 방법

@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.getText() 메서드는 항상 null을 반환합니다. 여기서 무슨 일이 일어나고있는거야? 내가 뭘 놓치고 있니?

+0

'에스프레소'를 사용하여 'UI'를 테스트하십시오. 'getText'는 null을 반환하지 않습니다 – Blackbelt

+0

어떻게 에스프레소로 테스트를 만들 수 있습니까? 이것은 정적 메소드이므로 액티비티 나 프래그먼트를 테스트하지 않을 것입니다. 그렇다면이 테스트를 수행하기 위해 에스프레소로 edittext를 어떻게 만들 수 있습니까? – FVod

답변

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)); 
    } 
} 
+0

감사합니다, 불행히도 이것은 작동하지 않습니다 : ( – FVod

+0

어떤 에러가 발생합니까 – Charu

+0

editText.setText를 할 때 예외가 발생합니다 : java.lang.RuntimeException : android.widget.TextView의 메소드 setText가 조롱되지 않았습니다. http : //g.co/androidstudio/not-mocked (자세한 내용은 – FVod

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()). then return (Editable.Factory.getInstance(). newEditable ("asd"));