2016-08-04 79 views
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.

有什么我做错了吗?我怎么嘲笑这个?

更新: 这显示了对我来说很好的问题。

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失败。 问题是通用抽象比具体方法获得相同的签名......并且它被我猜测弄糊涂了。

+0

我现在可以重现这一点。你的猜测对我来说听起来很合理 – tster

回答

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); 
} 

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