首页 > 解决方案 > 使用元组参数模拟对方法的调用

问题描述

我有一个类,它公开一个以元组为参数的公共方法,定义如下 -

public interface IRandomInterface
{
    void FunctionOne((int paramOne, int paramTwo) paramTuple, int paramThree);
}

public class SomeRandomClass:IRandomInterface
{
    public void FunctionOne((int paramOne, int paramTwo) paramTuple, int paramThree)
    {
        Console.WriteLine("Value of paramOne is " + Convert.ToString(paramTuple.paramOne));
        Console.WriteLine("Value of paramTwo is " + Convert.ToString(paramTuple.paramTwo));
        Console.WriteLine("Value of paramThree is " + Convert.ToString(paramThree));
    }
}

此类正在被另一个使用,其定义如下 -

public class AnotherClass
{
    private IRandomInterface _randomInterface;

    public AnotherClass(IRandomInterface randomInterface)
    {
        _randomInterface = randomInterface;
    }

    public void MethodOne()
    {
        Console.WriteLine("Some random logic here....");
        Console.WriteLine("...and then call to SomeRandomClass.FunctionOne");
        _randomInterface.FunctionOne((1,2),3);
    }
}

测试 AnotherClass 时如何模拟依赖项?我试过这个

[Fact]
public void Test1()
{
    //Arrange
    Mock<IRandomInterface> _randomInterfaceMock = new Mock<IRandomInterface>();
    _randomInterfaceMock.Setup(r => r.FunctionOne((It.IsAny<int>,It.IsAny<int>), 3));
    AnotherClass instance = new AnotherClass(_randomInterfaceMock.Object);
    
    //Act
    instance.MethodOne();
    
    //Assert...
}
    

不幸的是编译器不喜欢它。我收到错误 CS1503:

参数 1:无法从 '(method group, method group)' 转换为 '(int paramOne, int paramTwo)' 错误。

我看过这篇文章 - Mock a Tuple List c#这是类似的行,但没有为我解决问题(并且没有明确标记的答案),因此发布了这个问题。

标签: c#unit-testingtuplesmoq

解决方案


推荐阅读