Unit Testing Approves Duplication

I am studying TDD and experimenting with this in my current project. I noticed that I have to duplicate a lot of statements in my tests. Here is the situation: I have an Order class with two constructors, the first by default and the second has three parameters

Order(int customerId, int typeId, decimal amount)

In the OrderTests class, I verify that jobs work well

Assert.IsTrue(o.CustomerId == 5 && o.TypeId == 3 && amount == 500)

I have an order service class with the following order creation method, since order creation is a complex process.

Order CreateOrder(int cusotmerId, int typeId, int amount, moreParams...)

There is a test in the OrderServiceTests class for this method, and I need to use the same assert to verify that the order was created correctly in the CreateOrder service.

Assert.IsTrue(o.CustomerId == 5 && o.TypeId == 3 && amount == 500)
  • Can such repetitions be used in tests?
  • , ? ?
+3
3

, (.. , factory). , .

( : red-green-refactor), , , , . .

[TestMethod]
public void if_parametrized_ctor_is_called_then_state_should_be_accordingly {
  var order = new Order(customerId, ...);
  ObjectPropertiesShouldBeSetTo(order, customerId, ...);
}

[TestMethod]
public void if_factory_method_is_called_then_state_should_be_accordingly {
  var order = myFactory.CreateOrder(customerId, ...);
  ObjectPropertiesShouldBeSetTo(order, customerId, ...);
}

// Extracted to remove code duplication
public void ObjectPropertiesShouldBeSetTo(Order order, int customerId, ...) {
  Assert.AreEqual(customerId, order.CustomerId);
  Assert.AreEqual(...);
}

, Assert, . , , - .

+4

, - . AssertObjectIsValid .

, Assert. Assert , . Asserts , ( , CruiseControl.Net.) :

Assert.IsTrue(o.CustomerID == 5, "CustomerID doesn't match expected");
Assert.IsTrue(o.TypeId == 3, "TypeID doesn't match expected");
Assert.IsTrue(amount == 500, "Amount doesn't match expected");
+3

, . . , , . , . ( , unit test.) .

+1

Source: https://habr.com/ru/post/1790638/


All Articles