gpt4 book ai didi

c# - 如何验证调用了一个方法?

转载 作者:太空狗 更新时间:2023-10-30 01:24:55 25 4
gpt4 key购买 nike

我有一个 ICreateService依赖于 ITicketApiAdapter 的类.我已经尝试注册一个模拟 ITicketAdaper,以便在我创建匿名创建服务时注入(inject)它。

因此,在设置中,我为票证适配器注册了这个:

Fixture.Register(() =>
{
var ticketApiAdapter = new Mock<ITicketApiAdapter>();
ticketApiAdapter
.Setup( x => x.AddTicketComment(
It.IsAny<User>(),
It.IsAny<Customer>(),
It.IsAny<TicketComment>()))
.Returns(new SaveResult
{
Success = true,
Id = Fixture.CreateAnonymous<Guid>().ToString()
});

return ticketApiAdapter;
});

Fixture.Register(() => new CreateService(Fixture.CreateAnonymous<Mock<ITicketApiAdapter>>().Object));

根据我的理解,这应该“卡住”ICreateServiceMock<ITicketApiAdapter>这样当我请求一个匿名实例时,它就是我注册的实例。

我有一个看起来像这样的测试:

[TestMethod]
public void CreateServiceCallsAddTicketComment()
{
var apiTicketAdapter = Fixture.CreateAnonymous<Mock<ITicketApiAdapter>>();
var createTicketRequest = Fixture.CreateAnonymous<CreateTicketComment>();
var createService = Fixture.CreateAnonymous<CreateService>();

var results = createService.CreateTicketComment(createTicketRequest);

apiTicketAdapter
.Verify(x => x.AddTicketComment(
It.IsAny<User>(),
It.IsAny<Customer>(),
It.IsAny<TicketComment>()),
Times.Once());

Assert.IsTrue(results.All(x => x.Success));
Assert.IsTrue(results.All(x => x.Errors.Count == 0));

}

我希望 apiTicketAdapter 是我注册的那个,这样我就可以验证方法是否被调用。如果我单步执行,则会调用 TicketApiAdapter,但 Moq 说它不是。

编辑

这是我得到的错误:

CreateServiceCallsAddTicketComment threw exception: Moq.MockException: Expected invocation on the mock once, but was 0 times: x => x.AddTicketComment(It.IsAny(), It.IsAny(), It.IsAny())

Configured setups: x => x.AddTicketComment(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never No invocations performed.

最佳答案

当您注册代码块时,每次 Fixture 实例解析所请求的类型时都会调用该代码块。这意味着它没有被卡住。如果你想卡住一些东西,Freeze overloads之一通常更易于使用。

更好的是,因为您似乎在使用 Moq,我可以建议使用 AutoMoq extension

这将使您能够将测试重写为如下内容:

[TestMethod]
public void CreateServiceCallsAddTicketComment(new AutoMoqCustomization());
{
var fixture = new Fixture().Customize()
var apiTicketAdapter = fixture.Freeze<Mock<ITicketApiAdapter>>();
ticketApiAdapter
.Setup( x => x.AddTicketComment(
It.IsAny<User>(),
It.IsAny<Customer>(),
It.IsAny<TicketComment>()))
.Returns(new SaveResult
{
Success = true,
Id = Fixture.CreateAnonymous<Guid>().ToString()
});

var createTicketRequest = fixture.Freeze<CreateTicketComment>();
var createService = fixture.CreateAnonymous<CreateService>();

var results = createService.CreateTicketComment(createTicketRequest);

apiTicketAdapter
.Verify(x => x.AddTicketComment(
It.IsAny<User>(),
It.IsAny<Customer>(),
It.IsAny<TicketComment>()),
Times.Once());

Assert.IsTrue(results.All(x => x.Success));
Assert.IsTrue(results.All(x => x.Errors.Count == 0));

}

假设 CreateTicketRequest 使用构造函数注入(inject)或属性注入(inject)。

关于c# - 如何验证调用了一个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8069164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com