Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerMockito: how to mock methods called by the constructor?

I have the following class:

public class Foo {

  public Foo() {
     initField1();
     initField2();
     initField3();
  }

}

I need to change the behaviour (to mock) initField1() and initField3() for them making do nothing or something else that they actually do. I am interested in executing the actual code of initField2().

I want to write the following test:

Foo foo = new Foo();
assertTrue(foo.myGet());

myGet() returns an attribute of Foo that has been computed by initField2().

The initField() methods are of course private.

How can I do such a thing?

Thanks for your help and best regards.

like image 835
Julien Collah Avatar asked Oct 04 '22 05:10

Julien Collah


1 Answers

Considering anything can happen in legacy code :) you can use PowerMock to supress methods as described in http://code.google.com/p/powermock/wiki/SuppressUnwantedBehavior

import static org.powermock.api.support.membermodification.MemberMatcher.methods;
import static org.powermock.api.support.membermodification.MemberModifier.suppress;

@RunWith(PowerMockRunner.class)
@PrepareForTest(Foo.class)
public class FooTest {

    @Test
    public void testSuppressMethod() throws Exception {
        suppress(methods(Foo.class, "initField1", "initField3"));
        Foo foo = new Foo();
    }
}

Still, you should re-factor the class after you've got adequate test coverage for it.

like image 82
denis.solonenko Avatar answered Oct 10 '22 02:10

denis.solonenko