Vishal Kaushik
Vishal Kaushik

Reputation: 68

Mockito mock testing for nested functions calls

I have a serious conceptual problem with mock testing in a scenario of nested function calls. I'm using JUnit and Mockito in my project. Let me explain my problem with following example:-

public class ClassA {
        public void methodOne(param1, param2, param3, param4) {
            // do something

            String temp = methodTwo(param2, param3, param4);

            // do something
        }

        public String methodTwo(param2, param3, param4) {
            // do something

            return methodThree(param2, param3) + methodFour(param4);
        }

        public String methodThree(param2, param3) {
            // do something
            return param2.get(0).getIndex + ":" + param3.getPosition();
        }

        public String methodFour(param4) {
            // do something

            return param4.getDetail() + "|" + param4.getCount();
        }
    }

If we have to test the basic methods like methodThree() and methodFour(), we can create mocks of required params with required stubbing (to support the executtion of function being tested) and do the execution and verification (state/behavior) there after.

But what about the methods like methodTwo(), having nested calls to other functions which have already been tested as a separate unit. If we pass mock objects into methodTwo(), they will be passed into the nested methods and will give NullPointerException() as these mocks were not stubbed as per the need of nested function calls. Surely, we can add extra stubbing to the mocks to support smooth execution in nested calls too, but clearly this is not a healthy approach. This burden of stubbing will aggravate further as we move up to the large methods like methodOne() or the some other.

As far as Unit testing is concerned, we don't care about other units beside the one being tested. Please guide me where am I being wrong and suggest a better/proper way of Unit and mock testing. Thanks.

Upvotes: 1

Views: 1918

Answers (1)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79838

My thought here is that methodOne and methodTwo each meet some kind of specification, in terms of what behaviour they should have. The fact that you chose to implement each of these via calls to other methods of the same class is irrelevant; you should test that their behaviour is correct. So don't look at the implementation when you write the test - instead, look at the specification.

Of course, if you choose to ignore my advice, you can always use a Mockito spy, and stub out some methods while you test others. But seriously, don't.

Upvotes: 1

Related Questions