【问题标题】:Mockito - Set default return string value for all mocked methodsMockito - 为所有模拟方法设置默认返回字符串值
【发布时间】:2020-02-07 18:01:02
【问题描述】:

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

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

【问题讨论】:

    标签: android mockito mockito-kotlin


    【解决方案1】:

    我创建了一个类来在您的项目上执行此操作,只要需要,只需初始化模拟(通常在 @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)
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-11-27
      • 2022-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多