source: update Base rule Agent

This commit is contained in:
2026-03-09 18:01:01 +07:00
parent 3003a0ff0b
commit fd9f558fa1
22 changed files with 501 additions and 1426 deletions

View File

@@ -1,22 +1,22 @@
---
name: GenerateArchitectureTest
description: Hướng dẫn tạo Architecture Test sử dụng NetArchTest.Rules để bảo vệ kiến trúc Clean Architecture.
description: Guide to creating an Architecture Test using NetArchTest.Rules to protect the Clean Architecture structure.
---
# GenerateArchitectureTest Skill
Khi user yêu cầu kiểm tra hoặc khởi tạo **Architecture Test**, bạn cần sử dụng thư viện `NetArchTest.Rules` để sinh luận kiểm điểm nhằm bảo vệ chặt chẽ cấu trúc "Clean Architecture" của dự án.
When a user requests to verify or create an **Architecture Test**, you must use the `NetArchTest.Rules` library to generate tests that strictly protect the project's "Clean Architecture" boundaries.
## Mục đích
- Ngăn chặn Dev code ẩu, import sai library/module giữa các tầng (layer).
- Nếu vi phạm (VD: import Entity Framework vào tầng Domain), bài test này sẽ báo ĐỎ ngay lập tức lúc build code. Bằng chứng thép giúp kiến trúc được bảo vệ tuyệt đối!
## Purpose
- Prevent developers from writing sloppy code by incorrectly importing libraries/modules across layers.
- If a violation occurs (e.g., importing Entity Framework into the Domain layer), this test will immediately turn RED during the build process. It acts as solid proof to ensure the architecture is fully protected!
## Hướng dẫn viết Test Rules
## Writing Test Rules Guide
Bạn cần viết các test method (ng `[Fact]` với xUnit hoặc NUnit) sử dụng Fluent API của `NetArchTest.Rules`. Dưới đây là các luật phổ biến bắt buộc:
You need to write test methods (using `[Fact]` with xUnit or NUnit) that utilize the Fluent API of `NetArchTest.Rules`. Below are the mandatory common rules:
1. **Domain Layer Rules (Luật tầng Domain):**
- Domain không được phụ thuộc vào bất cứ thứ gì từ Infrastructure, Application hay WebAPI.
1. **Domain Layer Rules:**
- The Domain must not depend on anything from Infrastructure, Application, or WebAPI.
```csharp
[Fact]
public void DomainLayer_ShouldNot_HaveDependencyOn_OtherLayers()
@@ -34,16 +34,16 @@ Bạn cần viết các test method (dùng `[Fact]` với xUnit hoặc NUnit) s
}
```
2. **Application Layer Rules (Luật tầng Application):**
- Application Layer chỉ được phép giao tiếp với Domain, KHÔNG ĐƯỢC có dependency vào `Infrastructure` hoặc `WebAPI`.
2. **Application Layer Rules:**
- The Application Layer is only allowed to communicate with the Domain. It MUST NOT have dependencies on `Infrastructure` or `WebAPI`.
3. **Controller Rules (Luật đặt tên/vị trí API):**
- Controller bắt buộc phải kế thừa class BaseAPIController, và có hậu tố là "Controller".
- Không được phép truy vấn Database trực tiếp từ Controller (ngăn không cho Inject `DbContext` hay `IRepository` vào Controller, kiểm duyệt dependencies của Constructor).
3. **Controller Rules (Naming/API Location):**
- Controllers must inherit from the BaseAPIController class and have the suffix "Controller".
- Direct database queries from the Controller are strictly prohibited (prevent the injection of `DbContext` or `IRepository` into the Controller; verify Constructor dependencies).
4. **Handler Rules (CQRS):**
- Các Handler xử lý logic phải implements interface `IRequestHandler` và kết thúc bằng `CommandHandler` hoặc `QueryHandler`. Nó chỉ nằm ở Application Layer.
- Business logic Handlers must implement the `IRequestHandler` interface and end with `CommandHandler` or `QueryHandler`. They must solely reside in the Application Layer.
## Định dạng file đầu ra
- **Đường dẫn:** Chứa trong test project như `tests/MyNewProjectName.ArchitectureTests/`.
- **Tên file:** Thường đặt tên theo phạm vi test như `LayerTests.cs`, `DesignConventionTests.cs`, `NamingRulesTests.cs`, v.v.
## Output File Format
- **Path:** Placed within the test project, e.g., `tests/MyNewProjectName.ArchitectureTests/`.
- **File Name:** Usually named after the test scope, such as `LayerTests.cs`, `DesignConventionTests.cs`, `NamingRulesTests.cs`, etc.

