我有两个这样的类
public abstract class Foo<T> where T : Bar {
public Bar Do(Bar obj) {
//I cast to T here and the call the protected one.
}
...
protected abstract Bar Do(T obj);
}
public abstract class FooWithGoo<T> : Foo<T> where T:Bar {
...
}在使用Moq的单元测试中尝试模拟这一点时,new Mock<FooWithGoo<Bar>>()给出了这个异常。
System.ArgumentException: Type to mock must be an interface or an abstract or non-sealed class. ---> System.TypeLoadException: Method 'Do' in type 'Castle.Proxies.FooWithGoo``1Proxy' from assembly 'DynamicProxyGenAssembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.
我是不是做错了什么?我怎么能嘲笑它呢?
更新:这对我来说很好地说明了这个问题。
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace UnitTestProject1
{
public class Bar
{
}
public class BarSub : Bar
{
}
public abstract class Foo<T> where T : Bar
{
public Bar Do(Bar obj)
{
return null;
}
protected abstract Bar Do(T obj);
}
public abstract class FooWithGoo<T> : Foo<T> where T : Bar
{
public FooWithGoo(string x)
{
}
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var mock = new Mock<FooWithGoo<Bar>>("abc");
FooWithGoo<Bar> foo = mock.Object;
}
[TestMethod]
public void TestMethod2()
{
var mock = new Mock<FooWithGoo<BarSub>>("abc");
FooWithGoo<BarSub> foo = mock.Object;
}
}
}当测试2通过时,Test1失败。问题是泛型抽象得到的签名与具体方法的签名相同……我猜它会被这一点弄糊涂。
发布于 2016-08-05 07:12:47
通过提供的示例,我能够重现您的问题。
我通过使Do成为一个虚拟方法来让TestMethod1通过。
public abstract class Foo<T> where T : Bar {
public virtual Bar Do(Bar obj) {
return null;
}
protected abstract Bar Do(T obj);
}Moq要求公共方法要么是虚拟的,要么是抽象的,以便能够模拟它们的实现。
https://stackoverflow.com/questions/38777540
复制相似问题