派生抽象類我有兩個類這樣懲戒從抽象類
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失敗。 問題是通用抽象比具體方法獲得相同的簽名......並且它被我猜測弄糊塗了。
我現在可以重現這一點。你的猜測對我來說聽起來很合理 – tster