如果我要遵循测试驱动的开发周期,我必须首先编写测试,然后编写代码。但是,如果我有以下课程:
public class ServiceProvider : IServiceProvider
{
private readonly IService1 service1;
private readonly IService2 service2;
...
public ServiceProvider()
{
service1 = new Service1();
service2 = new Service2();
...
}
public IService1 Service1 { get { return service1; } }
public IService2 Service2 { get { return service2; } }
...
}
并且仅检查返回的实例的测试不为null:
[TestFixture]
public class ServiceProviderTest
{
[Test]
public void ServicesAreNotNull()
{
var serviceProviderUT = new ServiceProvider();
Assert.That(serviceProviderUT.Service1, Is.Not.Null);
Assert.That(serviceProviderUT.Service2, Is.Not.Null);
...
}
}
我怎么能写一个强迫我从那个班级到下一个班级的考试呢?
public class ServiceProvider : IServiceProvider
{
private readonly Lazy<IService1> service1;
private readonly Lazy<IService2> service2;
...
public ServiceProvider()
{
service1 = new Lazy<IService1>(() => new Service1());
service2 = new Lazy<IService2>(() => new Service2());
...
}
public IService1 Service1 { get { return service1.Value; } }
public IService2 Service2 { get { return service2.Value; } }
...
}
答案 0 :(得分:2)
您的测试不应强迫您执行特定的实施。它期望某种行为。对于单元测试,您的代码是黑盒子,如果行为正确,则测试成功。在这种情况下,服务的实现是私有的,因此您的测试不应该担心它是如何实现的。如果未更改类的接口,则应具有相同的单元测试。延迟初始化更像是一个代码审查项目。