简体   繁体   中英

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:

@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:

  • Mockito's approach is that if you can't mock something with Mockito, it probably is badly designed and should be refactored. I know it's not your code, and that actually leads to the next point:
  • "Don't test the framework". You likely don't need to test this part at all - it should be the responsibility of the frameworks creators to test it. You could try to contribute a patch if it is an open source project.
  • Mockito has some self-imposed limitations, so it might just not be the right tool for this job. There are other mocking frameworks that are more powerful and capable of doing this.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM