Monday 24 October 2016

java - JUnit test without variables

This is difficult to unit test because you have a dependency hard-coded into your object. That dependency is the system output console. Remove that dependency from the object and move it to the application's consuming code:



public class Example {
static String method1() {

return "method1";
}

public static void main(String[]args) {
System.out.println(method1());
}
}


Now you can test the method by simply asserting that the value returned by the method is what you expect.




The goal here is to remove dependencies from your code. Things like system console output will have to be somewhere, but you can isolate them behind mockable interfaces as the code gets more complex. Your business logic, the things you want to unit test, should be free from dependencies.

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...