0

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

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

4

1 回答 1

0

我创建了一个类来在需要时在您的项目上执行此操作,只需初始化模拟(通常在@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)
        }
    }
}
于 2020-02-07T18:17:54.053 回答