最小起订量:Return null 来自具有可空类型的模拟方法

Moq : Return null from a mocked method with nullable type

我在抽象 class 中有一个隐式运算符,类似于下面将数据转换为提供的类型。

public abstract class MyClass
{
    private object dataHolder; // just for representation
    // at implementation it tries to convert dataHolder object
    // or returns null if failed
    public abstract T? Convert<T>();
    public static implicit operator byte[]?(MyClass obj) => obj.Convert<byte[]?>();
}

我正在尝试为此创建单元测试 class

[TestMethod]
public void MyTestMethod()
{
    Mock<MyClass> mockedClass = new() { CallBase = true };
    mockedClass.Setup(x => x.Convert<byte[]?>()); // no return statement
    // this should be null using implicit operator
    byte[]? output = mockedClass.Object;

    // however I am receiving an empty byte[] (length 0).
    Assert.IsNull(output);
}

如何验证我的输出也可以为空?

如果您想测试隐式运算符是否按预期工作,您只需验证是否调用了预期的底层方法。

像这样;

[Test]
public void VerifyThatImplicitOperatorWorksAsExpected()
{
    Mock<MyClass> mockedClass = new() { CallBase = true };
    mockedClass.Setup(x => x.Convert<byte[]?>()).Returns<byte[]?>(null);
    byte[]? output = mockedClass.Object;

    Assert.IsNull(output);
    // Verify that the Convert method was called.
    mockedClass.Verify(x => x.Convert<byte[]?>(), Times.Once);
}