Refactor Code

  • Gravatar
    Mocking a Concreate Class While Testing a Controller

    by azamsharp on 6/19/2008 10:00:16 AM
  • I am working on an application that uses MVP pattern. One of the troubles I am having is to test the view. The view is referenced by the presenter and the presenter fires the AddEmployee method to insert the employee into the database. I am using Castle Active Record for my domain model and DAL layer. My question is that how can I make sure that the view is working even if the database is not in place. So, basically I have to mock the Employee but then I don't want to put Fakes or SubClasses or Interfaces in my AddEmployee code for the presenter since one day there will be database and it should work automatically without me having to go to all the presenters and changing the domain objects from fakes, interfaces to the concrete types.
  • Here is my unit test:

    [Test]
    [RollBack]
    public void should_get_employee_inserted_message_when_the_employee_is_inserted()
    {
    MockRepository mocks = new MockRepository();
    var mockedView = mocks.CreateMock<IAddEmployeeView>();


    Expect.Call(mockedView.BarCode).Return("1111");
    Expect.Call(mockedView.FirstName).Return("Mohammad");
    Expect.Call(mockedView.LastName).Return("Azam");

    mockedView.Message = "Employee inserted";

    mocks.ReplayAll();

    AddEmployeePresenter presenter = new AddEmployeePresenter(mockedView);
    presenter.AddEmployee();
    mocks.VerifyAll();

    }

    Here is the presenter (AddEmployee method):

    public void AddEmployee()
    {
    //bool result = _repository.AddEmployee(
    // new Employee()
    // {
    // BarCode = _view.BarCode,
    // FirstName = _view.FirstName,
    // LastName = _view.LastName,
    // });

    //if (result)
    //{ _view.Message = "Employee inserted"; }
    //else { _view.Message = "Employee not inserted"; }

    Employee employee = new Employee()
    {
    BarCode = _view.BarCode,
    FirstName = _view.FirstName,
    LastName = _view.LastName
    };



    //employee.Save();

    //if (employee.Id > 0)
    //{
    // _view.Message = "Employee inserted";
    //}
    //else { _view.Message = "Employee not inserted"; }
    }


    You will see that a lot of code has been commented out. I am more towards the repository approach since that is an interface and I can mock the behavior of the interface.
  • Refactor it!
Please log in to refactor the code! Login