Posts Tagged ‘testing’

Unit Test Private Java Methods using Reflection

Thursday, May 5th, 2011

Introduction

I realise that the thought of Unit Testing private methods in Java classes can be like a red rag to a bull for some people and I understand the arguments.

Therefore, I present the following as a “how to”, not a moral argument for or against!

Example

The class under test

public class Product() {
    private String privateMethod(String id) {
    //Do something private
    return "product_" + id;
  }
}

The (Reflection Based) Unit Test

import java.lang.reflect.Method;

import static org.junit.Assert.*;
import org.junit.Test;

public class ProductTest {
    private Product product; // the class under test
    private Method m;
    private static String METHOD_NAME = "privateMethod";
    private Class[] parameterTypes;
    private Object[] parameters;

    @Before
    public void setUp() throws Exception {
        product = new Product();
        parameterTypes = new Class[1];
        parameterTypes[0] = java.lang.String.class;
        m = product.getClass().getDeclaredMethod(METHOD_NAME, parameterTypes);
        m.setAccessible(true);
        parameters = new Object[1];
    }

    @Test
    public void testPrivateMethod() throws Exception {
        parameters[0] = "someIdentifier";
        String result = (String) m.invoke(product, parameters); 
  
        //Do your assertions
        assertNotNull(result);
    }
}

Update

I’ve since been told that if dp4j.jar is in the classpath at compile-time, it will inject the necessary reflection to make this work. I haven’t had time to try this yet so YMMV.

Tags: , ,
Posted in Development, How to's | No Comments »

Unit Testing Validation in Annotation Based Validating Spring Beans

Friday, April 22nd, 2011

Motivation

I added validation, via annotations, to a Spring “Model” bean. I needed someway to Unit Test this validation, without running the container and without initialising the Spring context.

The bean (simplified)

package foo.bar;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

public final class ProductModel {
        
    @NotNull
    @Size(max=100)
    @Pattern(regexp="[^\n^\t^\r]+", message="Long Name must not contain New Lines, Carriage Returns or Tabs")
    private String longName;

    @Size(max=20)
    private String shortName;

    // rest snipped for brevity
}

The Unit Test

package foo.bar;

import java.util.Set;

import javax.validation.ConstraintViolation;

import junit.framework.Assert;

import org.hibernate.validator.HibernateValidator;
import org.junit.Before;
import org.junit.Test;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

public class Temp {
    private LocalValidatorFactoryBean localValidatorFactory;
	
    @Before
    public void setup() {
        localValidatorFactory = new LocalValidatorFactoryBean();
        localValidatorFactory.setProviderClass(HibernateValidator.class);
        localValidatorFactory.afterPropertiesSet();
    }
    @Test
    public void testLongNameWithInvalidCharCausesValidationError() {
        final ProductModel productModel = new ProductModel();
        productModel.setLongName("A long name with\t a Tab character");
    	Set<ConstraintViolation<ProductModel>> constraintViolations = localValidatorFactory.validate(productModel);
    	Assert.assertTrue("Expected validation error not found", constraintViolations.size() == 1);
    }
}

More

It actually took me a few hours to work the above test out (simple as it is). If I hadn’t stumbled upon these Spring Unit Tests, I might never have got it.

Tags: , , , ,
Posted in Spring | 3 Comments »

EasyMock Capture Example

Thursday, September 2nd, 2010

Background

EasyMock version 2.4 introduced some new functionality – the ability to capture the arguments passed to mock objects. As ever a few lines of code speaks volumes.

Capture Example

Test Class

package foo.bar;

import static org.junit.Assert.assertEquals;

import org.easymock.Capture;
import org.easymock.EasyMock;
import org.easymock.IMocksControl;
import org.junit.Before;
import org.junit.Test;

public class TestServiceImpl {
    private Service service;
    private Dao dao;
    private IMocksControl controller;
    private final String description = "description";

    @Before
    public void setUp() throws Exception {
        controller = EasyMock.createStrictControl();
        dao = controller.createMock(Dao.class);
        service = new ServiceImpl();  
        service.setDao(dao);
    }
    @Test
    public void testSave() {
        Capture <DomainObject> capturedArgument = new Capture <DomainObject>();
        dao.save(EasyMock.and(EasyMock.capture(capturedArgument), EasyMock.isA(DomainObject.class)));
        controller.replay();
        service.save(description);
        controller.verify();
        DomainObject record = capturedArgument.getValue();
        assertEquals(description, record.getDescription());
        assertEquals("getNextId", record.getId());
    }
}

Source code for classes under test after the break…….
(more…)

Tags: , ,
Posted in Development, Examples | No Comments »

Selenium Tests Randomly Failing

Saturday, July 31st, 2010

The Problem

The project I’m currently working on uses a lot of selenium tests to verify the behaviour of the web front end and, I must say, I’ve been quite impressed with it.

Yesterday however after updating my local machine with the latest copy of the project from Clearcase I noticed a lot of failing tests; the worrying (interesting?) thing though was that the failures appeared to be “random”. Tests were passing one run and failing the next, with no changes having being made in the source code and no changes in the initial starting conditions. I was starting to pull my hair out. Curiously the tests ran fine on my colleagues’ and the build machine. My workmate had a look (remember the tests ran fine for him) but he too was getting the random failures on my machine – we were both stumped.
(more…)

Tags: , ,
Posted in quick tips | No Comments »

Unit Testing Spring apps with @RunWith(SpringJUnit4ClassRunner.class)

Thursday, June 24th, 2010

The Problem

I love Spring, who doesn’t?

One thing however that I found, until recently, a bit awkward was Unit Testing objects which were constructed and initiated via the Spring context and injected into other objects that consumed them. I have seen and used many and varied “bespoke” ways to do this, none of which I found satisfying.

This was until a collegue introduced me to the wonder that is SpringJUnit4ClassRunner. I know, I know, I should have been aware of this ages ago but as they say on millionaire “it’s easy if you know the answer”!
(more…)

Tags: , ,
Posted in Examples | 6 Comments »