locked
Group Asserts/ Multiple Asserts RRS feed

  • Question

  • i know a unit test should be testing a small piece of code so in many cases you wouldn't need to assert more than one thing at a time. How ever we have started using Specflow and BDD where your testing at a higher level. Because of this often a test is not valid unless more than one value matches their expected value. 

    Is there a way to assert a group of thins. like 

    "Pass if x = 3, y = 4 and z = 9"

    so the test would fail if any one is wrong but still report if all 3 values are wrong rather than having to fix one, discover that the next one is broken then fix that one.

    Thursday, March 3, 2011 11:55 PM

All replies

  • Hi Nitro,

    To check for all conditions, you could use something like this:

    if

     

     

    (x == 1 && y == 2 && z == 3)

    {

     

     

    //Do nothing

    }

     

     

    else

    {

     

     

    Assert.Fail("All conditions failed");

    }

    You could also use || instead of &&, could also use switch inside the condition and do Console.Writeline() and many other variations. The key here is to use Assert.Fail()

    Thanks,

    Anuj

    Friday, March 4, 2011 2:44 AM
  • Hello Nitro52,

    I am moving your thread to the Visual Studio Unit Testing forum so that you can get better response.

    Thanks,


    Vicky Song [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Friday, March 4, 2011 12:44 PM
  • If you're using SpecFlow then I would suspect your scenario is something like

    Given some values
    When something happens
    Then Pass if x = 3, y = 4 and z = 9

    If that's the case then this simplistic appproach to the test will do what you need:

    [Then(@"Pass if x = 3, y = 4 and z = 9")]
    public void ThenPassIfX3Y4AndZ9()
    {
    	var passX = (x == 3);
    	var passY = (y == 4);
    	var passZ = (z == 9);
    	Assert.IsTrue(passX && passY && passZ);
    }
    

    Personally I don't like this approach, and would prefer to see the BDD test as

    Given ...
    When ...
    Then X should be 3
    And Y should be 4
    And Z should be 9

    And just deal with the need to run multiple times to watch the test fail on each of the asserts because it's clear which value fails.  In the code above the output from the test run is something like this:

    Then Pass if x = 3, y = 4 and z = 9
    -> error: Assert.IsTrue failed.

    Not so useful to know which values are actually wrong.

     


    blog: http://www.richard-banks.org podcast: http://www.talkingshopdownunder.com
    Saturday, March 5, 2011 12:01 AM
  • If you are in an environment where you are free to use more than one unit testing framework then MbUnit has a multiple asserts feature.
    Kevin
    Wednesday, March 9, 2011 2:47 PM