gpt4 book ai didi

c# - 如何为假货创建有意义的单元测试

转载 作者:行者123 更新时间:2023-11-30 15:45:17 24 4
gpt4 key购买 nike

我了解如何进行单元测试的基础知识,但是我经常难以找到要测试的有意义的东西。我相信我必须创建一个伪造的实现并注入(inject)消费者。我有一个服务类负责订阅(使用 Exchange Web 服务 (EWS))Exchange 2010 请求更新新邮件。为了将我的订阅实现与服务本身分离,我决定将实现注入(inject)到服务中。以下是我目前拥有的。我省略了专门处理与 Exchange 通信的代码。

// Not a big fan of having two identical interfaces...
public interface IStreamingNotificationService
{
void Subscribe();
}

public interface IExchangeService
{
void Subscribe();
}

public class StreamingNotificationService : IStreamingNotificationService
{
private readonly IExchangeService _exchangeService;

public StreamingNotificationService(IExchangeService exchangeService)
{
if (exchangeService == null)
{
throw new ArgumentNullException("exchangeService");
}

_exchangeService = exchangeService;
}

public void Subscribe()
{
_exchangeService.Subscribe();
}
}

public class ExchangeServiceImpl : IExchangeService
{
private readonly INetworkConfiguration _networkConfiguration;
private ExchangeService ExchangeService { get; set; }

public ExchangeServiceImpl(INetworkConfiguration networkConfiguration)
{
if (networkConfiguration == null)
{
throw new ArgumentNullException("networkConfiguration");
}

_networkConfiguration = networkConfiguration;
// Set up EWS
}

public void Subscribe()
{
// Subscribe for new mail notifications.
}
}

更具体地说,我如何创建有意义的单元测试以确保订阅按应有的方式工作?

最佳答案

通常你会使用一个模拟框架来创建一个虚假的交换并测试这个对象是否确实调用了 Subscribe。我通常使用 Rhino Mocks ,你的测试看起来像像这样(有很多方法可以实现):

[Test]
public void SubscribesToExchange()
{
var exchange = MockRepository.GenerateMock<IExchangeService>(); //this is the stub
var service = StreamingNotificationService(exchange); //this is the object we are testing

service.Subscribe();
service.AssertWasCalled(x => x.Subscribe(););
}

关于c# - 如何为假货创建有意义的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5327518/

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