Mockito - 为所有模拟方法设置默认 return 字符串值

Mockito - Set default return string value for all mocked methods

我有一个 class,它有超过 20 个 return 字符串值的方法。这些字符串与我的测试无关,但是为每个函数设置一个 when->thenReturn 案例非常耗时,特别是因为其中有几个 classes.

有没有办法告诉 mockito 默认为空字符串而不是 null,或者我希望的任何字符串值?

我创建了一个 class 以在需要时在您的项目上执行此操作,只需初始化模拟(通常在 @Before 函数中)

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