๐จ๐ป๐ถ๐ ๐ง๐ฒ๐๐๐ถ๐ป๐ด ๐๐ฒ๐๐ ๐ฃ๐ฟ๐ฎ๐ฐ๐๐ถ๐ฐ๐ฒ๐
Unit testing is software testing in which individual units or components of a software application are tested. Unit testing aims to validate that each software unit performs as designed.
Unit tests ensure code quality, ease of maintenance, facilitate refactoring, and increase development speed.
When we talk about best practices, here is a list of that one should follow:
๐ญ. ๐ช๐ฟ๐ถ๐๐ฒ ๐ฎ ๐ป๐ฒ๐ ๐๐ฒ๐๐ ๐ณ๐ผ๐ฟ ๐ฒ๐๐ฒ๐ฟ๐ ๐ฑ๐ฒ๐ณ๐ฒ๐ฐ๐: When you encounter a defect, write a test that exposes the defect. This is also known as regression testing.
๐ฎ. ๐๐ฒ๐ฒ๐ฝ ๐๐ฒ๐๐๐ ๐๐บ๐ฎ๐น๐น ๐ฎ๐ป๐ฑ ๐ณ๐ผ๐ฐ๐๐๐ฒ๐ฑ: A unit test should be limited to an individual function or method. This makes it easier to identify and fix problems when the test fails.
๐ฏ. ๐๐๐ผ๐น๐ฎ๐๐ฒ ๐๐ผ๐๐ฟ ๐๐ฒ๐๐๐: Make sure each test is independent of all the others. This allows you to run each test individually and in any order.
๐ฐ. ๐ข๐ฟ๐ด๐ฎ๐ป๐ถ๐๐ฒ ๐๐ผ๐๐ฟ ๐๐ฒ๐๐๐ ๐ฏ๐ ๐๐ฒ๐๐ ๐๐๐ฝ๐ฒ: You can organize your tests by the type of object they are testing or the type of test they are. This makes it easier to find and run related tests.
๐ฑ. ๐ง๐ฒ๐๐ ๐ผ๐ป๐ฒ ๐ฐ๐ผ๐ฑ๐ฒ ๐ฝ๐ฎ๐๐ต ๐ฎ๐ ๐ฎ ๐๐ถ๐บ๐ฒ: Each test should verify one specific code path through a method. This makes it easier to understand what is being tested and why a test might fail.
๐ฒ. ๐๐๐ผ๐ถ๐ฑ ๐น๐ผ๐ด๐ถ๐ฐ ๐ถ๐ป ๐๐ฒ๐๐๐: When you put logic into your tests, you risk introducing bugs into your tests. Keep your tests simple.
๐ณ. ๐๐๐ผ๐ถ๐ฑ ๐๐๐ฎ๐๐ถ๐ฐ ๐บ๐ฒ๐๐ต๐ผ๐ฑ๐ ๐ถ๐ป ๐๐ผ๐๐ฟ ๐ฐ๐น๐ฎ๐๐๐ฒ๐ ๐๐ป๐ฑ๐ฒ๐ฟ ๐๐ฒ๐๐: Static methods can't be overridden in subclasses, which makes them difficult to test. Avoid using static methods in the classes you are testing.
๐ด. ๐๐๐ผ๐ถ๐ฑ ๐๐ฒ๐๐๐ถ๐ป๐ด ๐ถ๐บ๐ฝ๐น๐ฒ๐บ๐ฒ๐ป๐๐ฎ๐๐ถ๐ผ๐ป ๐ฑ๐ฒ๐๐ฎ๐ถ๐น๐: Your tests should focus on the behavior of your code, not its implementation. If you test implementation details, your tests can break even if the behavior of your code remains the same.
๐ต. ๐ช๐ฟ๐ถ๐๐ฒ ๐๐ฒ๐๐๐ ๐ณ๐ผ๐ฟ ๐บ๐ฒ๐๐ต๐ผ๐ฑ๐ ๐๐ต๐ฎ๐ ๐ต๐ฎ๐๐ฒ ๐๐ต๐ฒ ๐บ๐ผ๐๐ ๐ถ๐บ๐ฝ๐ฎ๐ฐ๐ ๐ณ๐ถ๐ฟ๐๐: Focus your testing efforts on the methods that impact your application most. This typically includes methods that contain complex logic or interact with external resources.
๐ญ๐ฌ. ๐จ๐๐ฒ ๐๐ต๐ฒ ๐๐๐ ๐ฝ๐ฎ๐๐๐ฒ๐ฟ๐ป: Arrange, Act, Assert is a typical pattern for writing unit tests. The Arrange section of a unit test method initializes objects and sets the data value passed to the method under test. The Act section invokes the method under test with the arranged parameters. The Assert section verifies that the method under test behaves as expected.