Search code examples
visual-studiopexpex-and-moles

Pex ignores default parameter assignment


I am using Pex to analyse function executions. However, I noticed that default parameters are not looked at.

Here's an example of what I mean:

public int bla(int x = 2)
{
    return x * 2;
}

When I run Pex, it generates the test case for int result = bla(0);. (x = 0)
Is there a way to tell Pex that it should also try to call bla( without parameter (i.e. int result = bla() )?


Solution

  • The 1st rule of IntelliTest/Pex is it tries to increase code coverage. If all statements have been covered, Pex will stop.

    There are many ways to add some code that only gets covered when x=2, such as in the test method. This might be the simplest that worked for me:

        [PexMethod]
        public int bla([PexAssumeUnderTest]Class1 target, int x)
        {
            if(x == 2)
            {
                PexAssert.ReachEventually();
            }
            int result = target.bla(x);
            return result;
            // TODO: add assertions to method Class1Test.bla(Class1, Int32)
        }
    

    The exploration results window should show:

        x      result
        0      0
        2      4
    

    I don't know of any way to have Pex automatically generate test cases for all default parameters.

    In real world production code it's highly likely the default value will be used in the code so you might not run into this problem often.

    And if you have all the code paths covered by Pex does it really matter whether the default value is used or not?

    It's probably more import to test the methods that call 'bla' with and without supplying a value.