avy avy - 1 month ago 11
Java Question

how to mock method from same class using junit

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 wotks fine when i use it for another class .
But if i want to mock method from same class it doesnt works.

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

Thanks .

Answer

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().

Comments