Should positive and negative unit tests for one method carry out individual tests?

Say, for example, I have a method that checks valid UK postal codes. I wrote a unit test for this method, which checks when the correct UK zip code is passed, the method returns true.

Should I create a separate unit test to check for an invalid UK zip code or do it in the same unit test?

thanks

+4
source share
3 answers

You must create separate test cases for each case. This will give you confidence that any future code that calls this method will work, also if you refactor, you can see which test fails, instead of just seeing how 1test failed, and not know why.

+5
source

Personally, I would write several tests that verify that it works correctly with different types of valid postal codes (NE1 2XX, NE21 2XX, E1 3YY, etc., checking various valid combinations of characters and numbers) and several failed tests with invalid ones different types (e.g. NEI 3XX).

+1
source

I use two functions, for example test_valid_data() and test_invalid_data() , and two data sets, for example valid_data[] and invalid_data[] . Then I write four testing procedures:

  • test_valid_data (valid_data []): this test must pass
  • test_valid_data (invalid_data []): this test should fail
  • test_invalid_data (valid_data []): this test should fail
  • test_invalid_data (invalid_data []): this test must pass

By working this way, you can pinpoint a failed test according to a specific dataset. This behavior would be difficult to achieve with just one big test. It also confirms that valid data is not considered invalid and vice versa.

+1
source

All Articles