Refactor Code

  • Gravatar
    Setting Up Objects Under Test

    by azamsharp on 5/3/2008 6:30:11 PM
  • One of the issues that I face when writing unit test is to set up the objects under tests with correct data so that they can be tested. I want to know what is the best way to set up the objects. Here are my couple of ways:
  • public void should_add_customer_successfully()
    {
    Customer c = new Customer()
    { FirstName = "john", LastName = "Doe" };

    // OR

    Customer c = FakeCustomerRepository.CreateCustomer();


    }
  • Refactor it!
  • Gravatar
    The problem usually isn't "how do I setup the properties of the object under test" but it's more like... I have TONS of setup code to prepare my environment, and only a few asserts! One way to reduce this is to introduce a pattern known as Object Mother or Builder. A fluent interface can be applied here that will help in test solubility. you can get really complex in your builder, but your tests get WAY more terse & readable.
    by subdigital on 5/4/2008 9:15:02 PM
  • public void an_employee_with_a_sales_history_of_1mil_and_a_seniority_of_4_years_should_get_a_15_pct_raise()
    {
    var emp = EmployeeBuilder.New("joe", "blow")
    .WithSale(100000m)
    .WithSale(500000m)
    .WithSale(300000m)
    .WithSale(100000m)
    .WithSale(50000m)
    .WithHireDate(DateTime.Now.AddYears(-5));

    var salaryCalc = new SalaryCalculator();
    var percentRaise = salaryCalc.CalculateSalaryRaisePercent(emp);

    Assert.That(percentRaise, Is.EqualTo(15.Percent));

    }
Please log in to refactor the code! Login