gpt4 book ai didi

java - dropwizard 单元测试抛出 UniformInterfaceException

转载 作者:行者123 更新时间:2023-11-30 03:47:37 29 4
gpt4 key购买 nike

我知道这个问题之前肯定已经被问过一千次了,但 Stackoverflow 上的答案都不适合我。我正在尝试为使用基本身份验证的 Restful api 创建单元测试。 API 代码如下:

@GET
@Timed
@Path("/getAuthPerson/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Person getAuthPerson(@PathParam("id")int id, @Auth Person user) {

/* use HTTP header:
Authorization : Basic dGVzdDpzZWNyZXQ=

For negative test case, use
Authorization : Basic dGVzdDoxMjM=
*/

if(user.getName().isEmpty()) {
return null;
}

Person p = new Person();
p.setName("Test");
p.setId(0);
p.setAge(10);

return p;
}

当我调用浏览器、IDE 或 Fiddler 的 RESTful 客户端时,此 API 起作用,即,当我不提供身份验证 header /不正确的 header 时,我正确地收到 401,并且当我提供正确的 header 时,我能够取回资源。然而,单元测试API拒绝工作,这里是单元测试的代码:

public class PersonResourceTest {
private static final PersonDao personDao = mock(PersonDao.class);

@ClassRule
public static final ResourceTestRule resources = ResourceTestRule.builder()
.addResource(new PersonResource(personDao))
.build();

private static Person getDummyPerson() {
Person person = new Person();
person.setName("John Doe");
person.setBirthDateTime(new DateTime("2012-11-21T13:01:33.568Z"));
person.setAge(10);
return person;
}

private final Person person = getDummyPerson();

@Before
public void setup() {
when(personDao.getPerson(eq(123))).thenReturn(person);
// we have to reset the mock after each test because of the
// @ClassRule, or use a @Rule as mentioned below.
reset(personDao);
}

@Test
public void authenticatedTestGetPositive() {
PersonDao testDao = mock(PersonDaoMongoImpl.class);
testDao.createPerson(person);

WebResource.Builder builder = resources.client().resource("/persons/getAuthPerson/123").getRequestBuilder();
builder.header("Authorization", "Basic dGVzdDpzZWNyZXQ=");
//builder.header("Authorization", "Basic dGVzdDoxMjM=");
builder.accept(MediaType.APPLICATION_JSON);

Person p = builder.get(Person.class);
assertThat(p).isEqualTo(person);
verify(testDao).getPerson(123);
}

}

不涉及身份验证的单元测试工作正常,但是此身份验证单元测试给出了此错误:

    ERROR [2014-08-10 14:48:58,108] com.sun.jersey.spi.container.ContainerRequest: A message body reader for Java class com.rms.pilotapi.core.Person, and Java type class com.rms.pilotapi.core.Person, and MIME media type application/octet-stream was not found.
The registered message body readers compatible with the MIME media type are:
*/* ->
com.sun.jersey.core.impl.provider.entity.FormProvider
com.sun.jersey.core.impl.provider.entity.StringProvider
com.sun.jersey.core.impl.provider.entity.ByteArrayProvider
--snipped---

最佳答案

您需要在 JUnit 测试规则 (@ClassRule) 中注册您的 PersonAuthenticator(或您用于身份 validator 的任何名称)。

问题是 Jersey 尝试反序列化您的参数 @Auth Person user,这应该由您的身份 validator 处理。

关于java - dropwizard 单元测试抛出 UniformInterfaceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25234265/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com