Moq:如何使用out参数模拟方法?

时间:2013-10-02 15:03:16

标签: c# unit-testing mocking moq fluentvalidation

我正在使用一个在函数中使用out参数的库,我需要使用该函数测试我的代码。

所以,试图通过我在该项目其余部分使用的Moq进行嘲讽。

问题

我知道下面有一面墙,所以问题(提前)是:

  • 根据以下链接:Moq可以使用构造函数模拟项目,该构造函数需要通常不会自己调用的参数吗?
  • 这是我测试代码的问题吗?有了图书馆吗?有了验证库吗?
  • 我是否使用Moq参数?
  • 我在哪里开始调试?

更新:引领到目前为止

我认为这是模拟IXLRow接口的模拟方面的问题。通常看起来XLRow只是从工作簿中实例化而从不通过new XLRow() - 这是一个因素吗?

以下测试通过(注意:模拟):

   [Fact]
    public void TryGetValueCanReturnTrueForVieldWithAnInteger_WhenAccessingFromRow()
    {
        var workbook = new XLWorkbook();
        workbook.Worksheets.Add("TestWS");
        var wb = workbook.Worksheet("TestWS");
        wb.Cell("A1").Value = "12345";

        // NOTE: Here we're referring to the row as part of an instantiated  
        //       workbook instead of Mocking it by itself
        int output;
        Assert.True(wb.Row(1).Cell("A").TryGetValue(out output));
    }

守则

获取有效对象模拟的方法的片段():

// ...other code that sets up other parts of the row correctly
int isAnyInt = 0; //I don't care about this value, only the true/false

// set this to false to true to mimic a row being a legitimate integer
mock.Setup(m => m.Cell("B").TryGetValue(out isAnyInt)).Returns(true);

测试快乐路径的xUnit测试 - 获取有效行的模拟,然后确保它通过验证。 注意:此测试通过。

    [Fact]
    public void Validate_GivenValidRow_ReturnsValid()
    {
        var mockRow = TestHelper.GetMockValidInvoiceDetailsWorksheetRow();

        var validationResult = new InvoiceDetailsWorksheetRowValidator().Validate(mockRow.Object);
        Assert.True(validationResult.IsValid);
    }

xUnit测试(基本上,“验证器是否因单元格不是整数而失败?”) 注意:此测试通过。

    [Fact]
    public void Validate_GivenNonNumericClaimantID_ReturnsInvalid()
    {
        int outint = 0;

        // Get a mock of a valid row
        var mockRow = TestHelper.GetMockValidInvoiceDetailsWorksheetRow();

        // change the TryGetValue result to false
        mockRow.Setup(m => m.Cell("B").TryGetValue(out outint)).Returns(false);

        var validationResult = new InvoiceDetailsWorksheetRowValidator().Validate(mockRow.Object);
        Assert.False(validationResult.IsValid);
        Assert.Equal("ClaimantID column value is not a number.", validationResult.Errors.First().ErrorMessage);
    }

验证器(使用FluentValidation):

public class InvoiceDetailsWorksheetRowValidator : AbstractValidator<IXLRow>
{
    public InvoiceDetailsWorksheetRowValidator()
    {
        RuleFor(x => x.Cell("B"))
            .Must(BeAnInt).WithMessage("ClaimantID column value is not a number.")
            .OverridePropertyName("ClaimantIDColumn");

    }

    private bool BeAnInt(IXLCell cellToCheck)
    {
        int result;
        var successful = cellToCheck.TryGetValue(out result);
        return successful;
    }
}

