ArchicionadoArchicionado

Unit Testing

EXPERT
This item has not been updated recently. Check its ring classification to assess its current relevance.
Adopt

Streamline test cases by following the F.I.R.S.T principle (Fast, Isolated, Repeatable, Self-validating, Timely) and proper taxonomy such as System Under Test (SUT) and the Arrange-Act-Assert (AAA) pattern. Train teams on advanced mocking frameworks like Moq to create flexible and maintainable tests. Leverage AutoFixture to automate test data generation, reducing boilerplate code and enhancing test readability. Adopt Data-Driven Testing (DDT) to efficiently validate multiple input scenarios, ensuring comprehensive coverage with minimal effort.

[Theory]
[InlineData(194, 107, 37, "#C26B25")]
[InlineData(66, 138, 245, "#428AF5")]
public void Mapper(int r, int g, int b, string hex)
{
    var (sut, source, expected) = Arrange();    // ARRANGE
    var res = sut.Convert(source);              // ACT
    Assert.Equal(expected, res);                // ASSERT

    (Sut sut, Color1 color, Color2 color) Arrange()
    {
        // Do complex or verbose stuff eg:
        // Create SUT
        // Create C1 from hex
        // Create C2 from {r,g,b}
        return (s, c1, c2);
    }
}
Adopt

Testing provides several key benefits:

  • Fail-fast strategy by exercising small units of code
  • Easier integration by building on validated blocks
  • Regression protection through guard clauses
  • Living documentation that evolves with the code
[Theory]
[InlineData(4, 2, 2)]
[InlineData(15, 3, 5)]
public void DivideWorks(int a, int b, int expected)
{
   var calculator = new Calculator();
   Assert.Equal(expected, sut.Divide(a, b)); 
}


[Fact]
public void DivideByZeroThrows() 
{
   var calculator = new Calculator();
   Assert.Throws<DivideByZeroException>(() => sut.Divide(50));
}
Assess

Discover the joy of testing! Testing is not just a practice; it's a mindset that transforms how we build software. By embracing testing, we ensure our code is reliable, maintainable, and robust.

public void DivideWorks()
{     
   var calculator = new Calculator();
   Assert.Equal(5, sut.Divide(15, 3)); 
}