How would you assert code like this? What would be the best approach to do so?
public void doSomething(int myProperty){
if (myProperty == 0) return;
// If myProperty is not zero, do something in the method
}
How would you assert code like this? What would be the best approach to do so?
public void doSomething(int myProperty){
if (myProperty == 0) return;
// If myProperty is not zero, do something in the method
}
If this code returns nothing, what is its purpose? What will be wrong if you remove this line?
If you find a valuable answer to these questions, you will find hints to test your code.
If you find no answer, then you can safely remove the line (and thus have no test to write).
You could assert that whatever happens after the return
doesn't happen when myProperty
is zero.
For example, if the method is (pseudo code!)
if myProperty == 0 return
myOtherProperty = 2
then your unit test could
myProperty
is set to zero, myOtherProperty
is set to something other than 2
myOtherProperty
is still set to what it was set to before.The question I ask when I see this is: what happens when myProperty is not zero?
Is there code after this return that alters class level/shared state? Can you assert against the class level/shared state to verify the behaviour?
When myProperty is zero, then the state should be unaffected by the method
You didn't post the method signature, so I suppose that it has void as return type. In this case there's no way to test it like you pointed; but if the method interacts with object scope properties you can test them to see if they change or not.
No matter what you do, you need to test against observable effects. Surely your method must be doing something.
When using state-based testing, you can inspect the state of your SUT or the Fixture after having executed the method to see if the state matches your expecations.
When that is not possible, you will need to perform Behavior Verification (aka interaction-based testing. This is often done with mock objects.
I think Mark Seemann gave you complete answer - this is just an illustration to it.
SomeVerifiableClass actor;
public void doSomething(int myProperty){
if (myProperty == 0) return;
// If myProperty is not zero, do something in the method
actor.doesSomething(myProperty);
}
Then your choices are to mock SomeVerifiableClass or to test with real one. If you use DI properly then mocking is a better option.
Mocking: validating behavior (pseudo code):
verify(mockedActor).noMethodsCalled();
In case of real object you validate state:
assert(isPrestine(actor));
If there is no actor in your case then you should be able to verify state of tested object (the one that executes doSomething).