Pex - Automated Whitebox Testing for .NET : parameterized unit testing

Parameterized Unit Testing


Parameterized Unit Tests (PUTs) are... tests that take parameters. Unlike traditional unit tests, which are usually closed methods, PUTs take any set of parameters. Is it that simple? Yes! From there, Pex will try to generate the (minimal) set of inputs that fully cover the code reachable from the test.

PUTs are defined using the PexMethod custom attribute in a similar fashion to MSTest (or NUnit, MbUnit, xUnit). PUTs are instance methods logically grouped in classes (tagged with PexClassAttribute). The following sample shows a simple PUT stored in the MyPexTest class:

[PexMethod]
void ReplaceFirstChar(string target, char c) {
    
    string result = StringHelper.ReplaceFirstChar(target, c);
 
    Assert.AreEqual(result[0], c);
}
where ReplaceFirstChar is a method that replaces the first character of a string:

class StringHelper {
    static string ReplaceFirstChar(string target, char c) {
        if (target == null) throw new ArgumentNullException();
        if (target.Length == 0) throw new ArgumentOutOfRangeException();
        return c + target.Substring(1);
    }
}

From this test, Pex can automatically generate inputs for a PUT that cover many execution paths of the tested code. Each input that covers a different execution path gets 'serialized' as a unit test:

[TestMethod, ExpectedException(typeof(ArgumentNullException))]
void ReplaceFirstChar0() {
    this.ReplaceFirstChar(null, 0);
}
...
[TestMethod]
void ReplaceFirstChar10() {
    this.ReplaceFirstChar("a", 'c');
}

For more details on getting started with PUTs, see


See Also

PexMethodAttribute, PexClassAttribute, PexAssume, Generic Parameterized Unit Testing
(c) Microsoft Corporation. All rights reserved. pex Wiki Documentation 0.93.50813.0