简体   繁体   English

如何分离实现相同接口的两个类的函数模拟?

[英]How to separate function mocks of two classes that implement the same interface?

My problem is defined in header, actually. 我的问题实际上是在标题中定义的。 I am writing unit tests with Junit, PowerMock&Mockito. 我正在与Junit,PowerMock和Mockito一起编写单元测试。 I am mocking a class like that, 我在嘲笑这样一个班级,

class User{
       public final synchronized String enter(AbstractClass ac){
       //.....
       }
}

// In test function
User mockUser = PowerMockito.mock(User.class);
PowerMockito.when(mockUser.enter( Mockito.any(Class1ImplementsSameAbstract.class)))
            .thenReturn("Some Str 1");
PowerMockito.when(mockUser.enter( Mockito.any(Class2ImplementsSameAbstract.class)))
            .thenReturn("Some Str 2");

System.out.println(mockUser.enter(new Class1ImplementsSameAbstract()));
System.out.println(mockUser.enter(new Class2ImplementsSameAbstract()));

How can I separate these two "when" conditions? 我怎样才能将这两个“何时”的条件分开? When I run this test, both of the "System.out.." lines print "Some Str 2". 当我运行此测试时,两个“System.out ..”行都打印“Some Str 2”。

The any* family of matchers do not do type checking, you should use isA(Class<T>) instead: any*系列的匹配器不进行类型检查,你应该使用isA(Class<T>)代替:

PowerMockito.when(mockUser.enter(Mockito.isA(Class1ImplementsSameAbstract.class)))
        .thenReturn("Some Str 1");

Or alternatively, use the actual arguments, eg: 或者,使用实际参数,例如:

final Class1ImplementsSameAbstract klass1 = new Class1ImplementsSameAbstract();

PowerMockito.when(mockUser.enter(klass1)).thenReturn("Some Str 1");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何为实现相同接口的两个类制作双向适配器? - How to make bidirectional adapter for two classes that implement the same interface? 在Java中,如何区分实现相同接口的类? - In Java, how to distinguish classes that implement the same interface? 如何使用迭代器为两个类实现接口 - How to implement an interface for two classes with an iterator 如何知道两个类是否实现一个公共接口? - How to know if two classes implement a common interface? 如何注入实现同一接口的两个不同类的两个实例? - How to inject two instances of two different classes which implement the same interface? 如何给两个不同的类相同的接口? - How to give two different classes the same interface? 如何注入同一接口的多个模拟 - How to inject multiple mocks of the same interface 如何创建两个具有相同名称,签名和返回类型的方法的类,就像它们实现相同的接口一样 - How to make two classes which both have method with the same name, signature and return type behave like they would implement the same interface 如何在仅使用批注实现相同接口的不同类中使用@autowired - How to use @autowired in different classes that implement the same interface with only annotations 如何实例化(在方法内部)实现同一接口的不同类? - How to instantiate (inside a method) different classes that implement the same interface?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM