简体   繁体   English

如何使用print语句对代码进行单元测试?

[英]How to unit test a code with print statement?

Many a times, technical interviewers ask questions such as 'print something'. 很多时候,技术面试官会问诸如“打印东西”之类的问题。 Eg: http://www.geeksforgeeks.org/given-a-binary-tree-print-all-root-to-leaf-paths/ 例如: http : //www.geeksforgeeks.org/given-a-binary-tree-print-all-root-to-leaf-paths/

The following code will ask to print all paths from root to leaf. 以下代码将要求打印从根到叶的所有路径。

How do I unit test a code like this ? 如何对这样的代码进行单元测试?

One solution would be to return a datastructure will all paths. 一种解决方案是返回所有路径的数据结构。 But then interviewer would rebuke me for consuming huge space complexity ? 但是面试官会因为消耗大量的空间而责备我吗?

One solution is to pass a PrintStream to your method. 一种解决方案是将PrintStream传递给您的方法。 When you call it from main , pass System.out , like this: 当您从main调用它时,请传递System.out ,如下所示:

public static void main(String[] args) {
    Tree tree = ...
    TreePrinter printer = ...
    printer.printTree(System.out);
}

When you call the method from your unit test code, pass it a subclass of PrintStream , which collects the output in memory, and compares it to the expected output: 当您从单元测试代码中调用该方法时,请将其传递给PrintStream的子类,该子类将输出收集到内存中,并将其与预期输出进行比较:

@Test
public void testTreePrinter() {
    Tree tree = ...
    TreePrinter printer = ...
    MyTestStream testStream = ...
    printer.printTree(testStream);
    assertEquals(expectedOutput, testStream.collectedOutput());
}

In the general case isolating a hard-to-test dependency (like console output) is the way to go. 通常,隔离难以测试的依赖项(例如控制台输出)是可行的方法。 So in general, I'd do something along the lines of dasblinkenlight's suggestion. 因此,总的来说,我会按照dasblinkenlight的建议进行操作。 This also cleanly separates the responsibilities of calculating the tree and printing it out (be it after or during calculation), which makes your code arguably more maintainable. 这也清晰地将计算树并打印出来的责任(在计算之后或过程中)分开,这可以使您的代码更具可维护性。

In the very common case of System.out, there's an alternative that does not require changing the production code: you can capture the out stream in a string by using System.setOut . 在System.out的非常常见的情况下,有一种替代方案不需要更改生产代码: 您可以使用System.setOut捕获字符串中的输出流 In the toy problem you provide, I would be tempted to take this shortcut. 在您提供的玩具问题中,我很想采用这个捷径。

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

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