JMockit and some local methods

Say I have a MyClass class with methods x() , y() and z() . Say x() calls y() and y() calls z() .

So every time I test x() , both y() and z() called. In case of abuse of the MyClass dependencies, I will have to mock the behavior of the dependencies inside x() , y() and z() .

So, if my tests for method x() are equal to testXWhen1() , testXWhen2() and testXWhen3() , I will have to repeat the expectations for my dependencies in each of the testing methods. In the end, I have code with expectations for what happens inside y() and z() , repeated for my three testing methods. Any solution to avoid this?

One of my ideas was to try and test the actual method x() , but taunt y() and z() . In this case, my MyClass instance should be partially mock and partially real MyClass . Is it possible?

Another solution was to be strict regarding expectations in x() , but not about what happens in y() and z() ... I think I can do this with @NonStrict instead of @Mocked , but that doesn't my favorite decision.

+4
source share
3 answers

If you want to test the x() method, then you have to mock the y() method. In this case, there is no need to mock z() , because you will never reach the call to z() inside y() (y is mocking). Test your x, y and z methods in different tests. Use PowerMock.It has a createPartialMock method.

+2
source

In the end, I have code with expectations for what happens inside y () and z (), repeated for my three testing methods. Any solution to avoid this?

Have you tried the extraction method refactoring?

Another solution was to be strict regarding expectations in x (), but not about what happens in y () and z () ...

This is exactly what I do when testing a certain part of the functionality (albeit using JMock). If the behavior I'm testing is not dependent on the result of dependency calls, I will explicitly use JMock, ignoring / allowing expectations. This makes the goal of the test much clearer and focuses on what exactly is being tested.

0
source

You can use the JMockit dynamic partial partial function by passing a class or object that will partially mock the Expectations/NonStrictExpectations .

In general, however, it is better to avoid the use of partial bullying, as this often indicates a lack of cohesion in the tested code and leads to more difficult to understand results.

In cases where there are many expectations in several tests, there is always the possibility of creating reusable blocks. You can encapsulate a series of expectations in a subclass of " XyzExpectations ", optionally with parameterized constructors, and create it in any number of tests (actually created by a subclass of "expectations" should be final ). The same can be done with test blocks.

0
source

Source: https://habr.com/ru/post/1386047/


All Articles