Java – I should test for situations where nothing happens
If the status is s or P, the sample can be deleted I have the following tests:
@Test public void canBeDeletedWhenStatusIsP() { Sample sample = new Sample(); sample.setState("P"); assertTrue(sample.canBeDeleted()); } @Test public void canBeDeletedWhenStatusIsS() { Sample sample = new Sample(); sample.setState("S"); assertTrue(sample.canBeDeleted()); }
Should I go further? How should I test when the sample cannot be deleted? For example:
@Test public void cantBeDeletedWhenStatusINeitherPNorS() { Sample sample = new Sample(); sample.setState("Z"); assertFalse(sample.canBeDeleted()); }
Is this test useful? What about test naming? Is this logic sufficient to test?
Solution
Saintthread gives you a good "direct" answer
But let's take a step back Because there is an error in your production code Most likely, your production code performs a switch - like operation on this string to represent the sample state Not just once, but in all the methods it provides And... This is not a good OO design!
Instead, you should use polymorphism, such as:
abstract class Sample { boolean canBeDeleted(); // ... probably other methods as well
With various specific subclasses, such as
class ZSample extends Sample { @Override canBeDeleted() { return false; } // ...
Finally, you have
class SampleFactory { Sample createSampleFrom(String stateIdentifier) { // here you might switch over that string and return a corresponding object,for example of class ZSample
Then your test boils down to:
>Testing plant; Enter the example of "Z", which returns an instance of zsexample > sample to test all your subclasses; For example, for an instance of zsexample, canbedeleted() returns false
The key is: your code does FSM (finite state machine) work Then don't use if / else throughout the place; Instead, do oo: create an explicit state machine Moreover, free bonus: this method can also make your sample object immutable; This is usually better than dealing with objects whose state can change over time (for example, immutability helps many threading problems)
Disclaimer: if your "sample" class is just a method, perhaps the above is excessive But in any other case... Maybe step back and see if my suggestions will add value to your design!