对不起我是JUnit测试的新手。
这是我的方法(根本无法修改):
public class HalfNumber {
private int value = 41;
public HalfNumber(){
};
public int getHalfValue() {
int halfValue = value / 2 + value % 2; //gets rounded
return halfValue;
}
}
如果没有任何参数但是从类变量获取值,我如何为getHalfValue()方法编写测试?
答案 0 :(得分:0)
这将是一个有效的测试:
@Test
public void numberTest() {
assertEquals(21, new HalfNumber().getHalfValue());
}
顺便说一句,这个课程的目的和设计是我见过的最糟糕的课程之一。
答案 1 :(得分:0)
您好@all并感谢您的回复。这是一个快速了解我找到的解决方案作为上述问题的解决方案,我希望这适用于在创建其对应的测试类时无法修改java类时遇到类似情况的所有人:
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);
}
}