Sunday, January 22, 2012

Using Reflection To Create Mock Objects

Well-established tools like Mockito and EasyMock offer a powerful range of features for defining and interacting with mock objects. I use both tools heavily in my unit tests, and would recommend them to anyone looking for a mocking framework.

Sometimes, however, a real (i.e. non-proxied) collaborator is called for, or adding third-party libraries may not be an option. In most cases, a suitable object could be instantiated by calling the constructor and setting it as a dependency to the object under test. Suppose though that we have the following 'Footballer' class, and we want to write a test for the 'getAvgGoalsPerGame()' method:

package com.rich.testingutils.mocking;
public class Footballer {
 
    private String name;
    private int age;
    private Double salary;
    private Integer gamesPlayed;
    private Integer goalsScored;
    private Boolean isCaptain;
 
    public double getAvgGoalsPerGame(){
        return (double) goalsScored / gamesPlayed;
    }
 
// <getters and setters>package com.rich.testingutils.mocking;
 
import org.junit.Test;
 
import static junit.framework.Assert.assertEquals;
 
public class FootballerTest {
 
    @Test
    public void testGetGameGoalsRatio() {
        Footballer footballer = new Footballer();
        footballer.setGamesPlayed(14);
        footballer.setGoalsScored(7);
        assertEquals(Double.valueOf(0.5), footballer.getAvgGoalsPerGame());
    }
 
}


Read more: Lines of code
QR: using-reflection-to-create-mock-objects.html
 
// <hashcode>
 
// <equals>
}


We know that unless both of the 'gamesPlayed' and 'goalsScored' are initialised, a NullPointerException will be thrown, so we might initially write the test as follows:

Posted via email from Jasper-Net