I've run into an unexpected problem that only seems to happen in unittests, but not outside of them. Consider the following example:
unittest {
class Ab {
int a;
string b;
static class Builder {
int _a;
string _b;
Builder a(int a) {
_a = a;
return this;
}
Builder b(string b) {
_b = b;
return this;
}
Ab build() {
Ab t = new Ab();
t.a = _a;
t.b = _b;
return t;
}
}
}
Ab ab = new Ab.Builder()
.a(1)
.b("ham")
.build();
assert(ab.a == 1);
assert(ab.b == "ham");
}
This fails to compile with the following error:
Generating test runner configuration 'builder-test-library' for 'library' (library).
Starting Performing "unittest" build using /usr/bin/dmd for x86_64.
Building builder ~master: building configuration [builder-test-library]
source/builder.d(58,16): Error: outer function context of `builder.__unittest_L41_C1` is needed to `new` nested class `builder.__unittest_L41_C1.Ab`
Error /usr/bin/dmd failed with exit code 1.
However, if I move the class definition outside of the unittest block, then everything works fine:
class Ab {
int a;
string b;
static class Builder {
int _a;
string _b;
Builder a(int a) {
_a = a;
return this;
}
Builder b(string b) {
_b = b;
return this;
}
Ab build() {
Ab t = new Ab();
t.a = _a;
t.b = _b;
return t;
}
}
}
unittest {
Ab ab = new Ab.Builder()
.a(1)
.b("ham")
.build();
assert(ab.a == 1);
assert(ab.b == "ham");
}
Generating test runner configuration 'builder-test-library' for 'library' (library).
Starting Performing "unittest" build using /usr/bin/dmd for x86_64.
Building builder ~master: building configuration [builder-test-library]
Linking builder-test-library
Running builder-test-library
2 modules passed unittests
Why is this error only found when declaring a class in the unittest?