我理解如何进行单元测试的基础知识,但是我经常很难找到要测试的有意义的东西。我相信我必须创建一个虚假的实现并注入消费者。我有一个服务类负责订阅(使用Exchange Web服务(EWS))Exchange 2010请求更新新邮件。为了将我的订阅实现与服务本身分离,我决定在服务中注入实现。以下是我目前的情况。我省略了专门与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.
}
}
更具体地说,如何创建有意义的单元测试以确保订阅按照应有的方式工作?
答案 0 :(得分:3)
通常你会使用一个模拟框架来创建一个虚假的交换并测试这个确实调用了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(););
}
答案 1 :(得分:1)
在单元测试方面,解耦和注射始终是一个非常好的主意。
现在您可以轻松地测试StreamingNotificationService类。你所要做的就是测试是否构造行为很好,如果subscribemethod调用你的注入(和假)IExchangeService。