powermock / powermock

PowerMock is a Java framework that allows you to unit test code normally regarded as untestable.
Apache License 2.0
4.15k stars 586 forks source link

Mocking of New with array argument #372

Open johanhaleby opened 9 years ago

johanhaleby commented 9 years ago

From Megafone...@gmail.com on October 26, 2011 14:07:21

I have a clas with the following constructor

public Struct(NameValue[] nameValueArray)
{
    _nvs = nameValueArray;
}

that I want to mock. Problem is that I get Unexpected constructor call.

First I tried expectNew with the class and an array, like this:

NameValue[] nameValues = new NameValue[] {nameValueMock,nameValueMock,nameValueMock,}; PowerMock.expectNew(Struct.class,nameValues).andReturn(structMock);

Result:

org.powermock.reflect.exceptions.ConstructorNotFoundException: No constructor found in class 'se.ericsson.cello.neal.cm.Struct' with parameter types: [ se.ericsson.cello.neal.cm.NameValue, se.ericsson.cello.neal.cm.NameValue, se.ericsson.cello.neal.cm.NameValue ].

It seems that each member of the array is treated as an argument.

Then I tried to eclose my array in another array, like this:

Object[] container = new Object[] {nameValues}; PowerMock.expectNew(Struct.class, container).andReturn(structMock);

Result:

java.lang.AssertionError: Unexpected constructor call se.ericsson.cello.neal.cm.Struct([ EasyMock for interface se.ericsson.cello.neal.cm.NameValue, EasyMock for interface se.ericsson.cello.neal.cm.NameValue, EasyMock for interface se.ericsson.cello.neal.cm.NameValue]): se.ericsson.cello.neal.cm.Struct([ EasyMock for interface se.ericsson.cello.neal.cm.NameValue, EasyMock for interface se.ericsson.cello.neal.cm.NameValue, EasyMock for interface se.ericsson.cello.neal.cm.NameValue]): expected: 1, actual: 0

Now, at least, it looks like there is an array sent into the constructor, BUT it still not working.

What shall I do to get it to work?

Original issue: http://code.google.com/p/powermock/issues/detail?id=352

johanhaleby commented 9 years ago

From johan.ha...@gmail.com on October 31, 2011 00:34:47

I think you need to wrap the array in an Object[] class, e.g.:

expectNew(Struct.class, new Object[] {nameValues}). ..

johanhaleby commented 9 years ago

From neillfon...@gmail.com on April 02, 2015 04:58:42

+1 That worked for me.

I would suggested an enhancement on the error message:

org.powermock.reflect.exceptions.MethodNotFoundException: No method found with name 'xyz' with parameter types: [ vargs ]. Have you tried to box them into an Object[] already? in class com.visualmeta.frontend.url.UrlMapperService. at

The documentation is not clear on this and I found very little insight on the web.