java - Mockito - 返回通用类型(多个)

标签 java unit-testing junit mocking mockito

所以基本上我想创建一个返回通用类型的模拟单元测试,对我来说验证该方法确实返回特定对象类型至关重要。任何关于这方面的想法或提示都会有帮助。

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
*/

最佳答案

终于得到了所需的解决方案。这应该可以解决问题,它对我来说是这样的:-

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

关于java - Mockito - 返回通用类型(多个),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41030117/

相关文章:

java - Java Web 应用程序的高级日志记录

java - Android http请求POST

java - fragment 中的Onclick按钮方法

c# - Observable.FromAsync 和 Observable.Switch 的单元测试失败

javascript - Angular : How to properly mock a Promise returned from $http

java - 如何检查测试套件在一个环境中运行缓慢的原因

java - 使用 Java 驱动程序在 Mongodb 中出现超时异常

php - Symfony2 验收测试不起作用

java - Junit 测试 - 测试运行中仅识别一个实例

java - Junit (3.8.1) 测试是否抛出异常(在单元测试中有效,添加到 testSuite 时失败)