tkpatro123 / mb-unit

Automatically exported from code.google.com/p/mb-unit
0 stars 0 forks source link

StaticTestFactory does execute the last test code from the loop for all tests #720

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
What steps will reproduce the problem?
1. following code:
        [StaticTestFactory]
        public static IEnumerable<Test> CreateStaticTests()
        {
            foreach (int searchTerm in new int[]{1,2,3,4,5})
            {
                yield return new TestCase("Search Term: " + searchTerm.ToString(), () =>
                {
                    Assert.AreEqual(2, searchTerm);                    
                });
            }
        }
Loaded and executed with Icarus

What is the expected output? What do you see instead?
I expect one assertion to pass and four to fail.
Instead all five fail. All five with the same message:
Expected Value : 2
Actual Value   : 5
Actual value seems to be always the last value in a loop.

What version of the product are you using? On what operating system?
Win7 64Bit, .Net 3.5, MBUnit 3.2.0.0

Please provide any additional information below.
I am not that experienced , but kept close to the examples you provide.

Original issue reported on code.google.com by snie...@gmail.com on 4 Sep 2010 at 4:19

GoogleCodeExporter commented 8 years ago
It's not a bug, but rather a common misunderstanding of how loops and closures 
are working together in C#. Please see the following question in Stackoverflow 
for more info 
(http://stackoverflow.com/questions/227820/why-is-it-bad-to-use-a-iteration-vari
able-in-a-lambda-expression)

Basically, you should use an intermediate variable. Like this:

[StaticTestFactory]
public static IEnumerable<Test> CreateStaticTests()
{
  foreach (int searchTerm in new int[] { 1, 2, 3, 4, 5 })
  {
     int i = searchTerm;
     yield return new TestCase("Search Term: " + i.ToString(), () =>
     {
       Assert.AreEqual(2, i);
     });
  }
}

Hope it helps,
Yann.

Original comment by Yann.Tre...@gmail.com on 5 Sep 2010 at 2:34

GoogleCodeExporter commented 8 years ago
Thank you very much. That helped. 
A small hint on the documentataion here: 
http://www.gallio.org/api/html/T_MbUnit_Framework_StaticTestFactoryAttribute.htm
 would be useful. To me the example code looks the same as my one.

Sebastian

Original comment by snie...@gmail.com on 5 Sep 2010 at 4:43

GoogleCodeExporter commented 8 years ago
You are absolutely right. The example in the documentation does not work at all 
for the exact same reason. I will fix that.

Regards,
Yann

Original comment by Yann.Tre...@gmail.com on 5 Sep 2010 at 5:11