Charlie
Charlie

Reputation: 664

TDD code to force lazy initialization

If I am to follow the test-driven development cycle, I must always write the test first, and then write the code. But then, if I have the following class:

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; } }
    ...
}

and a test that just checks that the instances returned are not 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);
        ...
    }
}

how can I write a test that forces me to go from that class to the following one?

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; } }
    ...
}

Upvotes: 1

Views: 98

Answers (1)

Peter
Peter

Reputation: 27944

Your test should not force you to do a specific implementation. It expects a certain behavior. For a unit test your code is a blackbox, if the behavior is correct the test succeeds. In this case the implementation of the services is private, so your test should not worry about how it is implemented. If the interface of a class is not changed, you should have the same unittests. The lazy initialization is more a code review item.

Upvotes: 2

Related Questions