简体   繁体   English

起订量:从可空类型的模拟方法返回 null

[英]Moq : Return null from a mocked method with nullable type

I have an implicit operator in an abstract class that is similar to below which converts the data to provided 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[]?>();
}

I am trying to create unit tests for this class我正在尝试为此 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);
}

How do I verify that my output can also be null?如何验证我的 output 也可以是 null?

If you want to test that the implicit operator works as expected you could just verify that the expected underlying method was called.如果您想测试隐式运算符是否按预期工作,您只需验证是否调用了预期的底层方法。

Something like this;像这样的东西;

[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);
}

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

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