Stubbing of mockito mock object on spock-based test -
i'm using spock fw mockito. have controller named 'hostcontroller' , service named 'hostservice'.
the 'hostcontroller' has method called host(long id)
, 'hostservice' has method called findone(long id)
.
i want test hostcontroller#host(long id)
, think of stubbing findone(long id)
method.
follow test code:
class mocktest extends specification { @mock private hostservice mockedservice; @injectmocks private hostcontroller controller; def setup() { mockitoannotations.initmocks(this); } def "mock test"() { given: def host = new host(id: 1, ipaddress: "127.0.0.1", hostname: "host1") mockedservice.findone(_) >> host when: map<string, object> result = controller.host(1) then: result.get("host") != null } }
in above test, controller.host(1)
return map<string, object>
type , has key named host
. assumed key hasn't null value, has null value.
why doesn't work think?
i found 1 of solutions.
in above example, tried stub hostservice#findone(long id)
method using spock mockedservice.findone(_) >> host
. perhaps seems not fit mock object of mockito.
rene enriquez introduce spock mock me. works well. however, want use @injectmocks , @mock. that, follow mockito mocking , stubbing instruction.(thank you, enriquez)
modified example is:
import static org.mockito.mockito.when; class mocktest extends specification { @mock private hostservice mockedservice; @injectmocks private hostcontroller controller; def setup() { mockitoannotations.initmocks(this); } def "mock test"() { given: def host = new host(id: 1, ipaddress: "127.0.0.1", hostname: "host1") when(mockedservice.findone(1)).thenreturn(host) when: map<string, object> result = controller.host(1) then: result.get("host") != null } }
we can use mockito stubbing, not spock's. works well!
Comments
Post a Comment