-1

Following is my class, where Display class has a static method resultDisplay(). Display class is coming from a jar file. I want to write junit for testCode() method. I am not interested in Display.resultdisplay() call. I just want to verify the content of list in junit.

public class Summation {

    private static final List<Integer> list = new ArrayList<>();
    
    public int testCode(int... a) {
        for(int aa : a)
            list.add(aa);
        return Display.resultDisplay(list);
    }
}
Shankar
  • 113
  • 1
  • 14
  • so ... you want to write a unit test for that unit that doesn't test that unit? – Stultuske Nov 10 '22 at 11:02
  • I have a different logic in actual code, which I can't share here. I want to test all the lines before the particular static method. – Shankar Nov 10 '22 at 11:04
  • is there a getter for that List? if not, good luck. you'll spending more time trying to get around that, than it's worth. Otherwise, if Display.resultDisplay (.. ) doesn't alter the content of the List, it should be pretty straightforward. – Stultuske Nov 10 '22 at 11:06
  • 4
    Wrap your static method in an instance method and mock that class. – tgdavies Nov 10 '22 at 11:06

1 Answers1

0

Mocking static accesses and globals is tricky. Fortunately, every problem can be solved with another layer of indirection:

interface DisplayWrapper {
  int resultDisplay(List<Integer> list);
}
class DisplayWrapperImpl implements DisplayWrapper {
  @Override int resultDisplay(final List<Integer> list) {
    return Display.resultDisplay(list);
  }
}
public class Summation {
    private static final List<Integer> list = new ArrayList<>();

    private final DisplayWrapper display;
    
    public Summation(final DisplayWrapper display) {
      this.display = display;
    }

    public int testCode(int... a) {
        Collections.addAll(list, a);
        return display.resultDisplay(list);
    }
}

Now your class can be easily tested.

Production code:

new Summation(new DisplayWrapperImpl())

Test code:

final DisplayWrapper display = mock(DisplayWrapper.class);
final Summation summation = new Summation(display);
// ...
knittl
  • 246,190
  • 53
  • 318
  • 364