Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如果没有默认构造函数,如何在对象上模拟方法?_C#_Moq - Fatal编程技术网

C# 如果没有默认构造函数,如何在对象上模拟方法?

C# 如果没有默认构造函数,如何在对象上模拟方法?,c#,moq,C#,Moq,使用moq,如果我试图直接在Foo上模拟一个方法,我会得到这样的结果:在非虚拟(在VB中可重写)成员上验证无效。 我的选择是mockIFoo,它解决了上述问题,但是我无法构造它,因为Foo没有无参数构造函数(构造函数参数不能为接口mock传递。)。我能做什么?Moq创建了一个代理对象,它要求所有模拟方法都是可重写的,并且类不是密封的。因此,您可以将您的方法标记为虚拟 下面的代码可以正常工作: public interface IFoo { int Test(int myParameter

使用moq,如果我试图直接在
Foo
上模拟一个方法,我会得到这样的结果:
在非虚拟(在VB中可重写)成员上验证无效。


我的选择是mock
IFoo
,它解决了上述问题,但是我无法构造它,因为
Foo
没有无参数构造函数(
构造函数参数不能为接口mock传递。
)。我能做什么?

Moq创建了一个代理对象,它要求所有模拟方法都是可重写的,并且类不是密封的。因此,您可以将您的方法标记为虚拟

下面的代码可以正常工作:

public interface IFoo
{
    int Test(int myParameter);
    int TestInternal(int myParameter);
}

public class Foo : IFoo
{
    private int _someConstructorArgument;

    public Foo(int someConstructorArgument)
    {
        _someConstructorArgument = someConstructorArgument;
    }

    public virtual int Test(int myParameter)
    {
        return _someConstructorArgument + TestInternal(myParameter);
    }

    public virtual int TestInternal(int myParameter)
    {
        return myParameter;
    }
}

public class Program
{
    static void Main(string[] args)
    {
        var mock = new Mock<Foo>(MockBehavior.Loose, 50);

        mock.Setup(x => x.TestInternal(100))
            .Returns(200);

        mock.CallBase = true;

        Console.WriteLine(mock.Object.Test(100));
        Console.ReadLine();
    }
}
公共接口IFoo
{
int测试(int-myParameter);
int TestInternal(int myParameter);
}
公共类Foo:IFoo
{
私有内部构造参数;
公共Foo(int-someConstructorArgument)
{
_someConstructorArgument=someConstructorArgument;
}
公共虚拟int测试(int myParameter)
{
返回_someConstructorArgument+TestInternal(myParameter);
}
公共虚拟int TestInternal(int myParameter)
{
返回myParameter;
}
}
公共课程
{
静态void Main(字符串[]参数)
{
var mock=新的mock(MockBehavior.Loose,50);
mock.Setup(x=>x.TestInternal(100))
.申报表(200份);
mock.CallBase=true;
Console.WriteLine(mock.Object.Test(100));
Console.ReadLine();
}
}

您应该能够毫无问题地模拟IFoo,并且在模拟接口时没有理由传递参数。您的IFoo mock就是这样(一个mock!),并且不了解Foo或任何实际实现,因此传递构造函数参数是没有意义的


编辑:我想补充一点,如果接口存在,模拟接口几乎总是比模拟具体实现更可取。如果您只有一个具体的实现,那么您想要模拟它这一事实可能意味着它将是添加接口的一个很好的候选者。

您完全正确。我甚至没有想清楚,我只是想找点事做。谢谢