【问题标题】:junit test when a method is called from one test从一个测试调用方法时的junit测试
【发布时间】:2013-03-05 18:26:31
【问题描述】:
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 测试的新手。我想知道如何为此编写测试用例以及要考虑的所有内容。怎么调用这个测试中调用的方法?

【问题讨论】:

标签: java unit-testing testing junit


【解决方案1】:

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。谷歌。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    • 2019-12-15
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多