首页 > 解决方案 > how do test with Junit for the method AddCalcNode()?

问题描述

Hello guys How do I test the method addCalcNode with JUnit?

public class Add {
    private final ObjectMapper mapper = new ObjectMapper();

    public ObjectNode addCalcNode(int i, int j) {
        ObjectNode node = mapper.createObjectNode();

        node.put("result", i+j);

        return node;
    }

}

标签: javajunit

解决方案


在日食中,

  1. 右键单击包含此类的文件(在左侧的文件夹视图中)。New > Other从上下文菜单中选择
  2. 在弹出窗口中,选择Java > JUnit > JUnit Test Case,然后单击“下一步”按钮
  3. 单击“完成”。如果需要,您可以在此处更改一些属性 - 它们相对简单 - 但在这种情况下没有太多需要。

现在,你有你的AddTest课。是时候编写一个测试方法了addCalcNode()

public class AddTest {
    @Test
    public void addCalcNodeTest() {
        // get a value from our class
        Add myAdd = new Add();
        ObjectNode addedNode = myAdd.addCalcNode(1, 2);
        // test that that value is correct
        // I don't know how your ObjectMapper works, so I'll just do this to demonstrate
        ObjectNode expected = (new ObjectMapper()).createObjectNode();
        expected.put("result", 3);
        // the assert functions are the core of JUnit, for testing that your function does
        // what you want it to. assertEquals() is the most basic of them.
        assertEquals(expected, addedNode);
    }
}

现在,右键单击这个 JUnit 类文件(在左侧的文件夹视图中),然后Run As > JUnit Test从上下文菜单中选择。

测试是否通过或失败的显示应该出现在某处。这就是制作和运行基本 JUnit 测试的方法。您可以从那里扩展您的测试,或者为这个测试添加更多功能,或者进行更多测试(只是用 注释的方法@Test)。


推荐阅读