Answer the question
In order to leave comments, you need to log in
How to write correct Unit/Integration tests?
The story is completely fictitious and is presented only to use the narrative style.
Let's take the simplest example of a calculator from the Internet, which usually demonstrates how to write unit tests and the TDD approach.
So I have some kind of system that calculates the salary of employees.
Code example:
public class SalaryCalculationService {
private readonly Calculator_calculator;
public SalaryCalculationService(Calculator calculator) {
_calculator = calculator;
}
public int CalculateSalary(Employee employee) {
//logic that uses calculator goes here
}
}
public class SalaryCalculationServiceTest {
[TestMethod]
public void ShouldCalculateSalaryCorrectly() {
//Arrange
var calculatorMock = new Mock<Calculator>().Sum().Returns((a, b) => Math.Sum(a, b)); //Мы абстрагируемся от конкретной реализации ICalculator
var calculationService = new SalaryCalculationService(calculatorMock.Object);
var employee = new Employee();
employee.SetWorkingDays(10);
//Act
var result = calculationService.CalculateSalary(employee);
//Assert
Assert.Equals(40, result);
}
}
public class Calculator: ICalculator {
public int Sum(int a, int b) {
return a + b;
}
}
public class CalculatorTest {
public void ShouldCalculateSumCorrectly() {
//Arrange
var calculator = new Calculator();
//Act
var result = calculator.Sum(2, 2);
//Assert
Assert.Equals(4, result);
}
}
Answer the question
In order to leave comments, you need to log in
that the less we mock, the more bugs our tests catch.
> how to
choose the right balance between ease of writing, speed of execution, and coverage.
The coolest in terms of coverage are end to end tests, in which you raise the entire infrastructure and make http requests to the service under test.
But they are quite slow, they require a complex infrastructure, and when writing, you need to think about how to make sure that the tests do not affect each other.
And now about my experience:
There was a project without tests, but at the same time it was clear that it needed to be completely refactored, and even rewritten a couple of modules from scratch, there was also a move from one subd to another. But there was documentation for all endpoints.
In this case, the approach with writing tests for HTTP was ideal.
Then I wrote them in Sharpe, but now I know that in Postman you can not only make requests, but also write tests that you can then run from the console.
And now for the rest:
We write everything in TDD, all tests are green, but bugs still appear.
one of our services that uses a database sends a SQL query with a syntax error
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question