嘲讽属性 - C# [英] Mocking attributes - C#

查看:184
本文介绍了嘲讽属性 - C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用一个项目中的自定义属性,我想他们在我的单元测试集成。

I use custom Attributes in a project and I would like to integrate them in my unit-tests.

现在我用犀牛制品创建我的嘲笑,但我不明白的方式,以我的属性(有参数)添加到它们。

Now I use Rhino Mocks to create my mocks but I don't see a way to add my attributes (and there parameters) to them.

我错过了什么,或者是不可能的?其他嘲讽框架?还是我和我的属性创建虚拟实现?

Did I miss something, or is it not possible? Other mocking framework? Or do I have to create dummy implementations with my attributes?

例如:我有一个插件架构(IPlugin)的接口,并有到元信息添加到一个属性的属性。然后我寻找与额外的处理插件实现这个属性的属性(存储它的价值,标记为贵只读...)

example: I have an interface in a plugin-architecture (IPlugin) and there is an attribute to add meta info to a property. Then I look for properties with this attribute in the plugin implementation for extra processing (storing its value, mark as gui read-only...)

现在,当我创建一个模拟,我可以很容易地添加一个属性到属性或对象实例本身?

Now when I create a mock can I add easily an attribute to a property or the object instance itself?

编辑:我发现了同样的问题后 - >的链接。答案没有100%,它是以Java ...

I found a post with the same question -> link. The answer there is not 100% and it is Java...

编辑2:这是可以做到...搜索更多一些(关于SO),发现2相关的问题(+答案)

EDIT 2: It can be done... searched some more (on SO) and found 2 related questions (+ answers)

这里和<一个href=\"http://stackoverflow.com/questions/268426/how-do-i-add-attributes-to-a-method-at-runtime\">here

现在,这是已在一种或另一种嘲弄的框架中实现?

Now, is this already implemented in one or another mocking framework?

推荐答案

为什么你就不能这样做:

Why can't you just do something like:

var sut = new SomeRandomAttribute(RestrictionType.Local);
Assert.AreEqual("Yada yada yada", sut.Yada);

如果你想测试code,它访问所有类型和做一些东西,每个的 SomeRandomAttribute 它找到的,我建议你在检索,装饰与您的自定义属性的MethodInfo对象和需要对这些对象执行的操作拆呢。后来应该很容易测试给出一个正确配置的MethodInfo对象和属性。前者可以通过使用特定测试占位符为你的属性像约瑟夫建议来完成。

If you would like to test the code that visits all your types and does some stuff for each of the SomeRandomAttribute's it finds, I would suggest you split it in retrieving the MethodInfo objects that are decorated with your custom attribute and the operations that need to be performed on these objects. The later should be easy to test given a correctly configured MethodInfo object and attribute. The former could be done by using specific test placeholders for your attribute like suggested by Joseph.

这篇关于嘲讽属性 - C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