我的问题实际上是在标头中定义的。我正在用Junit,PowerMock和Mockito编写单元测试。我在嘲笑这样的课,

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()));


如何区分这两个“何时”条件?当我运行此测试时,两个“ System.out ..”行均打印“ Some Str 2”。

最佳答案

any*匹配器家族不进行类型检查,应改用isA(Class<T>)

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


或者,使用实际参数,例如:

final Class1ImplementsSameAbstract klass1 = new Class1ImplementsSameAbstract();

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

08-07 05:54