Saturday 15 May 2010

java - Spring MVC Controller testing, and mocking many classes -



java - Spring MVC Controller testing, and mocking many classes -

we have many controllers in our system, , many spring info repositories.

i write tests controllers run through mvc context.

however, seems pretty cumbersome, , not right, have to, hand, mock every service , repository in system, can test controllers

e.g.

foocontrollertest.java

@runwith(springjunit4classrunner.class) @webappconfiguration @contexthierarchy(value = { @contextconfiguration(classes = { mockservices.class }), @contextconfiguration({ "classpath:/meta-inf/spring/mvc-servlet-context.xml" }), }) public class foocontrollertest { @autowired private webapplicationcontext wac; private mockmvc mvc; @autowired private foorepository foorepository; @autowired private fooservice fooservice; @before public void setup() throws exception { mvc = webappcontextsetup(wac).build(); } @test public final void list() { when(foorepository.findall()).thenreturn(...); mvc.perform(get("/foo"))... } @test public final void create() { foo fixture = ... when(fooservice.create(fixture)).thenreturn(...); mvc.perform(post("/foo"))... } }

mockservices.java

@configuration public class mockservices { @bean public foorespository foorepositiory() { homecoming mockito.mock(foorespository.class); } @bean public fooservice fooservice() { homecoming mockito.mock(fooservice.class); } //even though "only" testing foocontroller, still need mock barcontroller's dependencies, because barcontroller loaded web app context. @bean public barservice barservice() { homecoming mockito.mock(fooservice.class); } //many more "mocks" }

i not want utilize standalonesetup() (want utilize production configuration, eg conversion services, error handlers, etc)

is cost have pay writing controller tests far downwards line?

seems there should mock every class annotated @service or mock every interface extends jparepository

an mvc controller implemented glue code integrates model view. example, when invoking ejb controller , updating view model.

so, controller test may have sence when indeed mock dependencies , verify integration or "glue code" working expected. in general, if integration test implies many components, maybe modularization of whole sut may necessary scheme testable.

anyway, if find integration test laborious, maybe can seek coverage each standalone component , allow functional tests controller coverage.

java spring spring-mvc mockito

No comments:

Post a Comment