Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีทดสอบ C# ASP.NET WebAPI

การทดสอบ Web API เกี่ยวข้องกับการส่ง Request และรับ Response มีหลายวิธีในการทดสอบ Web API ที่นี่เราจะทดสอบโดยใช้ Postman และ Swagger ให้สร้าง StudentController ดังนี้

Student Model

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

Student Controller

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

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

ทดสอบด้วย Swagger

Swagger เป็น Specification สำหรับ Document REST API ระบุ Format (URL, Method, Representation) สำหรับอธิบาย REST Web Services Methods, Parameters, และ Models Description ผูกติดกับ Server Code อย่างแน่นอน ทำให้ APIs และ Documentation ซิงค์กัน

  1. ใน Application ใช้ Manage NuGet Packages ติดตั้ง Swagger (Swashbuckle)
  2. Run Web API Project และเข้า URL: swagger/ui/index
  3. Swagger จะ List Controller และ Action Methods อัตโนมัติ
  4. Expand Controller และทดสอบ Endpoint ด้วย Request

Get All Students Request/Response

วิธีทดสอบ C# ASP.NET WebAPI

วิธีทดสอบ C# ASP.NET WebAPI

Get Student by Id Request/Response

วิธีทดสอบ C# ASP.NET WebAPI

วิธีทดสอบ C# ASP.NET WebAPI

ทดสอบด้วย Postman

Postman เป็น API Client ยอดนิยม ทำให้ Developers สร้าง แชร์ ทดสอบ และ Document APIs ได้ง่าย โดยการสร้างและบันทึก HTTP/s Requests แบบ Simple และ Complex รวมถึงอ่าน Response ผลลัพธ์ - ทำงานมีประสิทธิภาพมากขึ้นและน่าเบื่อน้อยลง Postman ติดตั้งเป็น Application หรือใช้ผ่าน Browser ได้

วิธีทดสอบ C# ASP.NET WebAPI

Get All Students Request และ Response

วิธีทดสอบ C# ASP.NET WebAPI

Get Student by Id Request และ Response

วิธีทดสอบ C# ASP.NET WebAPI

วิธีทดสอบอื่นๆ

1. Unit Testing (xUnit/NUnit + Moq)


public class StudentControllerTests {
    private readonly StudentController _controller;
    private readonly Mock _mockService;
    
    public StudentControllerTests() {
        _mockService = new Mock();
        _controller = new StudentController(_mockService.Object);
    }
    
    [Fact]
    public async Task Get_ReturnsAllStudents() {
        // Arrange
        var students = new List { new Student { Id = 1, Name = "Test" } };
        _mockService.Setup(s => s.GetAllAsync()).ReturnsAsync(students);
        
        // Act
        var result = await _controller.Get();
        
        // Assert
        var okResult = Assert.IsType(result.Result);
        var returnedStudents = Assert.IsAssignableFrom>(okResult.Value);
        Assert.Single(returnedStudents);
    }
}

2. Integration Testing (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. Load Testing (NBomber, k6, JMeter)

สำหรับทดสอบ Performance และ Load