AlexWei
AlexWei

Reputation: 93

How can I mock constructor with varargs using PowerMockito?

I have a bean:

class Bean {
    public Bean(String name, Integer number, Resource... resources ) {
        // ...
    }
}

I want to mock constructor of the bean. Here is my test:

@Test
public void shouldReturnMockedBean() throws Exception {
        PowerMockito.whenNew(Bean.class)
                .withArguments(
                        Mockito.anyString(),
                        Mockito.anyInt(),
                        Mockito.<Resource>anyVararg()
                ).thenReturn(beanMock);

        Bean bean = new Bean("abc", 1);

        Assert.assertNotNull(bean);
}

I also use PowerMockito annotation in my test class:

@RunWith(PowerMockRunner.class)
@PrepareForTest({Bean.class})

But I get an error a null instead of my mock. What I'm doing wrong here?

Upvotes: 0

Views: 576

Answers (1)

castletheperson
castletheperson

Reputation: 33496

The varargs is getting set to null instead of creating a varargs where the first element is null.

To fix it, do Bean bean = new Bean("abc", 1, (Resource)null);

See this

If you meant to provide no Resources, however, then just omit the 3rd parameter.

Upvotes: 2

Related Questions