供参考,来自库的方法:

    public Boolean TryGetValue<T>(out T value)
    {
        var currValue = Value;

        if (currValue == null)
        {
            value = default(T);
            return true;
        }

        bool b;
        if (TryGetTimeSpanValue(out value, currValue, out b)) return b;

        if (TryGetRichStringValue(out value)) return true;

        if (TryGetStringValue(out value, currValue)) return true;

        var strValue = currValue.ToString();
        if (typeof(T) == typeof(bool)) return TryGetBasicValue<T, bool>(out value, strValue, bool.TryParse);
        if (typeof(T) == typeof(sbyte)) return TryGetBasicValue<T, sbyte>(out value, strValue, sbyte.TryParse);
        if (typeof(T) == typeof(byte)) return TryGetBasicValue<T, byte>(out value, strValue, byte.TryParse);
        if (typeof(T) == typeof(short)) return TryGetBasicValue<T, short>(out value, strValue, short.TryParse);
        if (typeof(T) == typeof(ushort)) return TryGetBasicValue<T, ushort>(out value, strValue, ushort.TryParse);
        if (typeof(T) == typeof(int)) return TryGetBasicValue<T, int>(out value, strValue, int.TryParse);
        if (typeof(T) == typeof(uint)) return TryGetBasicValue<T, uint>(out value, strValue, uint.TryParse);
        if (typeof(T) == typeof(long)) return TryGetBasicValue<T, long>(out value, strValue, long.TryParse);
        if (typeof(T) == typeof(ulong)) return TryGetBasicValue<T, ulong>(out value, strValue, ulong.TryParse);
        if (typeof(T) == typeof(float)) return TryGetBasicValue<T, float>(out value, strValue, float.TryParse);
        if (typeof(T) == typeof(double)) return TryGetBasicValue<T, double>(out value, strValue, double.TryParse);
        if (typeof(T) == typeof(decimal)) return TryGetBasicValue<T, decimal>(out value, strValue, decimal.TryParse);

        if (typeof(T) == typeof(XLHyperlink))
        {
            XLHyperlink tmp = GetHyperlink();
            if (tmp != null)
            {
                value = (T)Convert.ChangeType(tmp, typeof(T));
                return true;
            }

            value = default(T);
            return false;
        }

        try
        {
            value = (T)Convert.ChangeType(currValue, typeof(T));
            return true;
        }
        catch
        {
            value = default(T);
            return false;
        }
    }

问题

第一次测试通过。但是当我运行这个测试时,它失败了:

   [Fact]
   public void Validate_GivenNonNumericInvoiceNumber_ReturnsInvalid()
    {
        int outint = 0; // I don't care about this value

        // Get a mock of a valid worksheet row
        var mockRow = TestHelper.GetMockValidInvoiceDetailsWorksheetRow();

        mockRow.Setup(m => m.Cell("E").TryGetValue(out outint)).Returns(false);

        // Validates & asserts
        var validationResult = new InvoiceDetailsWorksheetRowValidator().Validate(mockRow.Object);
        Assert.False(validationResult.IsValid);

        // Placed here to ensure it's the only error message. This is where it fails.
        Assert.Equal("InvoiceNumber column value is not a number.",validationResult.Errors.First().ErrorMessage);
    }

但它没有失败,因为验证尚未实现 - 它失败,因为其他项目首先是无效的,即使我从获得有效的模拟返回它 - 通过测试的相同有效模拟否则。

确切地说,信息是:

  

Assert.Equal()失败

     

位置:第一个区别是位置0

     

预期:InvoiceNumber列值不是数字。

     

实际:ClaimantID列值不是数字。

我希望:

  • 它的工作方式与其他测试的工作方式相同,或
  • 因为快乐的道路也失败了。

但是当快乐路径(例如有效的模拟)通过时,但测试失败,因为该方法无效(同一个通过相同的验证作为“有效”模拟的一部分)...它让我完全糊涂了

供参考

2 个答案:

答案 0 :(得分:1)

我认为您不需要测试 TryGetValue 在图书馆里。

放入 BeAnInt 在一个单独的类 XLCellHelpers 中,使用 IXLCell

的模拟进行测试

