How to mock another method in the same class which is being tested?

后端 未结 2 1688
自闭症患者
自闭症患者 2020-12-10 15:34

I am writing JUnit Test case for a class which has two methods methodA,methodB. I would like to mock the call to the methodB from methodA in my test case I am using spy on

相关标签:
2条回答
  • 2020-12-10 16:07

    Taking this approach will result in brittle tests which will need to change if you refactor your class under test. I would highly recommend that you try to assert your expected test results by checking state of SomeClass rather than relying on mocks.

    If you do indeed need to mock MethodB then this is an indication that maybe the behaviour in MethodB actually belongs in a separate class which you could then test the interaction of SomeClass with via mocks

    if you do indeed need to do what you ask for then a PartialMock is what you want.

    you probably want to create a partial mock of some class but indicate that calls to MethodA should call the actual method but then mock MethodB

    You can see how to use them in the Mockito documentation

    As stated in their documentation though Partial mocks are a code smell, though they have identified some explicit use cases.

    0 讨论(0)
  • 2020-12-10 16:20

    I ran into this yesterday, for spies is best to do doReturn(X).when(spy).method(any())

    0 讨论(0)
提交回复
热议问题