我正在使用一个在函数中使用out参数的库,我需要使用该函数测试我的代码。
所以,试图通过我在该项目其余部分使用的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列值不是数字。
我希望:
但是当快乐路径(例如有效的模拟)通过时,但测试失败,因为该方法无效(同一个通过相同的验证作为“有效”模拟的一部分)...它让我完全糊涂了
答案 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);
}