Monday, January 20, 2014

Parameterised tests with TestNG

My previous posts on this blog have both been about how wonderful it is to be able to run exactly the same tests against client and server side code. However, actually doing that is a little bit clunky in JUnit, requiring you to create a separate test method for each implementation of your interface. At best you can do this:
@Test
public void testGetCustomerById_Service() {
    doTestGetCustomerById(service);
}

@Test
public void testGetCustomerById_Client() {
    doTestGetCustomerById(client);
}

public void doTestGetCustomerById(CustomerService service) {
    int id = random.nextInt();
        
    Customer expected = new Customer(id);
    when(customerDao.getById(id)).thenReturn(expected);
        
    Customer actual = service.getCustomerById(id);
    assertEquals(expected, actual);
}
Your choice is between writing 3 methods for each test, or 2 methods containing identical code. Here's something better you can do if you're using TestNG.
@Test(dataProvider = "myProvider")
public void testGetCustomerById(CustomerService service) {
    int id = random.nextInt();
        
    Customer expected = new Customer(id);
    when(customerDao.getById(id)).thenReturn(expected);
        
    Customer actual = service.getCustomerById(id);
    assertEquals(expected, actual);
}

@DataProvider(name = "myProvider")
public Object[][] provider() {
    return new Object[][] {{service}, {client}};
}
That Object[][] looks a bit ugly, but the results are great. Now you have 1 method per test, plus 1 data provider method for the whole test class. The first dimension of the returned array represents each run of the test, while the second allows you to pass multiple parameters. Here's a (slightly contrived) example testing a calculator implementation.
@Test(dataProvider = "myProvider")
public void testAddition(int a, int b, int expectedResult) {
    int result = calculator.calc(a + "+" + b);
    assertEquals(expectedResult, result);
}

@DataProvider(name = "myProvider")
public Object[][] provider() {
    return new Object[][] {{ 1, 2, 3 }, { 4, 5, 9 }, { 10, 11, 21 }};
}
And you can use the same provider to test subtraction.
@Test(dataProvider = "myProvider")
public void testSubtraction(int expectedResult, int b, int a) {
    int result = calculator.calc(a + "-" + b);
    assertEquals(expectedResult, result);
}

Monday, January 13, 2014

JAX-RS exception handling using CXF

One thing that I think is very important when implementing a RESTful service is to use the appropriate HTTP response codes for error statuses. JAX-RS provides a few ready-made exceptions that do this, so my getCustomerById method from the previous post can throw a NotFoundException if the customer does not exist.

But I'm using an underlying API that throws an exception if it receives too many requests in a short space of time. JAX-RS doesn't provide a TooManyRequestsException so I'll have to make one of my own.
public class TooManyRequestsException extends WebApplicationException {

    public TooManyRequestsException() {
        super(429);
    }

}
And here's a test for it:
@Test(expected=TooManyRequestsException.class)
public void testGetCustomerById_tooManyRequests() {
    int id = random.nextInt();
        
    when(customerDao.getById(id)).thenThrow(new TooManyRequestsException());
        
    customerService.getCustomerById(id);
}
The test above works as a unit test, but as an integration test using the client the exception caught is ClientErrorException. The CXF client doesn't know how to deal with the 429 status code and, frustratingly, CXF doesn't give us any mechanism to register a custom exception on the client side.

Fortunately, a little digging around in the source code reveals a workaround. The class JAXRSUtils contains a static map of exception classes mapped to HTTP status codes. When it receives an HTTP response with an error status it attempts to instantiate one of these exceptions using a constructor that takes a JAX-RS Response object. So I'll add that constructor to my TooManyRequestsException.
public TooManyRequestsException(Response response) {
    super(response);
}
The map is private, so we have to do some reflection hackery to get it in there. You can put this code anywhere it will be run by the client, such as a static block, but I decided the best thing for me was to create my own custom JAXRSClientFactory.
public class CustomJAXRSClientFactory {

    private final String url;

