繁体   English   中英

Moq - It.Is 参数被评估为 null

[英]Moq - It.Is parameter being evaluated as null

我试图通过实现这个模式来清理我的单元测试。 不幸的是,如果我尝试在匹配中使用 It.Is,我的设置有问题,所以:

public class MockEmployeeExclusionRulesService : Mock<IEmployeeExclusionRulesService>
{
    public MockEmployeeExclusionRulesService MockIsEmployeeExcludedFromSubmissionAsync(FpsFileContentEmployee fpsFileContentEmployee, bool output)
    {
        Setup(x => x.IsEmployeeExcludedFromSubmissionAsync(fpsFileContentEmployee))
            .ReturnsAsync(output);
        return this;
    }
}
_employeeExclusionRulesServiceMock.MockIsEmployeeExcludedFromSubmissionAsync(
    It.Is<FpsFileContentEmployee>(y =>
        y.FpsId == _fpsId &&
        y.PersonOnPayrollId == _personOnPayrollId),
    output: excludeFromSubmission);

当我单步执行代码时,我发现在 Setup 方法中, fpsFileContentEmployeenull 我找到了这个答案,我认为它可以解释发生了什么,但我不确定“使其成为表达式类型变量”是什么意思——我在制作什么表达式以及如何使用它?


尝试一个最小的可重现示例:

public class InputClass
{
    public string Foo {get; set;}
    public string Bar {get; set;}
}

public interface IMockClass
{
    bool DoTheThing(InputClass inputClass);
}
public class MockMockClass : Mock<IMockClass>
{
    public MockMockClass MockDoTheThing(InputClass inputClass, bool output)
    {
        Setup(x => x.DoTheThing(inputClass))
            .Returns(output);
        return this;
    }
}
[TestFixture]
public class AllTheTests
{
    private readonly MockMockClass _mockClassMock = new ();

    [Test]
    public void DoTheThingTest()
    {
        _mockClassMock.MockDoTheThing(
            It.Is<InputClass>(x =>
                x.Foo == "spam"),
            output: true);
    }
}

我相信如果你调试测试并逐行执行,你会发现当它进入MockMockClass.MockDoTheThing()时, inputClass将是null


编辑:看起来问题是试图将It.is分配给一个变量 - 这种情况在此处进一步描述。 不幸的是,我使用的模式是不可避免的,所以我需要找出一个解决方法。

我设法通过创建带有表达式的重载来找到解决方法,如下所示:

public class MockMockClass : Mock<IMockClass>
{
    public MockMockClass MockDoTheThing(InputClass inputClass, bool output)
    {
        Setup(x => x.DoTheThing(inputClass))
            .Returns(output);
        return this;
    }

    public MockMockClass MockDoTheThing(Expression<Func<InputClass, bool>> inputClassMatch, bool output)
    {
        Setup(x => x.DoTheThing(It.Is(inputClassMatch)))
            .Returns(output);
        return this;
    }
}
[TestFixture]
public class AllTheTests
{
    private readonly MockMockClass _mockClassMock = new ();

    [Test]
    public void DoTheThingTest()
    {
        _mockClassMock.MockDoTheThing(x =>
                x.Foo == "spam",
            output: true);
    }
}

这不是我最喜欢的解决方案,但它似乎有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM