File-like option where the "file contents" comes from a string?
Dennis
dkorpel at gmail.com
Wed Nov 27 16:38:33 UTC 2024
On Wednesday, 27 November 2024 at 01:12:23 UTC, Andy Valencia
wrote:
> Again and again for testing I run into how nice it would be to
> have an open "File" which has its contents set by the unit test
> code
I don't know what situation you're in so this may not be
applicable, but I personally rarely use mocks, because I write my
code as `pure` as possible and push dependencies on the file
system / environment / user interface etc. to the top. For
example, instead of:
```D
void main(string[] args)
{
writeln(lineCount(File(args[1], "r")));
}
int lineCount(File f) => f.byLine.walkLength;
unittest
{
// Annoyingly need to create file with test input
assert(lineCount(StringFile("Good\nday")) == 2);
}
```
You can also write it like:
```D
void main(string[] args)
{
writeln(lineCount(cast(string) read(args[1])));
}
int lineCount(string f) pure => f.splitter('\n').walkLength;
unittest
{
assert(lineCount("Good\nday") == 2);
}
```
This is a toy example. Again, you may have constraints that don't
allow structuring your code like that, but it's worth considering.
More information about the Digitalmars-d-learn
mailing list