I have a class like this:
public class Product : IProduct
{
static private string _defaultName = "default";
private string _name;
private float _price;
/// Constructor
public Product()
{
_price = 10.0F;
}
public void ModifyPrice(float modifier)
{
_price = _price * modifier;
}
I want ModifyPrice to do nothing for a specific value, but I also want to call the constructor that set the price to 10. I tried something like this:
var fake = new SProduct() { CallBase = true };
var mole = new MProduct(fake)
{
ModifyPriceSingle = (actual) =>
{
if (actual != 20.0f)
{
MolesContext.ExecuteWithoutMoles(() => fake.ModifyPrice(actual));
}
}
};
MProduct.Constructor = (@this) => (@this) = fake;
But even if fake is well-initialized with the good constructor, I can’t assign it to @this. I also try something like
MProduct.Constructor = (@this) => { var mole = new MProduct(@this)... };
But this time I cannot call my constructor. How am I supposed to do?
You don’t need to mock the constructor, the parameterless constructor of the
Productclass already does what you want.Add some debugging output to
Product.Mock only the
ModifyPricemethod.See the debug output to confirm everything works as expected:
Initializing price: 10 Skipped setting price. New price: 210By the way, you don’t need to use the stub here,
creating an instance of
Productwill suffice.Update:
Mocking a single method can be achieved with the
AllInstancesclass like this