C# Moq 中的模拟 IDisposable.Dispose() 方法

Mock IDisposable.Dispose() method in C# Moq

下面class是给我的,我需要为此编写测试用例。除了 Dispose()

之外,我能够编写的所有其他测试用例

注意:我不允许修改class DataProvider。

有人可以帮助我使用 Moq 框架编写 Dispose() 方法的测试用例。

public class DataProvider<TInput, TRequest, TResponse, TOutput>:IDataProvider<TInput,TOutput> , IDisposable where TRequest : class, new()
where TResponse : class, new()
{

    private readonly ICompose<TInput, TRequest> requestComp;
    private readonly ICompose<TResponse, TOutput> responseComp;
    private bool disposed;
    private readonly IData idata;

    public DataProvider(IConverter<TInput, TRequest> requestComp,
                           IConverter<TResponse, TOutput> responseComp,
                           IDealer dealer,
                           string passcode)
    {
        this.requestComp = requestComp;
        this.responseComp = responseComp;
        this.idata= dealer.GetCalculatedData(passcode);
    }

    public void Dispose()
    {
        if (this.disposed)
        {
            return;
        }

        this.idata?.Dispose();

        this.disposed = true;
    }

    #endregion - IDispose end


    public void GetData(TInput input)
    {
        //Do something here 
    }
}

下面是一些代码,应该解释测试的每个步骤。

[TestMethod]
public void Test()
{
    // Arrange.
    var mockData = new Mock<IData>();
    var mockDealer = new Mock<IDealer>();

    // Setup mockDealer so that the GetCalculatedData returns the object from mockData.
    mockDealer.Setup(d => d.GetCalculatedData(It.IsAny<string>())).Returns(mockData.Object);
    
    // Create the tested object (the DataProvider) using mocked dependencies.
    var dataProvider = new DataProvider<object, object, object, object>(
        requestComp: It.IsAny<IConverter<object, object>>(), 
        responseComp: It.IsAny<IConverter<object, object>>(), 
        dealer: mockDealer.Object,
        passcode: It.IsAny<string>()
    ); 
    
    // Act.
    dataProvider.Dispose();

    // Assert.
    // Verify that Dispose was called on the IData object.
    mockData.Verify(d => d.Dispose());
}

@Batesian、@JeroenMostert、@Nkosi:感谢您的回答。

我根据我的要求调整了代码,它成功了。

[TestMethod]
public void Test()
{
// Arrange.
var mockData = new Mock<IData>();
var mockDealer = new Mock<IDealer>();
var reqComposeMock = new Mock<IConverter<object, object>>();
var resComposeMock = new Mock<IConverter<object, object>>();

// Setup mockDealer so that the GetCalculatedData returns the object from mockData.
mockDealer.Setup(d => d.GetCalculatedData(It.IsAny<string>())).Returns(mockData.Object);

// Create the tested object (the DataProvider) using mocked dependencies.
var dataProvider = new DataProvider<object, object, object, object>(
    requestComp: reqComposeMock.Object, 
    responseComp: resComposeMock.Object, 
    dealer: mockDealer.Object,
    passcode: "passcode"
); 

// Act.
dataProvider.Dispose();

// Assert.
// Verify that Dispose was called on the IData object.
mockData.Verify(d => d.Dispose());
}