Unit Testing Strategy - Verify State of private field
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
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
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:
- Make an
internal
property to expose the field and then grant access via theInternalsVisibleTo
attribute to your test assembly. This way, you can keep encapsulation. - Directly access the field via Reflection. All Testing frameworks that I know have an API for that (e.g.
PrivateObject
in MSTest orMirror
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]
.)
精彩评论