sveri
sveri

Reputation: 1389

Count method invocation of method variable instance

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?

Upvotes: 0

Views: 87

Answers (2)

GhostCat
GhostCat

Reputation: 140613

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.

Upvotes: 1

Nadir
Nadir

Reputation: 1379

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

PowerMockito mock single static method and return object

Upvotes: 2

Related Questions