Is it worth to write unit-tests for such the simple code:
public class TableController {
private TableView view;
public TableController(TableView view) {
this.view = view;
}
public void onShowTable() {
view.showTable();
}
}
I have a lot of such very simple code in my projects which connects controllers, views, services, remote services, etc. Unit-tests just repeat everything and are usually larger than the code itself:
public class TableControllerTest {
@Test
public void showTable() {
TableView view = createMock(TableView.class);
view.showTable();
replayAll();
TableController controller = new TableController(view);
controller.onShowTable();
verifyAll();
}
}
Are such tests really needed?
Thanks!
No. You don’t have to unit test everything. On the other hand, you might want to try reversing the process and writing the tests first, then the code. In many cases you will find that if you write the test first, you end up writing different code that you thought you would as you’re thinking about it from the perspective of what should be the outcome when you write the test rather than what code should I write. When writing tests in this fashion you’ll find that the tests have much more value than simply exercising the code with them. Once you get the hang of it, you’ll also get a feel for when you need the test and when you don’t — automatic property accessors, for instance, don’t need to be unit tested IMO.
If you’re already doing the tests first, then I’m not sure I understand the question since your tests can’t repeat something that hasn’t been written yet. You’ve used your tests to define what the methods should do. That’s a very useful activity and also protective in the event that other tests cause a breaking change. Much better to find it in a unit test than in a live application.