I am using \"Jersey Test Framework\" for unit testing my webservice.
Here is my resource class :
import javax.ws.rs.GET;
import javax.ws.rs.Path;
imp
Here is how I did it with Jersey 2.20, Spring 4.1.4 RELEASE, Mockito 1.10.8, and TestNG 6.8.8.
@Test
public class CasesResourceTest extends JerseyTestNg.ContainerPerMethodTest {
@Mock
private CaseService caseService;
@Mock
private CaseConverter caseConverter;
@Mock
private CaseRepository caseRepository;
private CasesResource casesResource;
@Override
protected Application configure() {
MockitoAnnotations.initMocks(this);
casesResource = new CasesResource();
AbstractBinder binder = new AbstractBinder() {
@Override
protected void configure() {
bindFactory(new InstanceFactory(caseConverter)).to(CaseConverter.class);
bindFactory(new InstanceFactory(caseService)).to(CaseService.class);
}
};
return new ResourceConfig()
.register(binder)
.register(casesResource)
.property("contextConfigLocation", "solve-scm-rest/test-context.xml");
}
public void getAllCases() throws Exception {
when(caseService.getAll()).thenReturn(Lists.newArrayList(new solve.scm.domain.Case()));
when(caseConverter.convertToApi(any(solve.scm.domain.Case.class))).thenReturn(new Case());
Collection cases = target("/cases").request().get(new GenericType>(){});
verify(caseService, times(1)).getAll();
verify(caseConverter, times(1)).convertToApi(any(solve.scm.domain.Case.class));
assertThat(cases).hasSize(1);
}
}
You also need this class which makes the binding code above a bit easier:
public class InstanceFactory implements Factory {
private T instance;
public InstanceFactory(T instance) {
this.instance = instance;
}
@Override
public void dispose(T t) {
}
@Override
public T provide() {
return instance;
}
}
Edited as pr. request. This is the contents of my test-context.xml:
It turns out that my test-context.xml does not instantiate any beans nor scan any packages, in fact, it does not do anything at all. I guess I just put it there in case I might need it.