Lookahead in unittest

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri May 12 14:23:23 PDT 2017


On 5/10/17 12:53 PM, Raiderium wrote:
> On Wednesday, 10 May 2017 at 16:32:11 UTC, Adam D. Ruppe wrote:
>> On Wednesday, 10 May 2017 at 16:09:06 UTC, Raiderium wrote:
>>> I can't figure out if this is intended behaviour.
>>
>> It is. A unittest is a function, and in functions, all declarations
>> must be defined before used (just like local variables).
>>
>> Sometimes, you can wrap it in a struct:
>>
>> unittest {
>>   struct Decls {
>>     // put your decls here
>>   }
>>
>>   with(Decls()) {
>>    // call funcs here
>>   }
>> }
>
> Ah. I wasn't aware class declarations within functions (including
> unittest) were sensitive to their order, so that's something I've
> learned today. :)
>
> I tried the with(Decls()) syntax and it worked perfectly, thanks Adam.
> I'd been haphazardly nesting unittest{} blocks within the struct, and it
> felt less than sanitary.
>
> For full disclosure, the test I'm writing needs to create a reference
> cycle (as in, class B holding a reference to A), and it works properly
> if the classes are declared at module/class/struct level, but then
> either the class names pollute the module (which is just eww) or they're
> nested within a class/struct, which leads me to the current situation.
>
> Consider my problem solved :) Thanks again Stefan and Adam for the replies.

Note, you can achieve what you want with version(unittest):

version(unittest)
{
    class A { B b; }
    class B { }
}

unittest
{
    // use A and B here
}

-Steve


More information about the Digitalmars-d-learn mailing list