[英]Unit Testing Strategy - Verify State of private field
I have a windows service which recieves messages from a 3rd party service 我有一个Windows服务,收到来自第三方服务的消息
Each time it recieves a message it updates an in-memory record (held in List<MyObj>
) and periodically broadcasts them 每次收到消息时,它都会更新内存中的记录(保存在
List<MyObj>
)并定期广播它们
I would like to test the state of the List 我想测试List的状态
Options I have come up with are 我想出的选择是
Change the visibility of the List from private to protected. 将List的可见性从private更改为protected。 Then make a Test-Specific subclass which has a public property that exposes the state
然后创建一个Test-Specific子类,它具有公开属性的公共属性
add a public property to the class that is only compiled when in debug mode. 将公共属性添加到仅在调试模式下编译的类。 ie
即
#if (DEBUG) public IList<MyObj> TestProperty { get { return _myObj; } } #endif
Which is the best solution (or least bad)?
哪种解决方案最好(或最不好)?
Is there a better way? 有没有更好的办法?
* EDIT * * 编辑 *
Just found this article which provides a thorough run down of all the options 刚刚发现这篇文章提供了所有选项的彻底淡化
http://www.codeproject.com/KB/cs/testnonpublicmembers.aspx http://www.codeproject.com/KB/cs/testnonpublicmembers.aspx
Where possible, try to test the visible results of your code. 尽可能尝试测试代码的可见结果。 You say the class periodically broadcasts the list... well, if you can add extra control to how that broadcast occurs, you can effectively test the contents of the list by forcing it to be broadcast.
你说这个类定期广播列表......好吧,如果你可以对广播的发生方式添加额外的控制,你可以通过强制广播来有效地测试列表的内容。 That's the visible result of the code, so ideally that's what you should be testing.
这是代码的可见结果,所以理想情况下这就是你应该测试的内容。
I'm all for testing internals where it makes sense, but in this case it sounds like you're possibly going a little too far. 我完全是为了测试内部有意义,但在这种情况下,听起来你可能会走得太远。
(Another alternative is to make an internal property, and use [InternalsVisibleTo]
.) (另一种方法是制作内部属性,并使用
[InternalsVisibleTo]
。)
You have two options: 您有两种选择:
internal
property to expose the field and then grant access via the InternalsVisibleTo
attribute to your test assembly. internal
属性以显示该字段,然后通过InternalsVisibleTo
属性授予对测试程序集的访问权限。 This way, you can keep encapsulation. PrivateObject
in MSTest or Mirror
in MbUnit...). PrivateObject
在MSTest的或Mirror
在MbUnit的...)。 HTH. HTH。
Thomas 托马斯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.