Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help to write a unit test using Mockito and 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));       } } 

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

but it returns following exception,

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 ....

like image 525
Kadari Avatar asked Mar 03 '16 04:03

Kadari


People also ask

Does Mockito work with junit4?

Mock objects can be created using Mockito JUnit Runner ( MockitoJUnitRunner ). This runner is compatible with JUnit 4.4 and higher, this runner adds the following behavior: Initializes mocks annotated with @Mock , so that explicit usage of MockitoAnnotations#initMocks(Object) is not necessary.

Is Mockito used for unit testing?

Mockito is a Java-based framework used for unit testing of Java applications. This mocking framework helps in the development of testable applications.

Can we use JUnit and Mockito together?

Using JUnit Jupiter's MockitoExtension xml file. This single dependency replaces both the mockito core and the junit dependencies defined above. We then add @ExtendWith(MockitoExtension. class) to the test class and annotate fields that we want to mock with the @Mock annotation.


1 Answers

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 {  } 

And the setup code

@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);         }     }); } 

That implement TextUtils.isEmpty() with our own logic.

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" 

Thanks Behelit's and Exception's answer.

like image 87
Johnny Avatar answered Oct 01 '22 02:10

Johnny