Testing is often what separates a hobbyist from a professional engineer. In an enterprise environment, “it works on my machine” isn’t enough; you need an automated suite of tests to prove that a new change doesn’t break existing features (this is called Regression Testing).
To build a stable system, you should follow the Testing Pyramid strategy:
A Unit Test focuses on the smallest possible “unit” of code (usually a single method) in isolation.
These are the two most popular testing frameworks in the .NET ecosystem.
[Fact] attribute for normal tests and [Theory] for data-driven tests.[Test] and [TestCase]. It is still very common in legacy enterprise projects.Since unit tests must be isolated, how do you test a UserService that requires a database? You Mock it.
Integration tests verify that different parts of your application work together correctly.
TDD is a workflow where you write the test before the code.
Why use TDD? It forces you to think about the “Requirements” and “Interface” of your code before you get bogged down in the implementation.
C#
[Fact]
public void CalculateDiscount_ShouldReturnHalfPrice_WhenUserIsStudent() {
// Arrange
var mockSvc = new Mock<IUserTypeService>();
mockSvc.Setup(s => s.GetStatus(1)).Returns("Student");
var calculator = new DiscountCalculator(mockSvc.Object);
// Act
var result = calculator.GetTotal(100, 1); // $100 price for User #1
// Assert
Assert.Equal(50, result);
}