Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Cách test C# ASP.NET WebAPI

Testing WebApi bao gồm gửi request và nhận response. Có vài cách test WebApi. Ở đây test dùng Postman và Swagger. Tạo StudentController như dưới.

Student Model

namespace DemoWebApplication.Models { 
    public class Student { 
        public int Id { get; set; } 
        public string Name { get; set; } 
    } 
}

Student Controller

Ví dụ

using DemoWebApplication.Models; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web.Http; 

namespace DemoWebApplication.Controllers { 
    public class StudentController : ApiController { 
        List<Student> students = new List<Student> { 
            new Student { Id = 1, Name = "Mark" }, 
            new Student { Id = 2, Name = "John" } 
        }; 
        
        public IEnumerable<Student> Get() { 
            return students; 
        } 
        
        public Student Get(int id) { 
            var studentForId = students.FirstOrDefault(x => x.Id == id); 
            return studentForId; 
        } 
    } 
}

Test dùng Swagger

Swagger là specification cho documenting REST API. Nó chỉ định format (URL, method, representation) để mô tả REST web services. Methods, parameters, models description được tích hợp chặt vào server code, duy trì synchronization giữa APIs và documentation.

Trong ứng dụng, dùng Manage Nuget packages cài swagger.

Chạy WebApi project và nhập swagger/ui/index trong URL.

Swagger tự động list controller và action method. Có thể expand controller và test endpoint với request.

Get All Students Request/Response

Swagger UI hiển thị danh sách endpoints, cho phép nhập parameters và Execute để xem response JSON/XML.

Get Student by Id Request/Response

Test endpoint GET api/student/{id} với parameter id.

Test dùng Postman

Postman là API client phổ biến giúp dev tạo, share, test, document APIs. Cho phép tạo và lưu simple và complex HTTP/s requests, đọc responses. Kết quả: công việc hiệu quả hơn, ít tẻ nhạt hơn. Postman cài đặt như app hoặc dùng qua browser.

Get All Students Request/Response

POSTMAN UI hiển thị GET request đến /api/student trả về JSON array.

Get Student by Id Request/Response

GET request đến /api/student/2 trả về single student object.

Các cách test khác

1. Unit Test (xUnit/NUnit + Moq)

[Fact]
public async Task Get_ReturnsAllStudents() {
    // Arrange
    var mockRepo = new Mock();
    mockRepo.Setup(r => r.GetAll()).ReturnsAsync(new List { 
        new Student { Id = 1, Name = "Mark" } 
    });
    var controller = new StudentController(mockRepo.Object);
    
    // Act
    var result = await controller.Get();
    
    // Assert
    var okResult = Assert.IsType(result.Result);
    var students = Assert.IsAssignableFrom>(okResult.Value);
    Assert.Single(students);
}

2. Integration Test (WebApplicationFactory - ASP.NET Core)

public class StudentApiTests : IClassFixture> {
    private readonly HttpClient _client;
    
    public StudentApiTests(WebApplicationFactory factory) {
        _client = factory.CreateClient();
    }
    
    [Fact]
    public async Task GetStudents_ReturnsSuccess() {
        var response = await _client.GetAsync("/api/student");
        response.EnsureSuccessStatusCode();
        
        var content = await response.Content.ReadAsStringAsync();
        var students = JsonSerializer.Deserialize>(content);
        Assert.NotEmpty(students);
    }
}

3. Test với http-repl (CLI tool)

dotnet tool install -g Microsoft.dotnet-httprepl
httprepl https://localhost:5001
# Interactive shell: ls, cd api, get student, post student -c "{\"name\":\"Test\"}"

4. Automated API Testing (RestSharp / Flurl)

// Flurl.Http
var students = await "https://api.example.com"
    .AppendPathSegment("student")
    .GetJsonAsync>();

Best Practices

  • Test happy path + edge cases (404, 400, 500)
  • Test validation (invalid input, missing required fields)
  • Test authentication/authorization
  • Test pagination, filtering, sorting
  • Mock external dependencies trong unit test
  • Dùng TestContainers cho integration test với DB thật