问题描述
我正在尝试测试从drowpizard资源返回的视图是否正确组装。具体地说,用于添加用户的视图具有一个字段,该字段允许密码检查器在不满足某些规则的情况下拒绝建立用户的尝试。在部署和运行Webapp并指定错误的密码时,该视图非常有用,但是当我尝试对其进行单元测试时,该视图引发Web应用程序异常,表明该视图没有消息正文编写器。
I'm trying to test that a view returned from a drowpizard resource is assembled correctly. Specifically, the view to add a user has a field that allows a password checker to reject an attempt to build a user if it fails to meet certain rules. The view works great when deploying and running the webapp, and specifying a bad password, but when I try to unit test it, it throws a web application exception saying there's no message body writer for the view.
我的单元测试非常简单:
My unit test is pretty plain:
@Test
public void testBadPassword(){
ClientResponse response = null;
try {
response=client().resource("/users").post(ClientResponse.class, createUserParameters);
Status status = response.getClientResponseStatus();
assertEquals(Status.SEE_OTHER, status);
} finally {
if (response != null) {
response.close();
}
}
}
我拿回服务器500错误,该错误隐藏在以下内容中:
I get back a server 500 error, which has buried within the following:
javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message body writer for Java class com.seeker.stm.resources.views.AddUserView, and Java type class com.seeker.stm.resources.views.AddUserView, and MIME media type text/html was not found
at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:285)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1448)
用于处理请求并生成视图和响应的资源如下:
The resource dealing with the request and generating the views and responses looks like this:
@Path("/users")
public class UserResource {
public Object addUser(@FormParam("username") String username,
@FormParam("password") String password,
@FormParam("email") String email){
Set<String> passwordErrors = passwordChecker.checkValidity(password, username, email);
if (!passwordErrors.isEmpty()) {
return new AddUserView(userDAO.getAllActive(), passwordErrors);
}
// ...
}
I can understand the exception (the writers it knows about, like StringProvider and ByteArrayProvider, don't work for a response or a view or something) but I'd more like to know how to properly test a resource that can return either a response code, or a view.
推荐答案
您需要添加 addProvider(ViewMessageBodyWriter.class);
到您的 setUpResources
。
ViewMessageBodyWriter
是由 ViewBundle
作为提供程序添加的,这就是它在您的服务中起作用的原因(您可能在其中有 bootstrap.addBundle(new ViewBundle( ));
)。
ViewMessageBodyWriter
is added as a provider by ViewBundle
, which is why it works in your service (where you probably have bootstrap.addBundle(new ViewBundle());
).
这篇关于Dropwizard中的单元测试视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!