1

I want to test public methodToTest().

public class MyClass {
    private String id;

    public MyClass(String id) {}

    public Object methodToTest() {
        res = internalMethod();
        // logic on res
        return res;
    }

    private internalMethod() {
        foo = LegacyClass(id);
        res = foo.doSomething(); // DB operations here
        return res;
    }
}

public class LegacyClass {
    private static DB db = DefaultDb();
    private String id;

    public LegacyClass(String id) {}
 
    public Object doSomething() {
        return db.foo(id);
    }
}

In my test, I've tried:

  • @Mock on DB: not work. because can not @InjectMocks on LegacyClass instance as it is created inside internal method
  • @Spy on MyClass instance and doReturn-when on internalMethod (make it visible for test): not work. maybe it's some limitation on @Spy.

Is there any options except using PowerMock?

cosimoth
  • 167
  • 10
  • Would it not be possible to mock LegacyClass? (After some refactoring of course, to e.g. inject the legacy class into MyClass.) – Double_A Dec 13 '21 at 14:34
  • Mockito works via overriding methods, and `private` methods aren't usually available for override because they're not visible outside the class definition. You're going to either need to make minimal changes to your class under test (e.g. extract the construction of LegacyClass to an mockable/overridable method) or use PowerMock. See the full list here: [How to use Mockito when we cannot pass a mock object to an instance of a class](https://stackoverflow.com/q/27552499/1426891) – Jeff Bowman Dec 13 '21 at 19:45

0 Answers0