Unit testing a function returning void

Paul Backus snarwin at gmail.com
Thu Nov 3 11:43:35 UTC 2022


On Thursday, 3 November 2022 at 10:00:27 UTC, Bruno Pagis wrote:
> Good morning,
> I have the following class:
>
> ```
> class A {
>   int[] array;
>
>   ...
>
>   void print() {
>     writeln("array = ", this.array);
>   }
> }
> ```
>
> I would like to unit test the print function (yes, I know, not 
> very useful on the above example since print is merely a 
> duplicate of writeln...). Is there a way to use assert to test 
> the output of the print function to stdout?

The easiest way to do this is to modify the function so it can 
output somewhere other than stdout. Then you can have it output 
to a file in the unittest, and check the contents of the file to 
verify the result.

For example:

```d
import std.stdio;

class A
{
     int[] a;

     this(int[] a) { this.a = a; }

     void print(File output = stdout) {
         output.writeln("array = ", this.a);
     }
}

unittest {
     import std.file;

     A a = new A([1, 2]);
     a.print(File("test.txt", "wb"));
     assert(readText("test.txt") == "array = [1, 2]\n");
}
```


More information about the Digitalmars-d-learn mailing list