tags:

views:

126

answers:

2

Suppose I have a class ClasswithPrivateState which has a private field that depends strictly on the current system state when the object is created. Currently, this field is initialized inside the constructor.

But then I got stuck at testing this class since I can't change this private field in my testing method to test some cases. I am aware that I can use java reflection to change it, but I am wondering if this means the class design is bad or there is a better way to test it?

+1  A: 

So I guess your object looks like:

public ClassWithPrivateField() {
   this.field = determineStateFromEnvironment();
}

and hence it's difficult to test. It looks like you need to inject the behaviour of determining the environment state, and provide different mocked injections for different test scenarios. Maybe provide the determineStateFromEnvironment() via some strategy object which you can substitute during test scenarios ?

Brian Agnew
Thanks for your suggestion. yeah, that is pretty much what it looks like. One concern I had was that I don't wanna the user to be able to plug in their own behaviour of determineStateFromEnv(), so I intentionally hid it. By using some strategy object, it sort of makes this option open again. But I'm not sure if my thinking makes any sense.
wei
You can still instantiate the strategy object inside your constructor. Frameworks like JMockit (http://code.google.com/p/jmockit/) will still be able to mock the strategy object and thus allow you to simulate system states.
springify
+1  A: 

Something must trigger the state change, is it not possible that your test setup can initialise the conditions to trigger this? I appreciate that it may depend on a lot of things happening, but you should be able to "mock up" the environment, assuming you use interfaces to decouple your components this should be fairly straight forward.

Without knowing your design and what its trying to achieve a general rule is if it is not flexible to test then it is not going to be flexible enough to reuse in different circumstances than what it was originally developed without a lot of refactoring.

vickirk