-

Clean Tests

The Dual Standard

Do not adopt a dual standard where readability is neglected for tests.

As your code changes your tests will have to change. People who did not initially write them will have to understand them so that they can adapt, extend, or remove them.

XCTest classes can and should have instance variables and helper functions to enhance readability and reduce repetition. Both of which are perfectly safe to use, instance variables will be reset upon every test case. Helper functions will not be treated as tests as long as they don’t start with the word test.

Smaller Tests

Minimize the number of asserts and test just one concept per test function.

Smaller tests are easier to read and give clearer failure results. A tests failure should ideally be identifiable by its name and not require the user to dive deep in to the test code.

Any repetitive setup involved in doing this should be handled by setup(), instance variables or private helper functions.

func testAddMonths() {
    let may31 = SwiftyDate(day: 31, month: 5, year: 2019)

    let addMonthResult = may31.addMonths(1)
    XCTAssertEqual(addMonthResult.day, 30)
    XCTAssertEqual(addMonthResult.month, 6)
    XCTAssertEqual(addMonthResult.year, 2019)

    let addMonthResult2 = may31.addMonth(2)
    XCTAssertEqual(addMonthResult2.day, 31)
    XCTAssertEqual(addMonthResult2.month, 7)
    XCTAssertEqual(addMonthResult2.year, 2019)

    let june30 = SwiftyDate(day: 30, month: 6, year: 2019)
    let addMonthResult3 = june30.addMonths(1)
    XCTAssertEqual(addMonthResult3.day, 30)
    XCTAssertEqual(addMonthResult3.month, 7)
    XCTAssertEqual(addMonthResult3.year, 2019)
}
Bad: Three different scenarios bundled in to one test
func testDay31To30DayMonthJump() {
    let addMonthResult = may31.addMonths(1)
    XCTAssertEqual(addMonthResult.day, 30)
    XCTAssertEqual(addMonthResult.month, 6)
    XCTAssertEqual(addMonthResult.year, 2019)
}

func test31st2MonthJumpThroughA30DayMonth() {
    let addMonthResult = may31.addMonths(2)
    XCTAssertEqual(addMonthResult.day, 31)
    XCTAssertEqual(addMonthResult.month, 7)
    XCTAssertEqual(addMonthResult.year, 2019)
}

func testDay30To31DayMonthJump() {
    let addMonthResult = june30.addMonths(1)
    XCTAssertEqual(addMonthResult.day, 30)
    XCTAssertEqual(addMonthResult.month, 7)
    XCTAssertEqual(addMonthResult.year, 2019)
}
Good: Tests split up for different scenarios