0. What Happened to Moq?
About two days ago, it was revealed that Moq: https://github.com/moq/moq, the most famous unit testing mock library for .NET, has included a .NET analyzer since version 4.20. When you build a project that uses Moq, this analyzer scans your local git configuration, extracts your local email address, and sends it via the Moq author’s other project, SponsorLink, to a service hosted on Azure to check if you are a Sponsor. Related discussions can be found in this Reddit post: https://www.reddit.com/r/dotnet/comments/15ljdcc/does_moq_in_its_latest_version_extract_and_send/ and this GitHub issue: https://github.com/moq/moq/issues/1372.
This incident caused a huge uproar in the international .NET community. Some developers strongly condemned this behavior, while others defended Moq’s original author, thanking him for consistently maintaining the project despite receiving only a pitiful amount of sponsorship.
One netizen condemned the author and argued that Microsoft should blacklist Moq:
![]() |
|---|
| Figure 1 - Condemning the author and arguing that Microsoft should blacklist Moq |
Some netizens are also complaining about the above item:
![]() |
|---|
| Figure 2 - Is Microsoft always wrong? |
The two sentences above can be translated as follows:
- Did Microsoft really not blacklist the new package that the community dislikes? Has Microsoft stopped caring about the .NET ecosystem!
- Did Microsoft actually blacklist the new package that the community dislikes? This proves Microsoft's evil nature!
Some users emphasized that we should take seriously the fact that open-source project maintainers gain nothing from this, given that many users have neither sponsored this library nor contributed to it:
![]() |
|---|
| Figure 3 - Valuing the fact that open-source project maintainers gain nothing |
A netizen has released CleanMoq, which does not include the controversial feature:
![]() |
|---|
| Figure 4 - CleanMoq without the disputed feature |
I don't typically use Moq; I use NSubstitute instead. This incident did not affect me.
What truly caught my interest is that this event did not spark as widespread a discussion within the domestic community as one might expect. I only briefly discussed it with friends in a highly technical .NET WeChat group. Based on my experience, the average developer in China (myself included) often struggles just to secure a position at a small or medium-sized company. Such companies generally do not have a habit of writing unit tests and therefore do not use mocking libraries like Moq or NSubstitute. While I understand that companies have development cost considerations, I still view this as a tragedy and a vicious cycle. In my opinion, spending extra time writing tests actually saves the company money in the long run, but many companies and teams either fail to recognize this or face extremely tight development deadlines, leaving them with no spare time. As a result, no one writes unit tests, no one learns how to write them, and the quality of the software continues to decline.
1. What is Moq used for?
[Fact] // 表示这是一个单元测试方法
public void GetStudentById_ShouldReturnCorrectStudent_WhenIdExists()
{
// Arrange(准备阶段)
var mockStudentRepository = new Mock<IRepository<Student>>(); // 创建一个 Mock 对象,模拟 IRepository<Student> 接口的行为
var expectedStudent = new Student { Id = 1, Name = "Alice", Age = 18 }; // 创建一个期望返回的学生对象
mockStudentRepository.Setup(repo => repo.GetById(1)).Returns(expectedStudent); // 设置当调用 GetById 方法,并传入参数为 1 时,返回期望的学生对象
var studentService = new StudentService(mockStudentRepository.Object); // 创建一个 StudentService 对象,并传入 Mock 对象的 Object 属性,作为依赖注入
// Act(执行阶段)
var actualStudent = studentService.GetStudentById(1); // 调用 StudentService 的 GetStudentById 方法,并传入参数为 1
// Assert(断言阶段)
Assert.Equal(expectedStudent, actualStudent); // 断言期望的学生对象和实际返回的学生对象相等
mockStudentRepository.Verify(repo => repo.GetById(1), Times.Once()); // 验证 Mock 对象的 GetById 方法被调用了一次,并传入了参数为 1
}
Let's be clear on one point first: unit tests are written by developers, not by testers.
The above is a unit test code snippet that uses Moq. Unit tests should not depend on a physical database, so we use var mockStudentRepository = new Mock<IRepository<Student>>(); to create a simulated studentRepository. Then, we use mockStudentRepository.Setup(repo => repo.GetById(1)).Returns(expectedStudent); to configure the mock so that when the studentRepository.GetById method is called with the argument 1, it returns the previously constructed expectedStudent object. This ensures that our calls to methods in the Repository do not affect the actual data in the real database; instead, they return the fake data we have configured.
You might think we are deceiving ourselves, but in reality, this method is testing the GetStudentById method of StudentService, not the methods of StudentRepository. Therefore, assuming the return value of the Repository is necessary. Otherwise, if we requested the real database and it happened that there was no student with Id 1, would we have to modify our unit test code every time we ran the tests? Unit tests are run very frequently, during development, testing, and in CI/CD pipelines. Modifying the code each time would be highly costly.
As for the repository layer, I do not write any business logic in it, so I generally do not perform unit testing on it, as it is not meaningful. If you really want to test it, integration testing will help you do so.
2. What is Unit Testing
Unit testing is a software development practice that helps developers verify whether code functionality is correct and meets the expected requirements. There are many benefits to unit testing, such as improving code quality, reducing errors, increasing readability, facilitating refactoring, and boosting development efficiency. Conversely, not writing unit tests can significantly harm code maintainability, project health, and the development of future new requirements.
The negative impacts of not writing unit tests include the following aspects:
- Code Maintainability: Code without unit tests often lacks structure and standardization, making it difficult to understand and modify. If hidden errors or logical issues exist in the code, without unit tests to detect and fix them, the code becomes increasingly fragile and unreliable. Such code is a nightmare for maintainers, as they cannot be sure whether modifying one part of the code will affect functionality elsewhere.
- Project Health: Projects without unit tests often lack confidence and a sense of security. Unexpected issues or failures may occur every time a new version is released or deployed to the production environment. Such projects pose a risk to clients and users, as they do not know when they might encounter system crashes or data loss.
- Development of Future New Requirements: Developers who do not write unit tests often face greater pressure and challenges. When a project requires adding new features or modifying existing ones, they have no way to quickly verify whether the code is correct or ensure that no new errors are introduced. Such developers become a bottleneck for requirement changes, as they need to spend more time and effort on debugging and testing.
Not writing unit tests can also create a vicious cycle:
- Not writing unit tests leads to low code quality; low code quality leads to difficulty in maintenance; difficulty in maintenance leads to low development efficiency; low development efficiency leads to time pressure; time pressure leads to not writing unit tests.
- Not writing unit tests leads to high project risk; high project risk leads to user dissatisfaction; user dissatisfaction leads to frequent requirement changes; frequent requirement changes lead to increased development complexity; increased development complexity leads to not writing unit tests.
3. Summary
![]() |
|---|
| Figure 5 - The Vicious Cycle of Not Performing Unit Testing |
This is a meme related to testing (unit tests, integration tests, etc.). Here is a brief translation:
- Skip tests because time is tight => 2. Don't refactor, because there are no tests, and refactoring is too risky => 3. Developing new features takes longer because the code is terrible => 4. Delivery is delayed, and development speed needs to be increased => 1. Skip tests because time is tight
I hope companies and developers in China will place more importance on unit testing! If I have time later, I will write some simple introductory tutorials on unit testing. It is not actually that difficult.
One last ad: 😁 I am currently looking for new job opportunities. Ideally, a role with good work-life balance, based in Qingdao. Remote work opportunities are also welcome. If you are interested, please contact me via email: [email protected]. Thank you!





很多公司不写单元测试并不是单元测试难写,而是写出“可测试的代码”这件事本身其实非常有挑战性。例如这些代码都是和其他复杂的微服务平台产生了千奇百怪的依赖能编译过去都是万幸了,而mock太多又失去了写测试的意义,到最后成了玄学项目,不如直接docker-compose一下人肉测试。。。