繁体   English   中英

XUnit模拟方法,但不返回预期结果

[英]XUnit mocking a method but doesn't return expected result

我在XUnit测试中使用了Moq,但由于某种原因,该模拟无法正常工作。 这是我的单元测试:

 [Fact]
        public async Task SampleUnitTest()
        {
            //Arrange
            var httpClient = new HttpClient(new FakeHttpMessageHandler());
            _mockConstructRequest.Setup(x => x.ConstructRequestString(searchRequestModel))
                                 .Returns("a sample string");
            var service = new LibraryService(_mockConstructRequest.Object);

            //Act
            var response = service.GetResponse(new Request(), httpClient);

            //Assert
            response.Should().BeNull();

        }

         private class FakeHttpMessageHandler : HttpMessageHandler
        {
            public Func<HttpRequestMessage, CancellationToken, HttpResponseMessage> HttpRequestHandler { get; set; } =
            (r, c) =>
                new HttpResponseMessage
                {
                    ReasonPhrase = r.RequestUri.AbsoluteUri,
                    StatusCode = HttpStatusCode.OK
                };


            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                return Task.FromResult(HttpRequestHandler(request, cancellationToken));
            }
        } 

这是实际的代码,我正在尝试测试GetResponse方法。

  public class LibraryService : ILibraryService
 {
    private IConfiguration _configuration;
    private IRequestConstructor _requestContructor;
    public LibraryService (IRequestConstructor requestConstructor)
    {
        _requestConstructor = requestConstructor;
    }

    public async Task<Response> GetResponse(Request request, HttpClient client)
        {

            //construct request
            string requestString = _constructRequestString.ConstructRequestString(request, client);

            return null;
        }
 }

 public class RequestContructor : IRequestContructor
 {
  public string ConstructRequestString(Request request)
        {
            return "a request string";
        }
 }

我试图从单元测试中逐步检查代码,但是当断点在这一行时, requestString变量为null,而它应该返回“样本字符串”。 有人知道为什么吗?

string requestString = _constructRequestString.ConstructRequestString(request, client);

据我所知,您的模拟是错误的:模拟:

_mockConstructRequest.Setup(x => x.ConstructRequestString(searchRequestModel))
                                 .Returns("a sample string");

您正在调用的方法:

_constructRequestString.ConstructRequestString(request, client);

不应该是这样的:

_mockConstructRequest.Setup(x => x.ConstructRequestString(It.IsAny<Request>(),It.IsAny<HttpClient>()))
                                 .Returns("a sample string");

最重要的是:

尝试在构造函数中而不是在每个测试中初始化模拟和“ classUnderTest”,它将在测试之前每次运行,并为您做所有事情。 例如:

public class UnitTestClass{

private readonly ClassUnderTest _classUnderTest;
private readonly Mock<ClassUnderTestDependecy> mockedInstance;

public UnitTestClass {
mockedInstance= new Mock<ClassUnderTestDependecy>();
_classUnderTest= new ClassUnderTest (ClassUnderTestDependecy.Object);
}

}

c# xUnit Moq It.IsAny<object> 没有像预期的那样嘲笑<div id="text_translate"><p>以下是一段代码(简单的 HTTP post 调用),我试图在 Azure 函数中模拟:</p><pre> await httpClient.PostAsync("https://url.com", await File.ReadAllTextAsync(Path.Combine(Environment.GetEnvironmentVariable("APP_DIRECTORY"), "file.json"));</pre><p> 请注意,httpClient.PostAsync() 函数有两个参数:URL 作为字符串,body 作为对象。</p><p> 现在,在我的测试中,我像这样模拟这个 POST 调用:</p><pre> httpClientMock.Setup(s =&gt; s.PostAsync(It.IsAny&lt;string&gt;(), It.IsAny&lt;object&gt;())).ReturnsAsync(mockedHttpResponse);</pre><p> 我期待await File.ReadAllTextAsync(Path.Combine(Environment.GetEnvironmentVariable("APP_DIRECTORY"), "file.json")不会被调用,因为我将它设置为与任何对象一起工作。但是,我的测试用例失败了例外:</p><blockquote><p> 在 System.IO.Path.Combine(String path1, String path2) 处发现 System.ArgumentNullException 消息“Value cannot be null. (Parameter 'path1')”</p></blockquote><p> 当我通过在测试中设置环境变量来提供正确的路径(即使是虚拟路径也不起作用)时,它就起作用了。 但这似乎不是正确的方法,因为单元测试旨在在各种机器上运行,并且每台机器的基本路径都不同。</p></div></object>

[英]c# xUnit Moq It.IsAny<object> not mocking as expected

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 XUnit mocking 一个方法但没有返回正确的结果 使用 Moq 框架模拟方法不会返回预期结果 为什么这段代码没有返回预期的结果? xUnit中是否存在预期的结果属性? 使用Moq的Stubed Unit of Work方法不返回预期的整数 嘲笑不给返回选项 Mocking MongoDb Xunit中的Find、FindAsync等方法 c# xUnit Moq It.IsAny<object> 没有像预期的那样嘲笑<div id="text_translate"><p>以下是一段代码(简单的 HTTP post 调用),我试图在 Azure 函数中模拟:</p><pre> await httpClient.PostAsync("https://url.com", await File.ReadAllTextAsync(Path.Combine(Environment.GetEnvironmentVariable("APP_DIRECTORY"), "file.json"));</pre><p> 请注意,httpClient.PostAsync() 函数有两个参数:URL 作为字符串,body 作为对象。</p><p> 现在,在我的测试中,我像这样模拟这个 POST 调用:</p><pre> httpClientMock.Setup(s =&gt; s.PostAsync(It.IsAny&lt;string&gt;(), It.IsAny&lt;object&gt;())).ReturnsAsync(mockedHttpResponse);</pre><p> 我期待await File.ReadAllTextAsync(Path.Combine(Environment.GetEnvironmentVariable("APP_DIRECTORY"), "file.json")不会被调用,因为我将它设置为与任何对象一起工作。但是,我的测试用例失败了例外:</p><blockquote><p> 在 System.IO.Path.Combine(String path1, String path2) 处发现 System.ArgumentNullException 消息“Value cannot be null. (Parameter 'path1')”</p></blockquote><p> 当我通过在测试中设置环境变量来提供正确的路径(即使是虚拟路径也不起作用)时,它就起作用了。 但这似乎不是正确的方法,因为单元测试旨在在各种机器上运行,并且每台机器的基本路径都不同。</p></div></object> 选择不返回结果 恢复网址未返回预期结果
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM