Domanda

I am trying to unit test (in java) a piece of code which has several constructors and some with logic in them. So apart from setting some fields, the constructors may affect certain static objects depending on certain conditions being met. I was wondering how one would go about testing for these given that the code does not provide any getter methods and the fields are private. I am not at liberty to change the original code either. One way I can see if repeat every test I do for each constructor, but it seems a better solution should exist. I saw some solutions on this site and others for unit testing classes with multiple constructors but I did not find anything conforming exactly to my situation.

È stato utile?

Soluzione

The goal of unit testing it to ensure that an object behaves correctly for all possible input and is always in a consistent, expected state. It is especially valuable as classes and modules are being developed. Having no getters should make no difference.

In your case, I recommend throwing a large variety of parameter combinations at all the constructors (normal values, crazy values, null values, edge cases, etc.) and make sure the resulting object behaves as expected. Behaving as expected may mean operating correctly, gracefully failing, or throwing appropriate exceptions.

Surely the objects have some methods beyond the constructors, so you should include those in your tests. If the objects have any side effects, you can check that those occurred as expected.

Lastly, even though you are not at liberty to change the code, perhaps you can extend it by adding some extra methods whose only purpose would be to facilitate unit testing. If the no change rule is a simple coding policy at your organization, surely adding methods with the intention of improving quality would be OK.

On the other hand, if you really can't change the code, why bother unit testing at all? If you can't change the code, you can't fix any bugs unit testing might reveal.

Altri suggerimenti

All you work done by these constructors has some effect, right? So test the effects it has. On those static objects? Examine those. On subsequent behaviour of the object? Test that.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top