0

I have some code like this:

class FooBar {
    private String stateFoo;

    public FooBar(String stateFoo){
        this.stateFoo = stateFoo;
    }        

    public void foo() {
        FooInst f = FooInstFactory.createSomeFooInst(AnotherStaticFooConfig.getSomePath);
        f.justCountMe();
    }
}

My goal is to make sure that f.justCountMe() was executed exactly once. I know how to do it in general with mockito. What I don't know is how do I inject a mocked version of FooInst into the foo method? So that I can count the invocation?

Is it even possible to do so?

sveri
  • 1,372
  • 1
  • 13
  • 28

2 Answers2

2

You need to use powermockito and mock static method. See explanation how to do this here

PowerMockito mock single static method and return object

Community
  • 1
  • 1
Nadir
  • 1,369
  • 1
  • 15
  • 28
1

If possible; I suggest to avoid using mocking libraries that temper with static fields (in the way PowerMock/Mockito do) - as it often comes with undesired side effects (for example many "coverage" tools produce invalid results when static mocking takes places).

So my suggestion: re-design your class under test. Instead of fetching f from a static factory; provide a constructor for either the factory or f; then you can mock the corresponding object; without the need to turn to the mighty but dangerous "Powerxyz" stuff.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • I was thinking about this approach too, however, I always hesitate to change "production" code for better testing abilities. – sveri Apr 10 '15 at 06:49
  • @sveri That is why I try to do TDD (test driven development). I try to write test cases before, or at least "at the same" time when writing new production code. And I find so often that "hard to test" equals to "design is worth improving". – GhostCat Apr 10 '15 at 09:38