View File

@@ -1,34 +1,34 @@
---
name: GenerateIntegrationTest
description: Hướng dẫn to Integration Test (người thật việc thật) sử dụng WebApplicationFactory Testcontainers.
description: Guide to creating Integration Tests (end-to-end) using WebApplicationFactory and Testcontainers.
---
# GenerateIntegrationTest Skill
Khi user yêu cầu tạo **Integration Test** để kiểm tra API endpoint từ đầu đến cuối, bạn cần sinh ra code theo hướng dẫn sau:
When a user requests to create an **Integration Test** to verify API endpoints from start to finish, you need to generate the code according to the following guidelines:
## Mục đích
- Test xem các mảnh ghép lắp vào ghép với nhau có chạy đúng không.
- Flow: Client gọi API -> Middleware -> Controller -> CQRS Handler/Service -> Ghi/Đọc Database thật.
## Purpose
- Test whether the assembled components work correctly together.
- Flow: Client calls API -> Middleware -> Controller -> CQRS Handler/Service -> Read/Write to a real Database.
## Hướng dẫn thực hiện
## Implementation Guide
1. **Setup WebApplicationFactory:**
- Tự động setup `WebApplicationFactory<Program>` (to một test server ngay trong RAM của .NET).
- Override cấu hình ứng dụng nếu cần thiết (ví dụ thay đổi ConnectionString trỏ sang test container).
- Automatically setup `WebApplicationFactory<Program>` (to create an in-memory test server in .NET).
- Override application configurations if necessary (e.g., changing the ConnectionString to point to a test container).
2. **Setup Testcontainers (Real Database):**
- Sử dụng thư viện `Testcontainers` (hoặc cấu hình tương tự) để tự động spin up một Docker container chứa Database thật (ví dụ: PostgreSQL, SQL Server).
- Đảm bảo database container này được start trước khi chạy test và tự động xóa (dispose) sau khi test xong. Tránh dùng SQLite in-memory vì hay bị lỗi vặt và không tương đương với database production.
- Use the `Testcontainers` library (or similar configuration) to automatically spin up a Docker container containing a real Database (e.g., PostgreSQL, SQL Server).
- Ensure this database container starts before the tests run and is automatically disposed of after the tests complete. Avoid using in-memory SQLite because it often causes minor bugs and does not accurately mimic a production database.
3. **Viết kịch bản Test gọi API (Arrange - Act - Assert):**
- Tạo đối tượng `HttpClient` từ `WebApplicationFactory.CreateClient()`.
- **Arrange:** Chuẩn bị payload data dạng JSON objects hoặc tạo trước data base records nếu là API GET/PUT/DELETE.
- **Act:** Gọi thẳng vào API endpoint tương ứng bằng code. VD: `await client.PostAsJsonAsync("/api/v1/samples", payload);`.
- **Assert:** Kiểm tra kết quả trả về:
- Check HTTP Status: có phải `200 OK` hay `400 Bad Request` không.
- Deserialize response body để check chính xác object.
- (Tùy chọn) Query thẳng vào database container xem bản ghi đã được sinh ra/cập nhật thật chưa.
3. **Write API Test Scenarios (Arrange - Act - Assert):**
- Create an `HttpClient` object from `WebApplicationFactory.CreateClient()`.
- **Arrange:** Prepare payload data as JSON objects or prepopulate database records for GET/PUT/DELETE APIs.
- **Act:** Call the corresponding API endpoint directly via code. E.g.: `await client.PostAsJsonAsync("/api/v1/samples", payload);`.
- **Assert:** Verify the returned results:
- Check HTTP Status: is it `200 OK` or `400 Bad Request`?
- Deserialize the response body to check the exact object data.
- (Optional) Query the database container directly to confirm the record was actually created/updated.
## Định dạng file đầu ra
- **Đường dẫn:** Chứa trong project test tương ứng như `tests/MyNewProjectName.IntegrationTests/Controllers/...`.
- **Tên file:** `[ControllerName]Tests.cs` (ví dụ: `OrdersControllerTests.cs`).
## Output File Format
- **Path:** Placed in the corresponding test project, such as `tests/MyNewProjectName.IntegrationTests/Controllers/...`.
- **File Name:** `[ControllerName]Tests.cs` (e.g., `OrdersControllerTests.cs`).

