简体   繁体   English

Mockito:模拟并注入一个模拟的类

[英]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: 所以这里只是对它的一些想法:

  • Mockito's approach is that if you can't mock something with Mockito, it probably is badly designed and should be refactored. Mockito的方法是,如果你不能用Mockito嘲笑它,它可能设计得很糟糕,应该重构。 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. Mockito有一些自我限制,所以它可能不适合这项工作。 There are other mocking frameworks that are more powerful and capable of doing this. 还有其他更强大的模拟框架,并且能够做到这一点。

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

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