GRP GRP - 1 year ago 203
Java Question

How can I write a JUnit test for below method?

I'm sorry. I'm new to JUnit testing.

This is my method (which I can't modify at all):

public class HalfNumber {

private int value = 41;

public HalfNumber(){

public int getHalfValue() {
int halfValue = value / 2 + value % 2; //gets rounded

return halfValue;

How can I write a test for getHalfValue() method when doesn't have any parameters but it takes the value from a class variable?

Answer Source

Hi @all and thank you for your responses. This is a quick heads up about the solution I found as a workaround for above issue, I hope this works for all of you who had faced a similar situation when you can't modify the java class when creating its correspondent testing class:

public class TestHalfNumber {

private HalfNumber classUnderTest;

Map<String,Object> bindingsMap;

protected Map<String, String> captured;
protected Resource resource;    
protected ResourceResolver resourceResolver;
protected SlingHttpServletRequest sServletReq;

// ---------------------------------------------------------------------------
 * @param object
 *            of type WCMUsePojo. This object cannot be null.
 * @param map
 *            containing properties that needs to be initialized with
 *            WCMUsePojo
// ---------------------------------------------------------------------------
public void init(WCMUsePojo obj, Map<String, Object> map) {
    Map<String, Object> staticMap = new HashMap<String, Object>();

    staticMap.put("resource", resource);

    staticMap.put("request", sServletReq);

    if (map != null)

    if (obj != null)
        obj.init(new SimpleBindings(staticMap));
        throw new IllegalArgumentException("Subclass object is null ");

public void setUp()
    classUnderTest = new HalfNumber();  

// ---------------------------------------------------------------------------
 * Test case for GetHalfValue 
// ---------------------------------------------------------------------------
public void testGetHalfValue() throws Exception{

    int inputValue = 5;
    int expected = 3;

    bindingsMap = new HashMap<String,Object>();

    //Here is where we change the 4 by a 5 or any other value to test.

    int result = classUnderTest.getHalfValue();


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download