开发者

Testing code that could be optimised out

I'm just trying out tdd with nunit and i've written the following test, for my CachedEnumerable<T> class:

[Test]
public void CanNestEnumerations()
{
    var SourceEnumerable = Enumerable.Range(0, 10).Select(i => (decimal)i);
    var CachedEnumerable = new CachedEnumerable<decimal>(SourceEnumerable);

    Assert.DoesNot开发者_Python百科Throw(() =>
        {
            foreach (var d in CachedEnumerable)
            {
                foreach (var d2 in CachedEnumerable)
                {

                }
            }
        });
}
  1. Will the nested for loops be optimised out, since they don't do anything (CachedEnumerable is never used after the loops)?

  2. Are there any (other?) cases where test code could potentially be optimised out?

  3. If so, how can i ensure that the test code actually runs?


It would not be optimized out, as there is more going on that what it looks like. The code is actually more like (adapted from the accepted answer here):

using (IEnumerator<Foo> iterator = CachedEnumerable.GetEnumerator())
{
    while (iterator.MoveNext())
    {
        var d = iterator.Current;

        // Other loop
    }
}

The compiler does not know if there are side effects of calling MoveNext/Current, so it has to call them. If d is not used, then it could potentially optimize out the assignment. But it would still have to call Current. Same goes for the other loop.

The optimizations made shouldn't have any logical effect on your code. It would just remove things that have no effect or would never be called in normal conditions, among other things.


If so, how can i ensure that the test code actually runs?

You can disable "Optimize code" in the Properties tab of your unit test project. It's in the Build tab.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