我想在我的REST端点上执行集成测试,但是遇到了问题。
下面是我的终点。注意:我不能更改代码的这一部分。
@Path("/people")
public class PersonResource {
private final PersonService personService;
@Inject
public PersonResource(final PersonService personService) {
this.personService = personService;
}
@GET
@Produces("application/json")
public List<Person> getPersonList() {
return personService.getPersonList();
}
}
从网上可以找到的内容中,我具有以下基本测试结构。
public class PersonResourceTest {
private Dispatcher dispatcher;
private POJOResourceFactory factory;
@Before
public void setup() {
dispatcher = MockDispatcherFactory.createDispatcher();
factory = new POJOResourceFactory(PersonResource.class);
dispatcher.getRegistry().addResourceFactory(factory);
}
@Test
public void testEndpoint() throws URISyntaxException {
MockHttpRequest request = MockHttpRequest.get("people");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
System.out.print("\n\n\n\n\n" + response.getStatus() + "\n\n\n\n\n");
System.out.print("\n\n\n\n\n" + response.getContentAsString() + "\n\n\n\n\n");
}
}
但是,这会导致在setup
方法的最后一行出现以下错误。
java.lang.RuntimeException: RESTEASY003190: Could not find constructor for class: my.path.PersonResource
我探索了Registry
API,并认为也许应该使用addSingletonResource
,所以我将setup
的最后一行更改为dispatcher.getRegistry().addSingletonResource(personResource);
,并添加了以下内容。
@Inject
private PersonResource personResource;
但是这会在NullPointerException
的最后一行产生setup
。
模拟中的sparse documentation并不是很有帮助。谁能指出我要去哪里了?谢谢。
答案 0 :(得分:1)
您需要做两件事
public PersonResource() {
this(null)
}
dispatcher.getRegistry().addSingletonResource(new PersonResource(new PersonService()));
如果需要,可以模拟PersonService类:
private Dispatcher dispatcher;
@Mock
private PersonService service;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
dispatcher = MockDispatcherFactory.createDispatcher();
PersonResource resource= new PersonResource(service);
ispatcher.getRegistry().addSingletonResource(resource);
}
希望有帮助!