    private final List<Object> providers = new ArrayList<>();

    public VCommsManJAXRSClientFactory(String url) {
        registerExceptions();

        this.url = url;
        providers.add(new JacksonJsonProvider());
    }

    /** This is where we register the exceptions with the CXF client */
    private void registerExceptions() {
        try {
            Field f = JAXRSUtils.class.getDeclaredField("EXCEPTIONS_MAP");
            f.setAccessible(true);
            Map<Integer, Class<?>> m = (Map<Integer, Class<?>>) f.get(null);

            m.put(429, TooManyRequestsException.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public <T> T create(Class<T> serviceInterface) {
        JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
        bean.setProviders(providers);
        bean.setAddress(url);
        bean.setServiceClass(serviceInterface);
        return bean.create(serviceInterface);
    }

}
Now I replace the client code in my test with this:
CustomJAXRSClientFactoryBean clientFactory = new CustomJAXRSClientFactoryBean("http://localhost:9090");
customerService = clientFactory.create(CustomerService.class);
And my integration test passes :)

Tuesday, January 07, 2014

Using CXF as a JAX-RS server and client

I recently implemented a JAX-RS service and client using CXF and I think it's brilliant. Why? Because here's a unit test for my service code:
@Test
public void testGetCustomerById() {
    int id = random.nextInt();
        
    Customer expected = new Customer(id);
    when(customerDao.getById(id)).thenReturn(expected);
        
    Customer actual = customerService.getCustomerById(id);
    assertEquals(expected, actual);
}
And here's an integration test using the client:
@Test
public void testGetCustomerById() {
    int id = random.nextInt();
        
    Customer expected = new Customer(id);
    when(customerDao.getById(id)).thenReturn(expected);
        
    Customer actual = customerService.getCustomerById(id);
    assertEquals(expected, actual);
}
Yup, they're the same test! This makes me happy.

So, how is it done? We'll start with the service interface.
@Path("/customer")
public interface CustomerService {
    
    @GET
    @Path("/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    Customer getCustomerById(@PathParam("id") int id);
}
And an implementation that satisfies the unit test above.
public class CustomerServiceImpl implements CustomerService {
    
    @Inject CustomerDao customerDao;

    @Override
    public Customer getCustomerById(int id) {
        return customerDao.getById(id);
    }
}
Wiring up the unit test is simple, so here's what the integration test looks like in full:
public class CustomerServiceClientTest {
    
    // This is the client
    private CustomerService customerService;

    // CXF JAX-RS server
    private Server server;

    private Random random = new Random();

    @Before
    public void before() {
        CustomerServiceImpl serviceImpl = new CustomerServiceImpl();
        serviceImpl.customerDao = mock(CustomerDao.class);

        JAXRSServerFactoryBean serverFactory = new JAXRSServerFactoryBean();
        serverFactory.setAddress("http://localhost:9090");
        serverFactory.setProvider(new JacksonJsonProvider());
        serverFactory.setServiceBean(serviceImpl);
        server = serverFactory.create();

        JAXRSClientFactoryBean clientFactory = new JAXRSClientFactoryBean();
        clientFactory.setAddress("http://localhost:9090");
        clientFactory.setProvider(new JacksonJsonProvider());
        clientFactory.setServiceClass(CustomerService.class);
        customerService = clientFactory.create();
    }

    @After
    public void after() {
        service.destroy();
    }

    @Test
    public void testGetCustomerById() {
        int id = random.nextInt();
        
        Customer expected = new Customer(id);
        when(customerDao.getById(id)).thenReturn(expected);
        
        Customer actual = customerService.getCustomerById(id);
        assertEquals(expected, actual);
    }
}
The key thing here is the JAXRSClientFactoryBean, which creates an implementation of CustomerService that makes calls to the RESTful service running at localhost:9090.

What this means is that if you publish an artifact containing just the interface, your client-side project can make use of your RESTful service by directly calling the interface methods in Java, hiding the JAX-RS mechanics completely.