I have an implicit operator in an abstract class that is similar to below which converts the data to provided type.
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
[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?
CodePudding user response:
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);
}