Question

I'm new to Pex and Moles. I am trying to run Pex on my code but I am using Constructor injection. Is there a way of instructing Pex on how to inject the constructors?

Edit

    public UserLogic(IUserRepository userRepository)
    {
        _userRepository = userRepository;
    }

    public int GetUsersAge(int id)
    {
        User user = _userRepository.GetById(id);
        DateTime DOB = user.DOB;
        DateTime now = DateTime.Today;
        int age = now.Year - DOB.Year;
        if (DOB > now.AddYears(-age)) age--;
        return age;
    }

I need to inject a stub userRepository. Pex is failing with a NullReferenceException when _userRepository.GetById(id) is called. I have been using Moq for my unit tests but i want to switch to pex and moles

Should i use PexFactories to create my stubs?

Was it helpful?

Solution

Try passing a Moles Stub type to a Pex-generated parameterized test. To create a parameterized test, right-click the class you want to explore, and then select PEX > Create Parameterized Unit Test. This generates a method in the test class that contains arguments. The individual tests call this parameterized test, sending the individual test arguments.

When the code under test uses dependency injection by way of arguments (it has an interface typed argument), the Pex-generated paramterized test method will also contain the same interface type argument. You are able to write your own test methods that also call the parameterized method, feeding it your own values, including the interface type. Just be sure to not write them in the Pex-generated file!

I also suggest looking at using Mole Stub types, for your unit test injections. The Microsoft Moles Reference Manual is a very good place to start learning about how to use Moles in unit tests. A moles stub type will be created for your interface, when you create the parameterized test. Simply configure the detours for your stub type, and then pass it to the parameterized test.

Creating stub type detours is very easy. I suggest creating a configuration method in the test project, that configures frequently-used detours. I usually add an enumeration flag as an argument to this method, so I can easily tell it which detours to create on certain types, all in one call.

Sample enum:

[Flags()]
public enum MoleConfigurations
{
    MoleSqlClientObjects,
    DisableDirectory_Exists,
    DisableEventLogExtensions,
    DisableInitializeDatabaseObjects,
    DisableInitializeThreadingObjects,
    DisableQueueExistingDataFiles,
    DisableConstructor
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top