Я создал класс для выполнения этого в вашем проекте, когда это необходимо, просто инициируйте макет (обычно в функции @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)
}
}
}