Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit-testing Jersey with Mocks

We have a test which extends JerseyTest and we need a mock service injected into it. How can we do this?

Thanks

like image 839
alecswan Avatar asked May 08 '11 23:05

alecswan


1 Answers

Edit : this solution only works with Jersey 1.x, and is therefore quite outdated.

It refers to http://geek.riffpie.com/unit-testing-restful-jersey-services-glued-together-with-spring/ library.

If you use Spring, you can extend AbstractSpringAwareJerseyTest instead of JerseyTest, and inject whatever you need.

As requested, a little snippet of code :

public class MyClassTest extends AbstractSpringAwareJerseyTest{

  @Autowired
  private LdapSetupAndTearDown ldapSetupAndTearDown;

  @Before
  public void setUp2() throws Exception {
    ldapSetupAndTearDown.setUp();
  }

  @After
  public void tearDown2() throws Exception {
    ldapSetupAndTearDown.tearDown();
  }

  public MyClassTest () throws Exception {
    super(new WebAppDescriptor.Builder()
    .contextPath("JSONUserServiceTest")
    .contextParam("contextConfigLocation",
        "classpath:/ctx-config-test.xml,classpath:/ctx-core.xml, classpath:/ctx-jmx-test.xml, classpath:ctx-jersey.xml, classpath:ctx-ldap.xml, classpath:ctx-ldap-test.xml")
    .servletClass(SpringServlet.class).contextListenerClass(ContextLoaderListener.class).build());
  }
like image 55
Samuel EUSTACHI Avatar answered Sep 28 '22 06:09

Samuel EUSTACHI