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

Ste*_*ann 5 c# unit-testing moq abstract

我有两个这样的课程

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 {
  ...
}
Run Code Online (Sandbox Code Playgroud)

尝试使用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;
    }
}
}
Run Code Online (Sandbox Code Playgroud)

测试2通过时,Test1失败.问题是泛型抽象获得的具有相同的签名而不是具体方法......我猜它会让人感到困惑.

Nko*_*osi 0

我能够使用提供的示例重现您的问题。

我必须TestMethod1通过创建Do一个虚拟方法来通过。

public abstract class Foo<T> where T : Bar {
    public virtual Bar Do(Bar obj) {
        return null;
    }
    protected abstract Bar Do(T obj);
}
Run Code Online (Sandbox Code Playgroud)

Moq 要求公共方法是虚拟的或抽象的,以便能够模拟它们的实现。