XLCellHelpers 创建一个接口,例如 IXLCellHelpers ,将其注入到您的验证器中: InvoiceDetailsWorksheetRowValidator

模拟 IXLCellHelpers 以测试验证器。

赞:

using System;
                    
public class InvoiceDetailsWorksheetRowValidator : AbstractValidator<IXLRow>
{
private readonly IXlCellHelpers xlCellHelpers;

    InvoiceDetailsWorksheetRowValidator(IXlCellHelpers xlCellHelpers)
    {
        this.xlCellHelpers = xlCellHelpers;
    }
    
    public InvoiceDetailsWorksheetRowValidator()
    {
        RuleFor(x => x.Cell("B"))
            .Must(this.xlCellHelpers.BeAnInt).WithMessage("ClaimantID column value is not a number.")
            .OverridePropertyName("ClaimantIDColumn");
    }
}

public interface IXlCellHelpers
{
    bool BeAnInt(IXLCell cellToCheck);
}

public class XlCellHelpers : IXlCellHelpers
{   
    publi bool BeAnInt(IXLCell cellToCheck)
    {
        int result;
        var successful = cellToCheck.TryGetValue(out result);
        return successful;
    }
}

答案 1 :(得分:0)

尽管我喜欢FluentValidator,但这是我讨厌使用Fluent验证器进行测试时遇到的问题之一。

受测系统:

  public class InvoiceDetailsWorksheetRowValidator : AbstractValidator<IXLRow>
  {
      public InvoiceDetailsWorksheetRowValidator()
      {
        RuleFor(x => x.Cell("B"))
            .Must(BeAnInt).WithMessage("ClaimantID column value is not a number.")
            .OverridePropertyName("ClaimantIDColumn");

        RuleFor(x => x.Cell("E"))
            .Must(BeAnInt).WithMessage("InvoiceNumber column value is not a number.")
            .OverridePropertyName("ClaimantIDColumn");

      }

      private bool BeAnInt(IXLCell cellToCheck)
      {
        int result;
        var successful = cellToCheck.TryGetValue(out result);
        return successful;
      }
  }

单元测试:

  [Fact]
  public void Validate_GivenNonNumericClaimantID_ReturnsInvalid()
  {
     int outint = 0;

     // Get a mock of a valid row
     //var mockRow = TestHelper.GetMockValidInvoiceDetailsWorksheetRow();
       var mockRow = new Mock<IXLRow>();

     // change the TryGetValue result to false
     mockRow.Setup(m => m.Cell("B").TryGetValue(out outint)).Returns(false);

     var validationResult = new InvoiceDetailsWorksheetRowValidator().Validate(mockRow.Object);

     Assert.True(validationResult.Errors.Any
       (x => x.ErrorMessage == "ClaimantID column value is not a number."));

     //Other option:
     //validationResult.Errors.Remove(validationResult.Errors.First(x => x.ErrorMessage == "InvoiceNumber column value is not a number."));
     //Assert.Equal("ClaimantID column value is not a number.", validationResult.Errors.First().ErrorMessage);
  }

 [Fact]
 public void Validate_GivenNonNumericInvoiceNumber_ReturnsInvalid()
 {
     int outint = 0; // I don't care about this value

     // Get a mock of a valid worksheet row
     var mockRow = new Mock<IXLRow>();
     mockRow.Setup(m => m.Cell("E").TryGetValue(out outint)).Returns(false);

     // Validates & asserts
     var validationResult = new InvoiceDetailsWorksheetRowValidator().Validate(mockRow.Object);

     Assert.True(validationResult.Errors.Any
          (x => x.ErrorMessage == "InvoiceNumber column value is not a number."));

     //Other option:
     //validationResult.Errors.Remove(validationResult.Errors.First(x => x.ErrorMessage == "ClaimantID column value is not a number."));
     //Assert.Equal("InvoiceNumber column value is not a number.", validationResult.Errors.First().ErrorMessage);
  }
相关问题