nUnit/moq - 为什么我的模拟总是返回false?

Ric*_*lva 0 .net c# nunit unit-testing moq

我是nUnit和Moq进行单元测试的新手,并且在dbprovider中遇到了一个方法的问题.

我正在尝试测试在ICoDbProvider中调用Exists方法的验证方法.如果为false,则该方法会抛出一个excpetion,并且工作正常.如果为true,则该方法应该继续执行,直到return true;方法结束时的语句为止.

这是测试的方法:

private bool ValidateReciboCajaModel(ReciboCajaModel model)
{
        if (model == null)
            throw new ArgumentException("El modelo ha llegado nulo");

        if (string.IsNullOrWhiteSpace(model.AccionARealizar))
            throw new ArgumentException("No se ha definido una Acción a realizar");

        if (!_accionARealizarService.Exists(new AccionARealizarEntity(model)))
            throw new ArgumentException(@"No es una ""acción a realizar"" válida");


        if (string.IsNullOrWhiteSpace(model.CentroCostos))
            throw new ArgumentException("No se ha definido ningún centro de costos");

        if (!_centroCostosService.Exists(new CentroCostosEntity(model)))
            throw new Exception("No es un centro de costos válido");

        if (String.IsNullOrWhiteSpace(model.CuentaIngresoDinero))
            throw new Exception("No es una cuenta de Ingreso válida");

        if (!_terceroService.Exists(new TerceroEntity(model)))
            throw new Exception("No es un tercero registrado");

        if (String.IsNullOrWhiteSpace(model.Tercero))
            throw new Exception("No es un tercero válido");

        if (!_tipoReciboCajaService.Exists(new TipoReciboCajaEntity(model)))
            throw new Exception("No es un recibo de caja registrado");

        if (String.IsNullOrWhiteSpace(model.TipoReciboCaja))
            throw new Exception("No es un recibo de caja válido");

        if (!(0 < model.ValorPagado && model.ValorPagado <= 999999999999d))
            throw new Exception("El valor pagado no es válido");

        return true;

}
Run Code Online (Sandbox Code Playgroud)

该测试最初由Intellitest生成,它为私有方法测试生成了一个脚手架.

测试方法看起来像这样.

    [Test]
    [PexGeneratedBy(typeof(ReciboCajaBizTest))]
    [PexRaisedException(typeof(TargetInvocationException))]
    public void ValidateReciboCajaModel_ValidModel()
    {
        bool b;
        TargetInvocationException receivedException = new TargetInvocationException(null);

        ReciboCajaModel s1 = new ReciboCajaModel();
        var accionARealizarService = new Mock<ICoDbProvider>();
        var centroCostosService = new Mock<ICoDbProvider>();
        var terceroService = new Mock<ICoDbProvider>();
        var tipoReciboCajaService = new Mock<ICoDbProvider>();

        s1.TipoReciboCaja = "RC0";
        s1.Numero = 0;
        s1.Tercero = "tercero existente";
        s1.AccionARealizar = "some action";
        s1.FechaElaboracion = default(DateTime);
        s1.CentroCostos = "cc1";
        s1.CuentaIngresoDinero = "Débito";
        s1.ValorPagado = 1000000d;

        accionARealizarService.Setup(m => m.Exists(new AccionARealizarEntity(s1))).Returns(true);
        centroCostosService.Setup(m => m.Exists(new CentroCostosEntity(s1))).Returns(true);
        terceroService.Setup(m => m.Exists(new TerceroEntity(s1))).Returns(true);
        tipoReciboCajaService.Setup(m => m.Exists(new TipoReciboCajaEntity(s1))).Returns(true);

        ReciboCajaBiz s0 = new ReciboCajaBiz(null, accionARealizarService.Object, centroCostosService.Object,terceroService.Object,tipoReciboCajaService.Object);

        b = this.ValidateReciboCajaModel(s0, s1);

        Assert.AreEqual(true, b);
    }
Run Code Online (Sandbox Code Playgroud)

在这种情况下,模型中的所有内容都是正确的,并且该方法应返回有效标志.

调试时我有这种奇怪的行为.在设置Mocks行为之后,我在Watch窗口中调用了方法,并返回false,如图所示

debug显示行为不能正常工作

我还有一个测试accionARealizar对象不存在的方法,它返回false作为set.但我怀疑它是否正常工作.

更新

根据以下评论的要求,这是ReciboCajaModel

public class ReciboCajaModel
{
    [Required]
    [EnumDataType(enumType: typeof(TipoReciboCaja))]
    public string TipoReciboCaja { get; set; }
    [Required]
    public int Numero { get; set; }
    [Required]
    public string Tercero { get; set; }
    [Required]
    public string AccionARealizar { get; set; }
    [Required]
    public DateTime FechaElaboracion { get; set; }
    [Required]
    public string CentroCostos { get; set; }
    /// <summary>
    /// este campo no sólo enlaza la cuenta donde se hace el abono o accion a realizar, sino también la forma de pago
    /// </summary>
    [Required]
    public string CuentaIngresoDinero { get; set; }
    [Required]
    [Range(0, 999999999999)]
    public double ValorPagado { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

和ReciboCajaBiz构造函数和私有成员

    private ICoDbProvider _reciboCajaService;
    private ICoDbProvider _accionARealizarService;
    private ICoDbProvider _centroCostosService;
    private ICoDbProvider _terceroService;
    private ICoDbProvider _tipoReciboCajaService;

    public ReciboCajaBiz()
    {
        _reciboCajaService = new ReciboCajaService();
        _accionARealizarService = new AccionARealizarService();
    }

    public ReciboCajaBiz(ICoDbProvider reciboCajaService = null, ICoDbProvider accionARealizarService = null, ICoDbProvider centroCostosService = null, ICoDbProvider terceroService = null, ICoDbProvider tipoReciboCajaService = null)
    {
        _reciboCajaService = reciboCajaService == null ? new ReciboCajaService() : reciboCajaService;
        _accionARealizarService = accionARealizarService == null ? new AccionARealizarService() : accionARealizarService;
        _centroCostosService = centroCostosService == null ? new CentroCostosService() : centroCostosService;
        _terceroService = terceroService == null ? new TerceroService() : terceroService;
        _tipoReciboCajaService = tipoReciboCajaService == null ? new TipoReciboCajaService() : terceroService;
    }
Run Code Online (Sandbox Code Playgroud)

Ral*_*oss 5

乍一看,您的Moq表达式可能与您期望的不匹配.

您尝试匹配Exists()函数的对象引用,这意味着它将对对象引用进行相等性检查 - 这将不匹配.你新出了两个不同的对象.

_accionARealizarService.Exists(new AccionARealizarEntity(model))
Run Code Online (Sandbox Code Playgroud)

有关Moq Matching Arguments的更多信息,请参见此处

更改Setup模拟的表达式,以便查看这是否是问题更为慷慨.

你可以It.IsAny()在表达式中使用.

accionARealizarService.Setup(m => m.Exists(It.IsAny<SiigoEntity>())).Returns(true);
Run Code Online (Sandbox Code Playgroud)

一旦工作,您可以使用It.Is()表达式更具体,进行对象属性检查.