[英]Mockito: Mock and inject a mocked class
I currently am faced with the following test case: I want to mock the abstract ActorRef class from akka: 我目前面临以下测试用例:我想从akka模拟抽象的ActorRef类:
@RunWith(MockitoJUnitRunner.class)
public class ConstraintBuilderTest {
@Mock
ClassANeededByClassB a;
@InjectMock
ClassB b;
@Before
public void setUp(){
Mockito.when(a.equals(a)).thenReturn(true);
}
//tests go here
}
I know that the mockito page says it cannot mock equals. 我知道mockito页面说它无法模拟等于。 So are there any ideas on how to mock that?
那么有关于如何模仿的想法吗?
The equals method on ClassB uses ClassANeededByClassB to check its equality. ClassB上的equals方法使用ClassANeededByClassB来检查它的相等性。
What I could think of to do is to inject a into the mocked class b. 我能想到的就是在模拟的类中注入一个b。 How best to proceed?
如何最好地进行?
Please be aware that the classes come from a framework which I cannot change, so I cannot change its code to add a setter or anything like that. 请注意,这些类来自一个我无法更改的框架,因此我无法更改其代码以添加setter或类似的东西。
b
is a mock, so you shouldn't need to inject anything. b
是模拟,所以你不需要注入任何东西。 After all it isn't executing any real methods (unless you explicitly do so with by calling thenCallRealMethod
), so there is no need to inject any implementation of ClassANeededByClassB
. 毕竟它没有执行任何真正的方法(除非你通过调用
thenCallRealMethod
明确地这样做),所以不需要注入任何ClassANeededByClassB
实现。
If ClassB
is the class under test or a spy, then you need to use the @InjectMocks
annotation which will inject any matching mocks into ClassB
. 如果
ClassB
是被测试的类或间谍,那么你需要使用@InjectMocks
注释,它将任何匹配的@InjectMocks
注入ClassB
。
@RunWith(MockitoJUnitRunner.class)
public class ConstraintBuilderTest {
@Mock
ClassANeededByClassB a;
@InjectMocks
ClassB b;
// ...
}
As you said, Mockito doesn't support mocking equals
. 如你所说,Mockito不支持嘲笑
equals
。 There might be some workarounds but I don't know any. 可能有一些解决方法,但我不知道。 So here's just some thoughts about it in general:
所以这里只是对它的一些想法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.