C# 如何为赝品创建有意义的单元测试

C# 如何为赝品创建有意义的单元测试,c#,unit-testing,service,dependency-injection,C#,Unit Testing,Service,Dependency Injection,我了解如何进行单元测试的基本知识,但我常常难以找到有意义的东西进行测试。我相信我必须创建一个伪实现并注入消费者。我有一个服务类负责订阅(使用Exchange Web服务(EWS))Exchange 2010,请求更新新邮件。为了将订阅实现与服务本身分离,我决定将实现注入服务中。下面是我目前拥有的。我省略了专门处理与Exchange通信的代码 // Not a big fan of having two identical interfaces... public interface IStrea

我了解如何进行单元测试的基本知识,但我常常难以找到有意义的东西进行测试。我相信我必须创建一个伪实现并注入消费者。我有一个服务类负责订阅(使用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.
    }
}

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

通常,您会使用模拟框架来创建一个假交换,并对这个确实调用了订阅的对象进行测试。我通常使用,并且您的测试看起来像这样(有很多方法可以实现它):

[测试]
公共无效订阅交换()
{
var exchange=MockRepository.GenerateMock();//这是存根
var service=StreamingNotificationService(exchange);//这是我们正在测试的对象
service.Subscribe();
调用service.assertwas(x=>x.Subscribe(););
}

就单元测试而言,解耦和注入始终是一个非常好的主意

现在,您可以轻松地测试StreamingNotificationService类。您所要做的就是测试构造是否运行良好,subscribemethod是否调用您的注入(和伪)IExchangeService

[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(););
}