Back to listC#
xUnit - Unit Testing with Moq
Lv.51014@mukitaro0 playsDec 31, 2025
xUnit test class with Moq for mocking. Demonstrates Fact and Theory attributes for unit testing.
preview.csharp
1public class OrderServiceTests2{3 private readonly Mock<IOrderRepository> _mockRepository;4 private readonly Mock<ILogger<OrderService>> _mockLogger;5 private readonly OrderService _service;6 7 public OrderServiceTests()8 {9 _mockRepository = new Mock<IOrderRepository>();10 _mockLogger = new Mock<ILogger<OrderService>>();11 _service = new OrderService(_mockRepository.Object, _mockLogger.Object);12 }13 14 [Fact]15 public async Task GetOrderAsync_ReturnsOrder_WhenExists()16 {17 var order = new Order { Id = 1, Total = 100m };18 _mockRepository.Setup(r => r.GetByIdAsync(1)).ReturnsAsync(order);19 20 var result = await _service.GetOrderAsync(1);21 22 Assert.NotNull(result);23 Assert.Equal(100m, result.Total);24 }25 26 [Theory]27 [InlineData(0)]28 [InlineData(-1)]29 public async Task GetOrderAsync_ThrowsException_WhenInvalidId(int id)30 {31 await Assert.ThrowsAsync<ArgumentException>(() => _service.GetOrderAsync(id));32 }33}Custom problems are not included in rankings