簡體   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