2013-08-21 77 views
3

我有一组类可以在项目中使用REST方法。他们是这样的:如何使用Arquillian测试RESTful方法?

@Path("customer/") 
@RequestScoped 
public class CustomerCollectionResource { 

    @EJB 
    private AppManager manager; // working with DB 

    @GET 
    @Produces(MediaType.APPLICATION_JSON) 
    public Response list(@QueryParam("email") String email) { 
     final List<Customer> entities = manager.listCustomers(email); 
     // adding customers to result 
     return Response.ok(result).build(); 
    } 
} 

,我已经写了测试方法后:

@RunWith(Arquillian.class) 
public class CustomerResourceTest { 

@Deployment 
public static WebArchive createTestArchive() { 
     return ShrinkWrap.create(WebArchive.class, "test.war") 
     // Adding omitted         
     //.addClasses(....)     
    } 

    @Test @GET @Path("projectName/customer") @Consumes(MediaType.APPLICATION_JSON) 
    public void test(ClientResponse<List<Customer>> response) throws Exception { 
    assertEquals(Status.OK.getStatusCode(), response.getStatus());  
    } 
} 

,并试图运行这个测试时,我得到NullPointerException异常。这是因为在测试案例中空洞的回应。为什么发生这种情况?数据库配置正确。

回答

8

arquillian测试可以运行两种模式:容器内和客户端模式。 HTTP接口只能在客户端模式下测试(从来没有尝试过扩展,只使用了香草Arquillian)。

默认情况下,由arquillian测试运行器servlet调用的容器上下文中执行的测试方法。

@RunWith(Arquillian.class) 
public class CustomerResourceTest { 

    @EJB SomeBean bean; // EJBs can be injected, also CDI beans, 
         // PersistenceContext, etc 

    @Deployment 
    public static WebArchive createTestArchive() { 
     return ShrinkWrap.create(WebArchive.class, "test.war") 
     // Adding omitted         
     //.addClasses(....)     
    } 

    @Test 
    public void some_test() { 
     bean.checkSomething(); 
    } 
} 

在客户端模式下,测试方法是运行在容器外,因此您不必访问的EJB的,但EntityManager等注入测试类,但你可以为检测注入的URL参数方法。

@RunWith(Arquillian.class) 
public class CustomerResourceTest { 

    // testable = false here means all the tests are running outside of the container 
    @Deployment(testable = false) 
    public static WebArchive createTestArchive() { 
     return ShrinkWrap.create(WebArchive.class, "test.war") 
     // Adding omitted         
     //.addClasses(....)     
    } 

    // baseURI is the applications baseURI. 
    @Test 
    public void create_account_validation_test (@ArquillianResource URL baseURI) { 
    } 

您可以使用此URL参数来构建网址中使用您有任何方法,如新的JAX-RS客户端API调用你的HTTP服务。

您也可以混合使用这两种模式:

@RunWith(Arquillian.class) 
public class CustomerResourceTest { 

    @EJB SomeBean bean; 

    @Deployment 
    public static WebArchive createTestArchive() { 
     return ShrinkWrap.create(WebArchive.class, "test.war") 
    } 

    @Test 
    @InSequence(0) 
    public void some_test() { 
     bean.checkSomething(); 
    } 

    @Test 
    @RunAsClient // <-- this makes the test method run in client mode 
    @InSequence(1) 
    public void test_from_client_side() { 
    } 
} 

这是有时甚至是必要的,因为一些扩展,如持久性可以在客户端模式无法运行。

相关问题