首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模拟从抽象类派生的抽象类

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

Stack Overflow用户
提问于 2016-08-05 05:16:48
回答 1查看 384关注 0票数 5

我有两个这样的类

代码语言:javascript
复制
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.

我是不是做错了什么?我怎么能嘲笑它呢?

更新:这对我来说很好地说明了这个问题。

代码语言:javascript
复制
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失败。问题是泛型抽象得到的签名与具体方法的签名相同……我猜它会被这一点弄糊涂。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-05 07:12:47

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

我通过使Do成为一个虚拟方法来让TestMethod1通过。

代码语言:javascript
复制
public abstract class Foo<T> where T : Bar {
    public virtual Bar Do(Bar obj) {
        return null;
    }
    protected abstract Bar Do(T obj);
}

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38777540

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档