java - 从一个测试调用方法时的 junit 测试

标签 java unit-testing testing junit

public void createRootElement() throws FileNotFoundException, IOException
    {
    Properties prop = new Properties();
    prop.load(new FileInputStream("/home/asdf/Desktop/test.properties"));
        File file = new File(prop.getProperty("filefromroot"));
        try
            {
                // if file doesn't exists, then create it
                if (!file.exists())
                    {
                        file.createNewFile();
                    }
                FileWriter fw = new FileWriter(file.getAbsoluteFile());
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write("<root>"); //create the root tag for the XML File.
                bw.close();
            }
        catch(Exception e)
            {
            writeLog(e.getMessage(),false);
            }
    }

我是 junit 测试的新手。我想知道如何为此编写测试用例以及需要考虑的所有内容。如何调用该测试调用的方法。?

最佳答案

JUnit 测试用例应该如下所示:

import static org.junit.Assert.assertTrue;
import org.junit.Test;

public class ClassToBeTestedTest {

    @Test
    public void test() {
        ClassToBeTested c = new ClassToBeTested();
        c.createRootElement();
        assertTrue(c.rootElementExists());
    }

}

您使用@Test 注释标记测试方法并编写执行您想要测试的代码。

在这个例子中,我创建了你的类的一个实例并调用了 createRootElement 方法。

在那之后,我做了一个断言来验证是否一切都像我预期的那样。

您可以断言很多事情。阅读 JUnit 文档以获取更多信息。

一个好的做法是在实际编写代码之前编写测试。因此,该测试将指导您如何编写更好的代码。这称为 TDD。谷歌搜索。

关于java - 从一个测试调用方法时的 junit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15231296/

相关文章:

entity-framework - 为什么 DbContext 没有实现 IDbContext 接口(interface)?

javascript - Mocha - Chai Unit Terst 报告生成 - NodeJS

testing - Cypress - 在点击后记录来自请求的响应数据()

testing - 从用户的角度自动测试网站?

java - 如何使用eclipse部署MIDlet应用程序?

java - 如何修复 my/hibernate.cfg.xml 文件?

java - 输入流超时

java - 如何在不实现可序列化的情况下在 spring-struts web 应用程序中将 DTO 对象从客户端传输到服务器

python-3.x - 有没有办法断言已在 unittest 模拟对象上设置了属性?

node.js - 除了环境变量之外,还有更好的方法将敏感数据传递给程序吗?