¿Cómo utilizar Moles para un constructor?
-
14-11-2019 - |
Pregunta
Tengo una clase como esta:
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;
}
Quiero ModificarPrecio no hacer nada por un valor específico, pero también quiero llamar al constructor que fijó el precio en 10.Intenté algo como esto:
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;
Pero incluso si falso está bien inicializado con el constructor bueno, no puedo asignarlo a @this.También intento algo como
MProduct.Constructor = (@this) => { var mole = new MProduct(@this)... };
Pero esta vez no puedo llamar a mi constructor.¿Cómo se supone que debo hacer?
Solución
No necesitas burlarte del constructor, el constructor sin parámetros del Product
La clase ya hace lo que quieres.
Agregue algunos resultados de depuración a Product
.
public class Product
{
private float _price;
public Product()
{
_price = 10.0F;
Debug.WriteLine("Initializing price: {0}", _price);
}
public void ModifyPrice(float modifier)
{
_price = _price*modifier;
Debug.WriteLine("New price: {0}", _price);
}
}
Burlarse sólo del ModifyPrice
método.
[TestMethod]
[HostType("Moles")]
public void Test1()
{
// Call a constructor that sets the price to 10.
var fake = new SProduct { CallBase = true };
var mole = new MProduct(fake)
{
ModifyPriceSingle = actual =>
{
if (actual != 20.0f)
{
MolesContext.ExecuteWithoutMoles(() => fake.ModifyPrice(actual));
}
else
{
Debug.WriteLine("Skipped setting price.");
}
}
};
fake.ModifyPrice(20f);
fake.ModifyPrice(21f);
}
Vea el resultado de depuración para confirmar que todo funciona como se esperaba:
Initializing price: 10 Skipped setting price. New price: 210
Por cierto, no es necesario utilizar el código auxiliar aquí,
var fake = new SProduct { CallBase = true };
creando una instancia de Product
Será suficiente.
var fake = new Product();
Actualizar:Burlarse de un solo método se puede lograr con el AllInstances
clase como esta
MProduct.Behavior = MoleBehaviors.Fallthrough;
MProduct.AllInstances.ModifyPriceSingle = (p, actual) =>
{
if (actual != 20.0f)
{
MolesContext.ExecuteWithoutMoles(() => p.ModifyPrice(actual));
}
else
{
Debug.WriteLine("Skipped setting price.");
}
};
// Call the constructor that sets the price to 10.
Product p1 = new Product();
// Skip setting the price.
p1.ModifyPrice(20f);
// Set the price.
p1.ModifyPrice(21f);
Otros consejos
MProduct.Behavior = MoleBehaviors.Fallthrough;