I currently am faced with the following test case: I want to mock the abstract ActorRef class from akka:
@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. So are there any ideas on how to mock that?
The equals method on ClassB uses ClassANeededByClassB to check its equality.
What I could think of to do is to inject a into the mocked class 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.
b
is a mock, so you shouldn't need to inject anything. 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
.
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
.
@RunWith(MockitoJUnitRunner.class)
public class ConstraintBuilderTest {
@Mock
ClassANeededByClassB a;
@InjectMocks
ClassB b;
// ...
}
As you said, Mockito doesn't support mocking equals
. There might be some workarounds but I don't know any. So here's just some thoughts about it in general:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.