Moq 模拟单元测试 - 实现将模拟设置 GetAwaiter().GetResult() 代码的代码?

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

以下是有关我们技术开发环境的信息:

  • .NET 6

  • C# 10

  • Microsoft.NET.Test.Sdk”版本 15.5.0

  • 起订量版本 4.18.2

  • Xunit 版本 2.4.1

public interface IBlahClient : IDisposable
{
   Task<IBlahResponse<TResponse>> SendQueryAsync<TResponse>(int 
           invocationNumber, CancellationToken cancellationToken = default);
}

public class BlahClient : IBlahClient
{

    public Task<IBlahResponse<TResponse>> SendQueryAsync<TResponse>( int invocationNumber,  
    CancellationToken cancellationToken = default)
    {
        return …;
    }
}
public class SUTClass
{   
    public bool BlahBlahMethod(IBlahClient blahClient)
    { 
        var resp = blahClient.SendQueryAsync<dynamic>(5, CancellationToken.None).GetAwaiter().GetResult();
        
        // ...

        return …;
    }
}
public class SUTClassTests 
{
    [Fact]
    public void BlahTestMethod()
    {
        TaskCompletionSource< IBlahResponse <dynamic>> taskCompletionSource = new TaskCompletionSource<IBlahResponse<dynamic>>();
        
        taskCompletionSource.SetResult(graphQLResponseMock.Object);
              
        Mock<IBlahClient> blahClientMock = new Mock<IBlahClient>();
                        
        blahClientMock.Setup(c => c.SendQueryAsync<dynamic>( 5, CancellationToken.None))
                       .Returns(taskCompletionSource.Task);
              
        //Please show code that will Mock Setup the . GetAwaiter().GetResult();
    }
}

有人可以告诉我如何实现模拟设置

GetAwaiter().GetResult()
代码的代码吗?

c# unit-testing asynchronous moq synchronous
2个回答
0
投票

有一种模拟异步方法的方法(来自这里):

blahClientMock.Setup(c => c.SendQueryAsync<dynamic>( 5, CancellationToken.None))
    .ReturnsAsync(true);
          

0
投票

Moq 确实提供了几种模拟异步方法的方法

使用
Setup
ReturnsAsync

var blahClientMock = new Mock<IBlahClient>();
blahClientMock
    .Setup(c => c.SendQueryAsync<dynamic>(5, CancellationToken.None))
    .ReturnsAsync(graphQLResponseMock.Object);

Setup
.Result
Returns

一起使用
var blahClientMock = new Mock<IBlahClient>();
blahClientMock
    .Setup(c => c.SendQueryAsync<dynamic>(5, CancellationToken.None).Result)
    .Returns(graphQLResponseMock.Object);
© www.soinside.com 2019 - 2024. All rights reserved.