Thoppan / powermock

Automatically exported from code.google.com/p/powermock
Apache License 2.0
0 stars 0 forks source link

Mocking of New with array argument #352

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
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 reported on code.google.com by Megafone...@gmail.com on 26 Oct 2011 at 12:07

GoogleCodeExporter commented 9 years ago
I think you need to wrap the array in an Object[] class, e.g.:

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

Original comment by johan.ha...@gmail.com on 31 Oct 2011 at 7:34

GoogleCodeExporter commented 9 years ago
+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
<Stacktrace ommited>

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

Original comment by neillfon...@gmail.com on 2 Apr 2015 at 11:58