View File

@@ -1,32 +1,32 @@
---
name: GenerateUnitTest
description: Hướng dẫn to Unit Test cô lập (tốc độ cao) sử dụng Mocking (Moq hoặc NSubstitute).
description: Guide to creating isolated Unit Tests (high speed) using Mocking (Moq or NSubstitute).
---
# GenerateUnitTest Skill
Khi user yêu cầu tạo **Unit Test** cho một class/method, bạn cần tuân thủ các nguyên tắc sau để sinh ra code test:
When a user requests a **Unit Test** for a class/method, you must adhere to the following principles to generate the test code:
## Mục đích
- Chỉ test duy nhất 1 class/method.
- Bỏ qua hoàn toàn Database thật, Redis hay HTTP.
- Tốc độ chạy cực nhanh.
## Purpose
- Test solely one class/method in isolation.
- Completely ignore real Databases, Redis, or HTTP calls.
- Extremely fast execution speed.
## 1. Với CQRS Handlers hoặc Services
- **Nhận diện Dependencies:** Tự động nhận diện các Interface (ví dụ: `IRepository`, `IUnitOfWork`, `ILogger`, `IMediator`) được inject vào constructor.
- **Tạo Mock Object:** Sử dụng thư viện Mocking (như `Moq` hoặc `NSubstitute`) để tạo instance giả của các Interface này.
- **Kịch bản Test (Arrange - Act - Assert):**
- **Arrange:** Cấp data giả (Mock data) cho các hàm của Interface.
- **Act:** Gọi hàm thực thi (ví dụ `Handle()` của CQRS hoặc các method của Service).
- **Assert:** Kiểm tra kết quả trả về, HOẶC verify xem một method của Mock object có được gọi đúng số lần không (ví dụ kiểm tra xem `_repository.AddAsync()` có được gọi không), HOẶC kiểm tra xem nó có ném ra `ValidationException` khi input sai không.
## 1. For CQRS Handlers or Services
- **Identify Dependencies:** Automatically identify the Interfaces (e.g., `IRepository`, `IUnitOfWork`, `ILogger`, `IMediator`) injected into the constructor.
- **Create Mock Objects:** Use a Mocking library (like `Moq` or `NSubstitute`) to create fake instances of these Interfaces.
- **Test Scenario (Arrange - Act - Assert):**
- **Arrange:** Provide fake data (Mock data) for the Interface methods.
- **Act:** Call the method being executed (e.g., `Handle()` in CQRS or Service methods).
- **Assert:** Check the returned result, OR verify if a Mock object's method was called the correct number of times (e.g., checking if `_repository.AddAsync()` was called), OR verify if it throws a `ValidationException` given invalid input.
## 2. Với Domain Entities
- **Mục tiêu:** Kiểm tra các logic kinh doanh, tính toán nội bộ của Entity.
- **Kịch bản:**
- Khởi tạo Entity với các trạng thái cụ thể.
- Gọi method thay đổi trạng thái hoặc tính toán (ví dụ: `Order.CalculateTotal()`).
- Kiểm tra xem giá trị biến đổi có đúng với quy tắc nghiệp vụ không (ví dụ: `Total` phải bằng `Price * Quantity`).
## 2. For Domain Entities
- **Goal:** Verify internal business logic and calculations of the Entity.
- **Scenario:**
- Initialize the Entity with specific states.
- Call a method that alters the state or performs a calculation (e.g., `Order.CalculateTotal()`).
- Verify if the modified value adheres to business rules (e.g., `Total` must equal `Price * Quantity`).
## Định dạng file đầu ra
- **Đường dẫn:** Đặt trong project `tests/MyNewProjectName.UnitTests/...` (tương ứng với thư mục gốc của class bị test).
- **Tên file:** `[ClassName]Tests.cs` (ví dụ: `CreateOrderCommandHandlerTests.cs`).
## Output File Format
- **Path:** Placed in the `tests/MyNewProjectName.UnitTests/...` project (corresponding to the tested class's root directory).
- **File Name:** `[ClassName]Tests.cs` (e.g., `CreateOrderCommandHandlerTests.cs`).