Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primitive unit-tests

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!

like image 460
Andrey Minogin Avatar asked Dec 28 '09 16:12

Andrey Minogin


2 Answers

Tests for modules like that aren't really needed. However, tests for modules like that aren't hard to write. So there's really no harm in writing the tests. You also have to remember that simple modules of the kind you've shown tend to grow over time. If you don't have a test for the module, then when a new bit of logic is added to the module, you may decide that the delta between the old module and the new logic is too simple to test. Bit by bit the module grows without being tested.

So in the end, I will write the tests even for simple modules since they are simple to write, and they act as place holders for when the modules become more complicated.

like image 56
Robert C. Martin Avatar answered Sep 27 '22 17:09

Robert C. Martin


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.

like image 41
tvanfosson Avatar answered Sep 27 '22 19:09

tvanfosson