Removing a hidden source of bugs

To be able to use a short initializer only setting the title, we need to define it ourselves. But this also introduces a new source of potential bugs. We can remove the two micro features we have implemented and still have both tests pass. To take a look at how this works, open ToDoItem.swift, and comment out the properties and assignment in the initializer:

struct ToDoItem { 
//  let title: String 
//  let itemDescription: String? 
 
  
  init(title: String, 
itemDescription: String? = nil) {

// self.title = title // self.itemDescription = itemDescription } }

Run the tests. Both tests still pass. The reason for this is that they do not check whether the values of the initializer arguments are actually set to any ToDoItem properties. We can easily extend the tests to make sure that the values are set. First, let's change the name of the first test to test_Init_WhenGivenTitle_SetsTitle(), and replace its contents with the following code:

let item = ToDoItem(title: "Foo") 
XCTAssertEqual(item.title, "Foo", 
"should set title")

This test does not compile because ToDoItem does not have a title property (it is commented out). This shows that the test is now testing our intention. Remove the comment signs for the title property and assignment of the title in the initializer, and run the tests again. All the tests pass. Now, replace the second test with this one:

func test_Init_WhenGivenDescription_SetsDescription() { 
  let item = ToDoItem(title: "",
itemDescription: "Bar") XCTAssertEqual(item.itemDescription, "Bar", "should set itemDescription") }

Remove the remaining comment signs in ToDoItem, and run the tests again. Both the tests pass again, and they now actually test that the initializer works.

It is a good idea to use speaking test method names. It's quite common to use a pattern such as test_<method name>_<precondition>_<expected behavior>. This way, the method name tells all that you need to know about the test when a test fails. In this book, we will try to follow this pattern, but we will leave out some information (for example, the precondition), when the code gets harder to read because of the limited space here in the book. You should develop your own pattern and use it in all your tests.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.134.102