![](/img/trans.png)
[英]Can I use moq Mock<MyClass> to mock a class, not an interface?
[英]Can I get Moq to add attributes to the mock class?
我正在為我的項目編寫命令行界面。 用戶輸入“create project foo”,它找到負責“project”的控制器,然后調用Create
方法,將“foo”作為第一個參數傳遞。
它在很大程度上依賴於屬性和反射:控制器看起來像這樣:
[ControllerFor("project")]
class ProjectController
{
[ControllerAction("create")]
public object Create(string projectName) { /* ... */ }
}
我想在解析器的單元測試中使用Moq,如下所示:
Mock<IProjectsController> controller = new Mock<IProjectsController>();
controller.Expect(f => f.Create("foo"));
parser.Register(controller.Object);
parser.Execute("create project foo");
controller.VerifyAll();
將屬性添加到接口似乎不起作用 - 它們不是由派生類繼承的。
我可以讓Moq為被模擬的類添加屬性嗎?
更新:我剛剛意識到您可以使用TypeDescriptor.AddAttributes實際向現有類型添加屬性,可以針對實例或類型執行:
Mock<IRepository> repositoryMock = new Mock<IRepository>();
CustomAttribute attribute = new CustomAttribute();
// option #1: to the instance
TypeDescriptor.AddAttributes(repositoryMock.Object, attribute );
// option #2: to the generated type
TypeDescriptor.AddAttributes(repositoryMock.Object.GetType(), attributes);
如果需要,AddAttribute將返回一個TypeDescriptorProvider,可以將其傳遞給TypeDescriptor.RemoveProvider以刪除之后的屬性。
請注意, Attribute.GetCustomAttributes不會以這種方式找到在運行時添加的屬性。 而是使用TypeDescriptor.GetAttributes 。
原始答案
我不相信Moq(或任何其他模擬框架)支持自定義屬性。 我知道Castle Proxy(通常用於實際創建類的框架) 確實支持它,但是沒有辦法通過Moq訪問它。
你最好的辦法是將你的屬性加載方法抽象為一個接口(接受Type和Attribute類型),然后模擬它。
編輯:例如:
public interface IAttributeStrategy
{
Attribute[] GetAttributes(Type owner, Type attributeType, bool inherit);
Attribute[] GetAttributes(Type owner, bool inherit);
}
public class DefaultAttributeStrategy : IAttributeStrategy
{
public Attribute[] GetAttributes(Type owner, Type attributeType, bool inherit)
{
return owner.GetCustomAttributes(attributeType, inherit);
}
public Attribute[] GetAttributes(Type owner, bool inherit)
{
return owner.GetCustomAttributes(inherit);
}
}
需要屬性的類使用IAttributeStrategy的實例(通過IoC容器,或者可選地將其傳遞給構造函數)。 通常它將是DefaultAttributeStrategy,但您現在可以模擬IAttributeStrategy以覆蓋輸出。
這可能聽起來很復雜,但添加一層抽象比試圖實際模擬屬性要容易得多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.