GRP GRP - 3 months ago 59
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?

GRP GRP
Answer

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;
@Mock
protected Resource resource;    
@Mock
protected ResourceResolver resourceResolver;
@Mock
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)
        staticMap.putAll(map);

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


@Before
public void setUp()
{
    MockitoAnnotations.initMocks(this); 
    classUnderTest = new HalfNumber();  
    when(sServletReq.getResourceResolver()).thenReturn(resourceResolver);   
}

// ---------------------------------------------------------------------------
/**
 * Test case for GetHalfValue 
 */
// ---------------------------------------------------------------------------
@Test
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.
    bindingsMap.put("value",inputValue); 

    init(classUnderTest,bindingsMap);
    int result = classUnderTest.getHalfValue();
    Assert.assertEquals(expected,result);

    }

}