Pex And Dynamic Test Methods

Pex as covered in past posts is a pretty great white box testing tool. But let’s assume that you want to have a “factory” in the sense that test methods can be automagically built out. An example of this is you have a list of some acceptable data type, and you want harness a test case for each one, and avoid the use of haphazard data keeping in mind that Pex will only use varying values.

In this case, you must push Pex to use parameterized unit tests since you will essentially be targeting a value from a list of values. In the below, I am assuming an array of integers is being populated by the void PopulateIntArray() method. Following, the Test method is defined which has the method decoration of PexMethod which implies it is Pex parameterized unit test. In the method, we are leveraging the PexAssume.IsTrue which means the test case fails if the condition evaluates to false.

[csharp]
static int[] intArray = PopulateIntArray();
[PexMethod]
public void Test(int index)
{
PexAssume.IsTrue(index >= 0 && index < intArray.Length); int x = intArray[index]; ... } [/csharp] EDIT: As Peli points out in the comments, you can use the PexArguments decoration to pass in values as well.

Share

4 thoughts on “Pex And Dynamic Test Methods”

  1. I don’t understand why you would need to do that. Pex should figure out the interresting values itself. If you use the values in a special way, then Pex will craft those values. Otherwise, they do not matter. So the test case should read:

    [PexMethod]
    public void Test(int x) { … }

    If you want to ‘seeed’ the search, you can also use the [PexArgument(…)] attribute to specify values that Pex should use first before searching:

    [PexMethod]
    [PexArguments(123)]
    [PexArguments(456)]
    public void Test(int x) { … }

  2. Oh, you are correct. I had not used the PexArguments decoration previously. I will correct the post.

  3. Having a predefine set of values is fine. Feed them through the PexArguments attribute. Pex will execute the method with those values first, then it will look for additional values to cover the missing branches.

Leave a Reply

Your email address will not be published. Required fields are marked *