java - how test returned object from a mocked dependency that accepts two arguments inside the mocked object? -
i couldn't find post related problem. i'm using mockito , want test behavior within controller. think core of problem i'm not using mockito correctly when send in 2 arguments mocked interface. works fine if send in 1 argument. don't think fact i'm using spring mock mvc has this.
i have interface myservice:
public myobject dosomedoggystuff(long id, someotherobject soo); the purpose of interface things , homecoming myobject if successful. if can't find object homecoming null.
i have controller mycontroller:
@restcontroller @requestmapping(value = "/dogs") public mycontroller <snip> @requestmapping(method = requestmethod.post, value = "/{id}/toys/{toy}") responseentity<myobject> dodoggystuff(@pathvariable long id, @requestbody toy toy) { myobject result = this.myservice.dosomedoggystuff(id, toy); if(result == null) { homecoming new responseentity("errorinfo", httpstatus.not_found); } else { homecoming new responseentity<myobject>(result,httpstatus.created)' } } my test class looks this:
public mycontrollertest <snip> @mock private myservice myservicemock; @injectmocks private mycontroller mycontroller; the relevant logic of test method looks this.
myobject myobj = new myobject(); toy toy = new toy(); when(myservicemock.dosomedoggystuff(1, toy)).thenreturn(myobj); mockmvc .perform( post("/dogs/{id}/toys/{toys}", 1, toy).contenttype( testutil.application_json_utf8).content( testutil.convertobjecttojsonbytes(toy))).andexpect(status().iscreated()) .andreturn(); the problem i'm having expect in scenario when tests mycontroller on line: myobject result = this.myservice.dosomedoggystuff(id, toy);
result should myobj set in thenreturn it's set null. have other methods in service accepts 1 argument , works fine. can't grasp need differently when send in 2 arguments using mockito.
if understand requirements correctly should utilize mock this:
when(myservicemock.dosomedoggystuff(eq(1), any(toy.class))).thenreturn(myobj);
the way have written code, mock homecoming myobj when called toy object instantiated with, never since spring instantiate class on it's own. problem doesn't have number of arguments.
if want test specific toy , not instance of it, need add together equals (and right spec, hashcode) method mockito can match toys. in absence of equals method, references checked , of couse not equals because instances not same.
java unit-testing mockito mockmvc
No comments:
Post a Comment