作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试模拟一个具有 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/
我是一名优秀的程序员,十分优秀!