模拟从抽象类派生的抽象类

5
我有两个像这样的类
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.是否有做错的地方?如何进行Mock操作?
更新:这对我来说很好地显示了问题。
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;
    }
}
}

测试1失败,而测试2通过。 问题在于通用抽象类获得了与具体方法相同的签名...我想它被搞混了。


我现在可以重现这个问题。你的猜测听起来很有道理。 - tster
1个回答

0

我能够通过提供的示例重现您的问题。

我通过将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要求公共方法必须是虚拟的或抽象的,以便能够模拟它们的实现。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接