Hi everybody,
I've developed a jersey-spring webservice, and when doing unit-tests
with junit, can't get it working.
When the Test class invokes the tested class through a jersey class,
everything works, but the tested class autowired components do not get
injected via spring framework,
so the dao in this example is null, and a null pointer exception is
returned.
Am i doing something wrong ?
Let me explain with an example :
--- Test class ----
@ContextConfiguration(locations={"/test-applicationContext.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class JunitJerseyTest extends JerseyTest {
static AppDescriptor descriptor = null;
@BeforeClass
public static void init() {
descriptor = new WebAppDescriptor.Builder(
"com.mcentric.prism.ws" )
.contextPath("PrismWS" )
.contextParam("contextConfigLocation",
"/test-applicationContext.xml" )
.servletClass(SpringServlet.class )
.contextListenerClass( ContextLoaderListener.class )
.requestListenerClass( RequestContextListener.class )
.build();
}
@Override
public TestContainerFactory getTestContainerFactory() {
return new InMemoryTestContainerFactory();
}
@Override
public AppDescriptor configure() {
return descriptor;
}
@Test
public final void testDataPlan() {
try {
DataPlan plan = resource().path("/HSI/plan/1")
.accept( MediaType.APPLICATION_XML)
.get( DataPlan.class );
Assert.assertNotNull( plan );
Assert.assertEquals( plan.getId(), 1L);
} catch (Exception e) {
Assert.fail();
}
}
--- Tested resource ----
@Path("/{product}/plan/{planid}")
@Component
@Scope("request")
public class Dataplan extends PrismAbstractCommand {
@Autowired
private WSDAOInterface dao;
@PathParam("product") ProductType product;
@PathParam("planid") Long planId;
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@GET
public ReplyBean processRequest() {
ReplyBean reply = new ReplyBean();
if (checkParameters()) {
DataPlan plan = dao.getDataPlan(planId);
if (plan != null) {
LOGGER.info("Retrieved "+plan.getName());
reply.getDataplans().add(new DataplanBean(plan));
} else {
LOGGER.error("There's no plan with id "+planId);
reply.setResultCode(ResultCode.PlanNotAvailable.getErrorCode());
}
}
return reply;
}
}