java - PowerMockito - How do I use whenNew() with a typed List? -
i want powermockito return empty array-list of foos when new arraylist<foo>() called, not sure how construct statement. specifically, want new arraylist<anyothertype>() create new list normal.
arraylist<foo> foolist = new arraylist<foo>(); powermockito.whennew(arraylist.class).withparametertypes(foo.class).thenreturn(foolist); ^ here's have, .withparametertypes(foo.class) not allow me follow .thenreturn(). option witharguments(firstargument, additionalarguments).
is possible powermock, , if so, how construct it?
edit:
ok, underlying problem need result of method i'm trying test, had mock request, , list placed in request @ end of method i'm trying test.
inspectionaction.viewinspectiondetailsajax(mapping, form, request, response); this method pulls couple of parameters request, mocked (mockito.mock(httpservletrequest.class);). in our app place data on session-level variable. since method called several times @ once , results ajax'd page, each piece of data stored in request instead:
request.setattribute("inspectionajaxdetails", details); so need way details, typed arraylist, when request mocked.
the short answer is: can't. matt lachman pointed out in comments, can't capture generics of type, can't list<foo> without getting list<bar> , list<anyothertype>. because collections used heavily, bad idea try capture them powermock.
in case, needed list given mocked httpservletrequest attribute (mapped <string, object>) in method trying test. had find different solution. in case, create non-anonymous implementation of answer retrieve values after method run. mockito call looked this:
requestanswer requestanswer = new requestanswer(); mockito.doanswer(requestanswer).when(request).setattribute(matchers.anystring(), matchers.anyobject()); arraylist<foo> details = (arraylist<foo>) requestanswer.getattribute("foo"); my requestanswer class implements answer<object>, , important method looks this:
@override public object answer(invocationonmock invocation) throws throwable { object[] args = invocation.getarguments(); string methodname = invocation.getmethod().getname(); if ("setattribute".equals(methodname)) { string key = (string) args[0]; object value = args[1]; attributes.put(key, value); } else if ("getattribute".equals(methodname)) { string key = (string) args[0]; return attributes.get(key); } else if ("getparameter".equals(methodname)) { string key = (string) args[0]; return parameters.get(key); } return null; } the rest couple of maps , getters , setters.
Comments
Post a Comment