dropwizard单元测试抛出UniformInterfaceException

时间:2014-08-11 00:15:45

标签: java rest junit jersey dropwizard

我知道这个问题之前必须要问过一千次,但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;
}

当我调用浏览器的RESTful客户端,我的IDE或来自Fiddler时,这个API有效,即当我没有提供auth标头/不正确的标头时我正确得到401,并且当我提供正确的时候能够取回资源头。但是,单元测试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---

1 个答案:

答案 0 :(得分:2)

您需要在JUnit testrule(PersonAuthenticator)中注册@ClassRule(或您用于身份验证器的名称)。

问题是Jersey试图反序列化您的参数@Auth Person user,该参数应该由您的身份验证器处理。