1

When I use PowerMock to mock the constructor,I want to specify the type of the paremeters. I use the method

PowerMock.expectNew(Class<T> type, Class<?>[] parameterTypes, Object... arguments)

If I want to specify the String type, what shoud I fill in the parameterTypes?

Touki
  • 7,465
  • 3
  • 41
  • 63
Bort
  • 97
  • 1
  • 13

1 Answers1

4

Given these example classes:

public class MyClass {
    public MyClass(String theParam) {
        //Some interesting code...
    }
}

public class MyFactory {
    public MyClass createMyClass() {
        return new MyClass("foo");
    }
}

Then you would do an expectNew as follows:

public class MyFactoryTest {
    @Test
    public void testCreateMyClass() {
        //...

        PowerMock.expectNew(MyClass.class, new Class[] {String.class}, "foo");

        //...
    }
}
Matt Lachman
  • 4,541
  • 3
  • 30
  • 40
  • Thanks very much,It's very useful.But I'm sorry i can't vote up beacuse of the low reputation. – Bort Aug 29 '13 at 02:13
  • As the author of the question, you can still accept the answer. :-) – Matt Lachman Aug 30 '13 at 17:37
  • hello ,it's me again.when i use Whitebox.invokeConstructor(),what shou I do to specify the parameters' type – Bort Sep 24 '13 at 10:01
  • Read the docs: http://powermock.googlecode.com/svn/docs/powermock-1.5.1/apidocs/org/powermock/reflect/Whitebox.html#invokeConstructor(java.lang.Class, java.lang.Class[], java.lang.Object[]). It has a similar signature to expectNew(). But that's really a different question. – Matt Lachman Sep 24 '13 at 13:13