Unit Testing something that returns nothing, how to assert?

How would you state such a code? What would be the best way to do this?

public void doSomething(int myProperty){
    if (myProperty == 0) return;
    // If myProperty is not zero, do something in the method
}

      

+2


a source to share


6 answers


You can argue that whatever happens after return

does not happen when it myProperty

is zero.

For example, if the method (pseudo code!)

if myProperty == 0 return

myOtherProperty = 2

      



then your unit test could

  • Arrange what's myProperty

    set to zero is myOtherProperty

    set to something other than2

  • Act by calling the method under test
  • Assert , which myOtherProperty

    is still set to what it was installed for before.
+3


a source


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 don't find an answer, you can safely delete the line (and therefore not have a test to write).

+7


a source


Whatever you do, you need to test against the observed effects . Of course, your method has to do something.

When using a health check, you can check the status of the SUT or Fixture after it has executed this method to see if the status matches your results.

If this is not possible, you need to perform Behavior Testing (aka interaction-based testing . This is often done with mock objects .

+4


a source


I think Mark Seemann gave you a complete answer - this is just an illustration of him.

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 choice is to mock SomeVerifiableClass or test with a real one. If you use DI correctly, then ridicule is the best option.

Rejection: Checking behavior (pseudocode):

  verify(mockedActor).noMethodsCalled();

      

In the case of a real object, you check the state:

  assert(isPrestine(actor));

      

If there is no actor in your case, you should be able to check the state of the object under test (the one that does doSomething).

+1


a source


The question I ask when I see this is: what happens when myProperty is nonzero?

Is there any code after this return that changes the class / shared state? Can you assert against a class / general state to test the behavior?

When myProperty is zero, then the state should not be affected by the method

0


a source


You haven't posted the method signature, so I'm guessing it's not valid as a return type. In this case, there is no way to test it as you indicated; but if the method interacts with the properties of the object's scope, you can check them to see if they have changed or not.

0


a source







All Articles