Using Microsoft Unit Test Wizard, it creates Accessor objects if you need to test a non-public property in another project. Inside my Unit Tests I create helper functions so that I don’t repeat the same code just in every Unit Test method. Currently I have two tests that are almost identical except one takes a standard object, and the other takes the Accessor version. Since the Accessor is based on the standard version I should be able to have one function and I assume I should be able to use Generics to accomplish. The issue is trying to retype and compile failures.
Here are the existing two functions:
// Common function to create a new test record with standard Account object
internal static void CreateAccount(out Account account, bool saveToDatabase)
{
DateTime created = DateTime.Now;
string createdBy = _testUserName;
account = new Account(created, createdBy);
account.Notes = Utilities.RandomString(1000);
if (saveToDatabase)
account.Create();
}
// Common function to create a new test record with Account_Accessor
internal static void CreateAccount(out Account_Accessor account, bool saveToDatabase)
{
DateTime created = DateTime.Now;
string createdBy = _testUserName;
account = new Account_Accessor(created, createdBy);
account.Notes = Utilities.RandomString(1000);
if (saveToDatabase)
account.Create();
}
I tried changing the signature to of a combined function to:
internal static void CreateAccount<T>(out T account, bool saveToDatabase) {...}
but couldn’t get recast T properly to Account or Account_Accessor. Any suggestions?
You should add constraint to the generic function, because of this two methods:
I suggest you to add some interface with this two methods and add inheritance from it to your two classes.
Constraint should be as follows:
About constraints you can read at http://msdn.microsoft.com/en-us/library/bb384067.aspx
UPDATE
Here is some comments about my example:
1. I’ve replaced
CreateInstanceby addingnew()constraint.2. Because new() constraint can’t have parameters because of .NET generic limitations, I’ve added
Init()method to theIAccountinterface.3.
Initmethod should not be called by client code of theAccountclass, that’s why we define the method as private and explicitly for IAccount.4. Because of
new()constraint you should provide parameterless constructor forAccount. If you do this, your client code should not call this parameterless ctor.As for me I’d leave
Activator.CreateInstanceas is. It is good workaround for the limitations of genericnew()constraint