开发者

Unit Testing Strategy - Verify State of private field

开发者 https://www.devze.com 2023-01-26 09:34 出处:网络
I have a windows service which recieves messages from a 3rd party service Each time it recieves a message it updates an in-memory record (held in List<MyObj>) and periodically broadcasts them

I have a windows service which recieves messages from a 3rd party service

Each time it recieves a message it updates an in-memory record (held in List<MyObj>) and periodically broadcasts them

I would like to test the state of the List

Options I have come up with are

  1. Change the visibility of the List from private to protected. Then make a Test-Specific subclass which has a public property that exposes the state

  2. add a public property to the class that is only compiled when in debug mode. i.e.

#if (DEBUG)
        public IList<MyObj> TestProperty
        {
            get { return _myObj; }
        }
#endif

开发者_StackOverflow中文版 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


You have two options:

  1. Make an internal property to expose the field and then grant access via the InternalsVisibleTo attribute to your test assembly. This way, you can keep encapsulation.
  2. Directly access the field via Reflection. All Testing frameworks that I know have an API for that (e.g. PrivateObject in MSTest or Mirror in MbUnit...).

HTH.
Thomas


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].)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号