Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should writing mocks for unit tests be in a separate commit?

Tags:

It is a bad idea to commit code that no one is using, as it will be hard for the reviewer to understand why it is written, and will be hard to know if code is correct.

As Im writing in TDD, before I write the code logic I write unit tests.
The tests sometimes depend on new mocks, whose first (and only) use is the tests. Applying the above principle, I don't want to commit the mocks by themselves. Thus I end up committing the unit tests and mocks in the same commit.

This makes the commit rather long, and the mocks don't feel like part of it. It will be far nicer to have them in a different commit (and maybe even have it reviewed by a different dev, that understands the mocking code better).

I know this design question can be a matter of taste, but I'm new to TDD, and feel there is probably one solution that is more correct then the other.
Any input will be appreciated.

like image 474
Nimrod Fiat Avatar asked Jun 18 '20 11:06

Nimrod Fiat


1 Answers

The most important policy regarding Git commits is that each commit should pass the build. One could argue that with TDD, it'd make sense to commit each step of the red/green/refactor cycle, like this:

  • Red, commit (but don't do this)
  • Green, commit
  • Refactor, commit

However, if you commit on red, you'll have commits that fail the build, which will make good use of e.g. git bisect impossible. I think it's okay to make separate commits out of the green and refactor phases, if you like, but if you can keep each overall change small, it's not of greatest importance.

If you can add mocks before you add the tests, and the build still passes, I consider that to be acceptable practice. It's not something I'd do myself, but I don't see how it would be a problem.

Usually, a reviewer will look at a combined diff of several commits, so this is unlikely to be confusing.

Still, with TDD, the most common process is to first write the test, and then write just enough code to make the test pass. If that includes mocks, then add them as a reaction to the test.

If you find that it makes for some coarse-grained commits, then that's the TDD process giving you feedback. The feedback isn't that your application of the process is necessarily wrong, but rather that you might benefit from reconsidering your API design.

like image 91
Mark Seemann Avatar answered Sep 28 '22 08:09

Mark Seemann