Unit Test for a Method that Changes the State of a private Field
So, I have the following problem (using C#):
I have two private fields in a class, one that saves the original state of a field and one that saves the updated state.
I now want to write a method that basically takes the original state, copies it to the updated state and changes some of its content.
So far I have implemented that as a void method which just changes the state of the fields (if needed). These fields will later be used by another method.
I don't think I will have any 开发者_开发问答trouble with the implementation, but I'm trying to write unit tests for this method (with MSTest) and can't see how I can properly test this.
The thing I would really need to test is whether given the input parameters the content of the field has changed compared to its original state or not. Since both fields are private I can neither access the original state to set a value for the unit test nor can I access the fields to use for any comparisons for any assertions.
The easiest way would be to expose all these fields with public properties, but I really have no use for public properties apart from the unit tests. Another way would be to rewrite the method to return the updated state, but that still doesn't help me in setting the original state to what I need for the tests.
Any ideas or best practices on how to approach this?
Use PrivateObject.GetField()
to retrieve the final state of that field. (privateObject members)
This is the better route than modifying the API merely to make it test-able.
What visible change does it make if the fields are copied properly? Presumably it affects the behaviour of the object in some way... so that's the ideal thing to test.
Sometimes it can be worth adding internal helper methods for the sake of testability (in conjunction with InternalsVisibleTo
) but ideally, testing the changes to visible behaviour/state is a less fragile approach.
精彩评论