Need help to write a unit test using Mockito and JUnit4

前端 未结 10 1036
余生分开走
余生分开走 2020-12-15 04:06

Need help to write a unit test for the below code using Mockito and JUnit4,

public class MyFragmentPresenterImpl { 
      public Boolean isValid(String value         


        
相关标签:
10条回答
  • 2020-12-15 04:39

    This is a known issue as mentioned by @Exception. In my case, I also stumbled upon same situation but on advice of senior dev decided to use Strings.isNullOrEmpty() instead of TextUtils.isEmpty(). It turned out to be a nice way to avoid it.

    Update: I should better mention it that this utility function Strings.isNullOrEmpty() requires Guava library.

    0 讨论(0)
  • 2020-12-15 04:42

    You should use Robolectric:

    testImplementation "org.robolectric:robolectric:3.4.2"
    

    And then

    @RunWith(RobolectricTestRunner::class)
    class TestClass {
        ...
    }
    
    0 讨论(0)
  • 2020-12-15 04:49

    As a followup to Johnny's answer, to catch TextUtils.isEmpty(null) calls as well, you could use this piece of code.

    PowerMockito.mockStatic(TextUtils.class);
    PowerMockito.when(TextUtils.isEmpty(any()))
        .thenAnswer((Answer<Boolean>) invocation -> {
            Object s = invocation.getArguments()[0];
            return s == null || s.length() == 0;
        });
    
    0 讨论(0)
  • 2020-12-15 04:52

    Use PowerMockito

    Add this above your class name, and include any other CUT class names (classes under test)

    @RunWith(PowerMockRunner.class)
    @PrepareForTest({TextUtils.class})
    public class ContactUtilsTest
    {
    

    Add this to your @Before

    @Before
    public void setup(){
        PowerMockito.mockStatic(TextUtils.class);
        mMyFragmentPresenter=new MyFragmentPresenterImpl();
    }
    

    This will make PowerMockito return default values for methods within TextUtils

    You would also have to add the relevant gradle depedencies

    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"
    
    0 讨论(0)
提交回复
热议问题