Unit testing a function returning void

H. S. Teoh hsteoh at qfbox.info
Thu Nov 3 16:11:27 UTC 2022


On Thu, Nov 03, 2022 at 08:51:52AM -0700, Ali Çehreli via Digitalmars-d-learn wrote:
> On 11/3/22 03:00, Bruno Pagis wrote:
> 
> >    void print() {
> >      writeln("array = ", this.array);
> >    }
> 
> Similar to Paul Backus's program but I would try to avoid the file system
> for unit tests when possible. In this case, you can print into a sink, which
> can be useful in other ways as well:
[...]

Alternatively, you can templatize on File to make it swappable with a
mock object:

	void myfunc(File = std.stdio.File)(File output = stdout) {
		output.writeln(...);
	}

	unittest {
		struct MockFile {
			string output;
			void writeln(Args...)(Args args) {
				output ~= format(args);
			}
		}
		MockFile mock;
		myfunc(mock);
		assert(mock.output == ...);
	}


T

-- 
"Maybe" is a strange word.  When mom or dad says it it means "yes", but when my big brothers say it it means "no"! -- PJ jr.


More information about the Digitalmars-d-learn mailing list