gpt4 book ai didi

c# - Moq It.IsSubtype 没有隐式引用转换

转载 作者:行者123 更新时间:2023-12-05 01:06:08 24 4
gpt4 key购买 nike

我正在尝试模拟一个具有 T : IFoo

约束的泛型方法

但是起订量似乎无法理解转换并给出以下错误:

The type 'Moq.It.IsSubtype<SomeNamepace.IFoo>'cannot be used as type parameter 'T' in the generic type or method'IMyClass.DoSomething(Action)'. There is no implicit referenceconversion from'Moq.It.IsSubtype<SomeNamepace.IFoo>' to'SomeNamepace.IFoo'.

    public interface IFoo
{
}

class Foo : IFoo
{

}

public interface IMyClass
{
public IDisposable DoSomething<T>(Action<T> asd) where T : IFoo;
}

public class MyTest
{
[Test]
public void SomeTest()
{
var mock = new Mock<IMyClass>();

mock.Setup(e => e.DoSomething(It.IsAny<Action<IFoo>>())).Returns(Mock.Of<IDisposable>());

// What I want but gives compiler error
// mock.Setup(e => e.DoSomething(It.IsAny<Action<It.IsSubtype<IFoo>>>())).Returns(Mock.Of<IDisposable>());


// Action<IFoo> would work, but in real code its not used like that
Action<Foo> myAction = (e) => { };
var result = mock.Object.DoSomething(myAction);

result.Dispose(); // Null reference exception
}
}

最佳答案

自从 It.IsSubtype<IFoo>未实现 IFoo ,你不能这样用。由于类型限制。

但是,您可以使用 IFoo就其本身而言,这应该说明您传入的任何值,因为它们都需要实现 IFoo .换句话说,类型约束已经为您完成了确保类型正确的繁重工作。例如,给定这样的设置:

public interface IFoo
{
}

public interface IMyClass
{
string DoSomething<T>() where T : IFoo;
}

您的测试代码应该是这样的:

var mock = new Mock<IMyClass>();
mock.Setup(e => e.DoSomething<IFoo>()).Returns("cheese");

var result = mock.Object.DoSomething<IFoo>();

Assert.Equal("cheese", result); // true

编辑:

在对问题进行额外澄清后,上面的答案仍然有效,我们可以做类似的事情:

mock
.Setup(e => e.DoSomething<Foo>(It.IsAny<Action<Foo>>()))
.Returns(new MyDisposableObject());

现在我们使用 Foo因为我们明确知道传入的类型,所以我们不再需要担心接口(interface)。事实上,我们甚至可以简化代码,因为我们不再需要明确说明泛型类型:

mock
.Setup(e => e.DoSomething(It.IsAny<Action<Foo>>()))
.Returns(new MyDisposableObject());

关于c# - Moq It.IsSubtype 没有隐式引用转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69800011/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com