如何为我尝试但出错的逻辑编写单元测试用例?

问题描述 投票:0回答:1

我尝试为下面的类编写单元测试用例,但它抛出了一条错误消息。

每当调用

GetRoles()
方法时,它都会在
HttpResponseMessage response= ...
行抛出错误。

namespace ApiServices
{
   public class UserServices
   {
        private System.Uri baseAddress = new Uri("http://localhost:62943/api/user/");
        HttpClient client;
        public UserServices()
        {
            client = new HttpClient();
            client.BaseAddress = baseAddress;
        }

        // This method calling api getRoles method and its return list of roles
        public List<Roles> GetRoles()
        {
            List<Roles> roles = new List<API_Project_Models.Roles>();
            HttpResponseMessage response = client.GetAsync(client.BaseAddress + "/getRoles").Result;
            if (response.IsSuccessStatusCode)
            {
                string data = response.Content.ReadAsStringAsync().Result;
                roles = JsonConvert.DeserializeObject<List<Roles>>(data);
            }

            return roles;
        }
    }
}

我试过这个测试用例,但我抛出错误。

public class UserServicesTest
{
    [Fact]
    public void UserServices_GetRoles_Test()
    {
        //Arrange
        var _service= new UserServices();

        //Act
        var data= _service.GetRoles();

        //Assert
        Assert.Null(data);
    }
}

这是错误信息:

System.NotSupportedException:不支持的表达式:x => x.GetRoles() 不可覆盖成员(此处:UserServices.GetRoles)不得用于设置/验证表达式。

c# unit-testing moq xunit dotnet-httpclient
1个回答
-1
投票

这是您可以使用的示例代码

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using ApiServices;
using Moq;
using Xunit;

namespace ApiServices.Tests
{
    public class UserServicesTests
    {
        private readonly UserServices _userServices;
        private readonly Mock<HttpMessageHandler> _httpMessageHandlerMock;
        private readonly HttpClient _httpClient;

        public UserServicesTests()
        {
            _httpMessageHandlerMock = new Mock<HttpMessageHandler>();
            _httpClient = new HttpClient(_httpMessageHandlerMock.Object)
            {
                BaseAddress = new Uri("http://localhost:62943/api/user/")
            };
            _userServices = new UserServices {Client = _httpClient};
        }

        [Fact]
        public async Task GetRoles_ReturnsExpectedRoles()
        {
            // Arrange
            var expectedRoles = new List<Roles>
            {
                new Roles {Id = 1, Name = "Admin"},
                new Roles {Id = 2, Name = "User"}
            };
            var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent("[{\"id\":1,\"name\":\"Admin\"},{\"id\":2,\"name\":\"User\"}]")
            };
            _httpMessageHandlerMock.Protected()
                .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
                .ReturnsAsync(httpResponseMessage);

            // Act
            var result = await _userServices.GetRoles();

            // Assert
            Assert.Equal(expectedRoles.Count, result.Count);
            for (int i = 0; i < expectedRoles.Count; i++)
            {
                Assert.Equal(expectedRoles[i].Id, result[i].Id);
                Assert.Equal(expectedRoles[i].Name, result[i].Name);
            }
        }
    }
}

在这个测试中,我们首先设置了一个mock HttpMessageHandler 来模拟来自服务器的HTTP 响应。然后,我们使用模拟处理程序创建一个 HttpClient 实例,并将其传递给正在测试的 UserServices 实例。

接下来,我们安排调用 GetRoles 方法的预期结果,并设置模拟处理程序以返回包含预期数据的 HTTP 响应。

然后,我们通过调用 GetRoles 方法来执行操作并检索实际结果。

最后,我们通过比较列表中角色的计数和属性来断言实际结果与预期结果相匹配。

© www.soinside.com 2019 - 2024. All rights reserved.