1

I am using JUnit and my situation is as follow:

class A{
    public int[] method1(){
       ...
       int res = method2();
       ...
       return intArray;
    }

    public int method2(){
      ....
      return intA;
    }
}

I am trying following to mock the method2()

new MockUp<MockClass>() {
            int[] methodToMock() {
                int[] mockedResult = {1, 2, 4, 6};
                return mockedResult;
            }
        };

Above code works fine when i use it for another class . But if i want to mock method from same class it doesn't works.

please guide me to find the mocking method in JUnit, to mock method from same class.

Thanks.

4
  • At first you should ask yourself why do you want to mock method2? Does it contain behavior that is out of scope of the rest of the class? Shold it be moved to some other, if not its own class? Commented Nov 1, 2016 at 12:48
  • You did not tell which mocking framework you use. If you'd use Mockito you could create a spy for the class under test and configure the alternative behavior for method2. Commented Nov 1, 2016 at 12:49
  • @TimothyTruckle I am using JMockit. Commented Nov 1, 2016 at 12:52
  • i cant move this method to any other class . And this method is also used some where else so i cant club it in one. Commented Nov 1, 2016 at 12:55

1 Answer 1

2

public method which calls another public method of the same class is not necessary a problem in software development but it creates an inner coupling in your class and may be sign of too much responsibilities in the class. It is not necessary always true but the question may be asked.
The proof : here, unit testing becomes harder without tricking.

i cant move this method to any other class . And this method is also used some where else so i cant club it in once.

With these constraints, I propose you keep these two public methods and introduce a new class which factors the common behavior of the two methods.
The two public methods can now rely on the common class to do the processing.

class A{

  private CommonProcess commonProcess;

  public int[] method1(){
   ...
   int res = commonProcess.method(...);
   ...
   return intArray;
  }

  public int method2(){
   ....
   commonProcess.method(...);
   ...
   return intA;
  }
}

Now, to mock the external dependency in method2 or method1, just mock the call to commonProcess.method().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.