简体   繁体   English

如何在简单算法上应用单元测试?

[英]How can i apply Unit Testing on my simple algorithm?

I have a maven project that draws Christmas tree. 我有一个绘制圣诞树的maven项目。 I need to implement Unit tests on it but i have no idea how to do it :/ 我需要对其执行单元测试,但是我不知道该怎么做:/

I already set up , JUnit on my Maven project 我已经在Maven项目中设置了JUnit

for (int i = 0; i < 4; i++) {
   for (int j = 0; j < 10 - i; j++)
    System.out.print(" ");
   for (int k = 0; k < (2 * i + 1); k++)
    System.out.print("*");
   System.out.println();
  }

Assuming your class that draws Christmas tree looks more or less like that: 假设您的班级绘制圣诞树看起来像这样:

class ChristmasTreeDrafter {

    void draw() {
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 10 - i; j++)
                System.out.print(" ");
            for (int k = 0; k < (2 * i + 1); k++)
                System.out.print("*");
            System.out.println();
        }
    }
}

You can test it in that way: 您可以通过以下方式进行测试:

public class ChristmasTreeDrafterTest {

    private final ByteArrayOutputStream out = new ByteArrayOutputStream();

    @Before
    public void setup() {
        System.setOut(new PrintStream(out));
    }

    @Test
    public void shouldDrawChristmasTree() {
        // given
        ChristmasTreeDrafter christmasTreeDrafter = new ChristmasTreeDrafter();

        // when
        christmasTreeDrafter.draw();

        // then
        Assert.assertEquals("          *\r\n" +
                "         ***\r\n" +
                "        *****\r\n" +
                "       *******\r\n", out.toString());
    }
}

In the setup method standard output stream is redirected to the out object and thanks to this you can verify its content in then block. setup方法中,标准输出流被重定向到out对象,由于这个原因,您可以在then块中验证其内容。 Unfortunately Java has no multiline strings, so this code looks ugly. 不幸的是,Java没有多行字符串,因此这段代码很难看。 In order to improve readability you can extract this content to the file under test/resources (assuming default maven project structure). 为了提高可读性,您可以将此内容提取到test/resources下的文件中(假设使用默认的maven项目结构)。

At a high level: the purpose of that code is to print a tree or triangle made of asterisks. 概括而言:该代码的目的是打印由星号制成的树或三角形。 The test is simple, run the code and see of it generates the desired output. 测试很简单,运行代码,看看它会生成所需的输出。

Since the code is printing to System.out you will need to redirect System.out to a file or a string (see this ) then compare the generated output to the desired output to see of the code is operating properly. 由于代码正在打印到System.out,因此您需要将System.out重定向到文件或字符串(请参阅参考资料 ),然后将生成的输出与所需的输出进行比较,以查看代码是否正常运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM