使用 Moq 和 xUnit 对服务进行单元测试

iam*_*isw 5 c# unit-testing moq xunit

抱歉,这可能是一个非常业余的问题,但我很难理解如何正确使用起订量。总的来说,我对单元测试还很陌生,但我想我已经开始掌握它的窍门了。

所以这是我的问题...我下面有这段代码,它TestServer在 Visual Studio 中使用我用于单元测试的代码...我试图进行模拟,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);

}
Run Code Online (Sandbox Code Playgroud)

这里是IGamesByPublisher

public interface IGamesByPublisher interface.
{
    Task<IEnumerable<Publisher>> Execute(GamesByPublisherQueryOptions options);
    }
}
Run Code Online (Sandbox Code Playgroud)

我试过

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

然后我尝试了

// 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);
Run Code Online (Sandbox Code Playgroud)

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

我显然缺少一些使用起订量的基础知识......

Nko*_*osi 7

你很接近。

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);
Run Code Online (Sandbox Code Playgroud)

上面创建了模拟,设置了它的预期行为,以便在任何时候Execute使用GamesByPublisherQueryOptions.

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