Does anyone know the best way to go about mocking private constructors? Preferably with natural typemocks.
In our system the method for creating a Coupon and saving it to the database looks as follows:
public class Coupon
{
private string _couponName;
private Coupon()
{
...
}
public static Coupon Create(IDataElephant elephant, string couponName)
{
Coupon coupon = new Coupon();
coupon._couponName = couponName;
elephant.Save(coupon);
Check.Ensure(coupon.ID != 0);
return coupon;
}
}
The thing we want to mock in the code above is IDataElephant elephant.
Our current (not working) approach for mocking the IDataElephant in the Coupon.Create method looks something like this:
internal static void ExpectCreateCoupon(IDataElephant elephant, string couponName)
{
int id = GenerateUniqueID();
using (RecordExpectations recorder = RecorderManager.StartRecording())
{
// This is the troublemaking line of code.
// The construcor is private and can't be called here.
Coupon createdCoupon = new Coupon(); // <<< Alternative needed!
recorder.CallOriginal();
elephant.Save(createdCoupon);
// Save would normally give createdCoupon an id, but since that's mocked:
recorder.VerifyMode = VerifyMode.PassIfNotCalled;
recorder.ExpectAndReturn(createdCoupon.ID, id).RepeatAlways();
recorder.VerifyMode = VerifyMode.Normal;
recorder.CheckArguments();
}
}
So basically what we're after is some way to expect a call to the constructor and make it return a real Coupon.
The class we want to mock is IDataElephant, not the coupon.
In a test the classes above would be called like this:
ExpectCreateCoupon(elephant, "COUPONNAME");
Coupon.Create(elephant, "COUPONNAME");
Any ideas?