【问题标题】:Mockito - Return Generic types ( multiple )Mockito - 返回通用类型(多个)
【发布时间】:2016-12-08 01:09:14
【问题描述】:

所以基本上我想创建一个返回泛型类型的模拟单元测试,对我来说,验证该方法确实返回特定的对象类型是必不可少的。对此的任何想法或提示都会有所帮助。

class Example {
    public AnotherClass<T> generateExampleType( String args ) {
         return new AnotherClass<T> (args);
    }
}

class Another {

     String method1(Type1 a) {
        //
     }

     String method2(Type2 a) {
        //
     }
}

class ClassUnderTest{


   public void methodUnderTest() {

    // code

      AnotherClass<Type1> obj1 = helper.<Type1>generateExampleType("abc");
      AnotherClass<Type2> obj2 = helper.<Type2>generateExampleType("def");

      String one = another.method2(obj2);
      String two = another.method1(obj1); // this fails as part of verify in unit test

    // code
   }
}    

测试

when(helper.<Type1>generateExampleType(anyString()).thenReturn(Obj1Mock);
when(helper.<Type2>generateExampleType(anyString()).thenReturn(Obj2Mock);
verify(another).method2(Obj2Mock);
verify(another).method1(Obj1Mock); // This fails expected Obj1, actually passed Obj2

Obj1 和 Obj2 都用作同一工作流中其他方法调用的一部分。但是,mockito 始终默认为最后创建的(在此实例中为 obj2),并且我的单元测试失败

/*
 Expected class - Type1
 Actually invoked - Type2
*/

【问题讨论】:

  • 为什么要返回泛型类型?
  • generateExampleType 方法没有类型参数。
  • @Tim - 我想返回一个泛型,它是庞大工作流程的一部分
  • @Bubletan 它返回一个特定类型,我确实需要它

标签: java unit-testing junit mocking mockito


【解决方案1】:

终于得到了需要的解决方案。这应该可以解决问题,并且对我有用:-

http://www.agilearts.nl/tasty-test-tip-using-argumentcaptor-for-generic-collections-with-mockito/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 2017-01-21
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    相关资源
    最近更新 更多