【问题标题】:Unit Testing a Service with Moq & xUnit使用 Moq 和 xUnit 对服务进行单元测试
【发布时间】:2019-01-13 02:31:11
【问题描述】:

抱歉,这可能是一个非常业余的问题,但我很难理解如何正确使用起订量。作为一个整体,我对单元测试很陌生,但我想我开始掌握它。

所以这是我的问题...我在下面有这段代码的 sn-p,它在 Visual Studio 中使用 TestServer 进行单元测试...我正在尝试模拟 IGamesByPublisher 以便我的测试不依赖于存储库中的数据(或者模拟GamesByPublisher 会更好吗?...或者我需要两者都做吗?)

public static TestServerWithRepositoryService => new TestServer(services =>
{
    services.AddScoped<IGamesByPublisher, GamesByPublisher(); 
}).AddAuthorization("fake.account", null);


[Fact] // 200 - Response, Happy Path
public async Task GamesByPublisher_GamesByPublisherLookup_ValidRequestData_Produces200()
{

    // Arrange
    var server = ServerWithRepositoryService;

    // Act
    var response = await server.GetAsync(Uri);

    // Assert
    Assert.NotNull(response);
    Assert.Equal(HttpStatusCode.OK, response.StatusCode);

}

这里是IGamesByPublisher

public interface IGamesByPublisher interface.
{
    Task<IEnumerable<Publisher>> Execute(GamesByPublisherQueryOptions options);
    }
}

我试过了

public static TestServerWithRepositoryService => new TestServer(services =>
{
    services.AddScoped<Mock<IGamesByPublisher>, Mock<GamesByPublisher>>(); 
}).AddAuthorization("fake.account", null);

然后我尝试了

// Not exactly what I attempted, but that code is long gone... 
var mock = new Mock<IGamesByPublisher >();
var foo = new GamesByPublisherQueryOptions();
mock.Setup(x => x.Execute(foo)).Returns(true);

我并没有真正找到关于使用 Moq 的出色文档,只是 GitHub 上的快速入门指南,我不知道如何应用(可能是我自己的经验水平有问题......)。

我显然错过了使用 Moq 的一些基础知识...

【问题讨论】:

    标签: c# unit-testing moq xunit


    【解决方案1】:

    你很亲密。

    public static TestServerWithRepositoryService => new TestServer(services => {
        var mock = new Mock<IGamesByPublisher>();
    
        var publishers = new List<Publisher>() {
            //...populate as needed
        };
    
        mock
            .Setup(_ => _.Execute(It.IsAny<GamesByPublisherQueryOptions>()))
            .ReturnsAsync(() => publishers);
        services.RemoveAll<IGamesByPublisher>();
        services.AddScoped<IGamesByPublisher>(sp => mock.Object); 
    }).AddAuthorization("fake.account", null);
    

    上面创建了模拟,设置了它的预期行为,以在任何时候用GamesByPublisherQueryOptions 调用Execute 时返回一个发布者列表。

    然后它会删除所需接口的所有注册以避免冲突,然后在请求解析接口时注册服务以返回模拟。

    【讨论】:

    • 谢谢!我在 Return(true) 上遇到错误;我的猜测是这应该是布尔值以外的其他东西?删除注册的好主意!错误:CS1503 参数 1:无法从 'bool' 转换为 'System.Threading.Tasks.Task>' Project.WebApi.Test
    • @TravisWoodward。我修好了它。我误读了界面并使用了您为模拟设置的内容,没有意识到它与界面定义不匹配..
    • 非常感谢,这对我很有帮助。现在我可以做更多的研究,以了解为什么会以这种方式完成。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多