[英]How can I set a generic parameter in the moq setup?
我正在嘗試使用 MOQ 設置具有通用功能的模擬界面。 該函數具有以下符號:
public interface IWizard
{
bool Cast<TSpell>(TSpell spell)
where TSpell : SpellBase, IComponents;
}
當我嘗試設置設置功能時,我似乎無法直接完成它。 我不斷收到消息,說不可能進行隱式轉換。 它包含以下文本:“沒有從“SpellBase”到“IComponents”的隱式引用轉換。
var wizard = new Mock<IWizard>();
wizard
.Setup(x => x.Cast(It.IsAny<SpellBase>())) // this line has an error
.Returns(true);
除了實現同時實現SpellBase
和IComponents
的基類之外,我還有哪些選擇? 這甚至可能嗎?
EDIT1:我嘗試通過以下方式實施 Piotr 的方法:
[Test]
public void Test_JsonConvert_Performace()
{
var wizard = new Mock<IWizard>();
wizard
.Setup(x => x.Cast(It.IsAny<TestSpell>()))
.Returns(true);
var result = wizard.Object.Cast(new RealSpell());
Assert.IsTrue(result);
}
public interface IWizard
{
bool Cast<TSpell>(TSpell spell)
where TSpell : SpellBase, IComponents;
}
public abstract class SpellBase
{
}
public interface IComponents
{
}
public class TestSpell : SpellBase, IComponents
{
}
public class RealSpell : SpellBase, IComponents
{
}
不幸的是我的測試失敗了。
Fist 選項:您需要從IWizard.Cast
約束中刪除IComponent
public interface IWizard
{
bool Cast<TSpell>(TSpell spell) where TSpell : SpellBase, IComponents;//wont compile
bool Cast<TSpell>(TSpell spell) where TSpell : SpellBase; //will compile
}
第二種選擇:創建一個繼承SpellBase
並實現IComponents
public class ComponetsSpellBase:SpellBase, IComponents
{
//IComponents Implementation
}
wizard.Setup(x => x.Cast(It.IsAny<ComponetsSpellBase>())).Returns(false);
public class FireSpell:ComponentSpellBase{}
您可以使用通用方法創建模擬:
[TestMethod]
void Test()
{
var wizard = MockObject<TestSpell>();
}
private Mock<IWizard> MockObject<T>() where T : SpellBase, IComponents
{
var mock = new Mock<IWizard>();
mock.Setup(pa => pa.Cast(It.IsAny<T>()))
.Returns(true);
return mock;
}
private class TestSpell : SpellBase, IComponents
{ }
TestSpell
類僅在您的測試項目中是必需的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.