Search code examples
androidmockitomockito-kotlin

Mockito - Set default return string value for all mocked methods


I have a class that has over 20 methods that return string values. These strings are not relevant for my test, but it's pretty time consuming to set a when->thenReturn case for each of the functions, specially because there are several of these classes.

Is there a way to tell mockito to default empty string instead of null, or any string value that I wish for that matter?


Solution

  • I created a class to perform this on your project whenever needed, simply init the mock (usually in @Before function)

    myClassMock = mock(MyClass::class.java, NonNullStringAnswer())
    

    NonNullStringAnswer.kt

    /** Used to return a non-null string for class mocks.
     *
     * When the method called in the Mock will return a String, it will return the name of the
     * method instead of null.
     *
     * For all other methods the default mocking value will be returned.
     * 
     * If you want to mock additional methods, it is recommended to use doReturn().when instead on
     * when().thenReturn
     *
     * Example of usage:
     *
     * myClassMock = mock(MyClass::class.java, NonNullStringAnswer())
     *
     **/
    class NonNullStringAnswer : Answer<Any> {
        @Throws(Throwable::class)
        override fun answer(invocation: InvocationOnMock): Any {
            return if (invocation.method.returnType == String::class.java) {
                invocation.toString()
            } else {
                Mockito.RETURNS_DEFAULTS.answer(invocation)
            }
        }
    }