Search code examples
junitcallbackvoidjava-6

Is it possible to determine a method's callback if its type is void and its "return;" had skipped its execution?


I have a method which works like this:

public void deploy(UserInput userInput)  {
   if (userInput is wrong)
      return;

   //start deployment process
}

The userInput consist of individual checks in the deploy method. Now, I'd like to JUnit test if the user input check algorithms behave right (so if the deployment process would start or not depending on the right or wrong user input). So I need to test this with right and wrong user inputs. I could do this task by checking if anything has been deployed at all, but in this case this is very cumbersome. So I wonder if it's somehow possible to know in the corresponding JUnit test if the deploy method has been aborted or not (due to wrong user inputs)? (By the way, changing the deploy method is no option.)


Solution

  • You could create a UserInput stub / mock with the correct expectations and verify that only the expected calls (and no more) were made.

    However, from a design point of view, if you were able to split your validation and the deployment process into separate classes - then your code can be as simple as:

    if (_validator.isValid(userInput)) {
      _deployer.deploy(userInput);
    }
    

    This way you can easily test that if the validator returns false the deployer is never called (using a mocking framework, such as jMock) and that it is called if the validator returns true.

    It will also enable you to test your validation and deployment code seperately, avoiding the issue you're currently having.