How an Unit Test should look like

Often during my life as a programmer, coach and trainer I have to explain how a test should look like. So I decided to write about this subject.

Remember that code, especially test code, is read more often than written. Often you will be the person to read it after you wrote it. So do yourself a favour and write the test well, be expressive, make the test speak for itself without searching any method signature, package, module or interface.

So here are the main characteristics of a good test in my view:

  1. Testing_the_Tesla_at_Argonne_National_Laboratory_(3)Write your test by using the language of the domain
    Because the test should represent the reason why a feature exists in your product. Always the reason comes from the business side. A person that knows the business domain, but does not know programming should be able to read your test. A good batch of unit tests should be like a newspaper article: titles, paragraphs. Anyone understanding that language should be able to read the newspaper article.
  2. You should test only one atomic behaviour
    You do not want to have tens of red tests when something brakes or changes because you will have a hard time understanding what happens. If you do not test one atomic behavior it is very possible you will write tests that overlap. You want one test for one small behavior, and that test will tell you if something was changed in the production system. For me a unit test means that the unit you test is the behavior. If you test more behaviors in a test, then it is not a unit test. It can be an integration test, an acceptance test, an integrated test, an end-to-end test or any other type of test. And of course, an unit test should have minimum one and maximum one verification.
  3. A test should be very clear
    The purpose of writing this test should be expressed in its name. An unit test should be very short and clear, ideally 2-3 lines of code. All your variables from the test should be named appropriately for their usage. Your assert should express what you verify. If your assert does not express what you verify, you can always create a private function with a clear name to express what you verify.

So these are the main characteristics in an unit test. Now, I leave you with a question: when is the last time you showed your unit tests to non-technical people. If you have not, try doing that and see what they understand. This is the ultimate test of your tests quality.

Would you like to have better tested deliverables? We can help with:

If the situation is more complex, we would be happy to create a customized package for your needs.

More from the Blog

Leave a Comment

Your email address will not be published. Required fields are marked *

    Your Cart
    Your cart is empty
      Apply Coupon
      Available Coupons
      individualcspo102022 Get 87.00 off
      Unavailable Coupons
      aniscppeurope2022 Get 20.00 off
      Scroll to Top