DI and testable Presenters

Topics: Web Client Software Factory
Dec 25, 2008 at 6:19 AM
Edited Dec 26, 2008 at 5:36 AM
Hi,
Writing my first wcsf app and I am trying to design testable presenters and use DI. Currently, I plan to use a different constructor for the unit test because its the only way I can think of to mock the IDataGateway class. eg.

public class CustomerPresenter : Presenter<ICustomerView>
    {
        private AppController _controller;
        private IDataGateway _dataGateway;

  //used for unit test only
        public CustomerPresenter(AppController controller, IDataGateway dataGateway)
        {
            _controller = controller;
            _dataGateway = dataGateway;
        }

        [InjectionConstructor]
        public CustomerPresenter([CreateNew] AppController controller, [ServiceDependency] Database database)
        {
            _controller = controller;
            _dataGateway = new CustomerGateway(database);
        }
    }

 I know this isn't ideal becuase I cant test the actual constructor used by DI. But what is a better way to do this?

Dec 26, 2008 at 12:58 PM

Hi,

I think the way you are solving the problem is ok. My only suggestion would be trying to create a Constructor hierarchy. In this way, you will be able to modify only the root Constructor’s behavior if any change is necessary. You could implement it using something like this:

 

public class CustomerPresenter : Presenter<ICustomerView>

{

private AppController _controller;

private IDataGateway _dataGateway;

 

//used for unit test only

//You can implement here all your constructor logic avoing duplicate code

public CustomerPresenter(AppController controller, IDataGateway dataGateway)

{

_controller = controller;

_dataGateway = dataGateway;

}

 

[InjectionConstructor]

public CustomerPresenter([CreateNew] AppController controller, [ServiceDependency] Database database): this(controller, new CustomerGateway(database)) { }

}

 

Please, let me know if this helps.

 

Ezequiel Sculli

http://blogs.southworks.net/esculli/
Dec 26, 2008 at 1:58 PM
That is a very good point. Thanks for the input.