48

What's the difference between XCTAssert and XCTAssertTrue? They seem to be doing the same thing, if so why do we need both?

Boon
  • 40,656
  • 60
  • 209
  • 315
  • different semantics. I use `XCTAssertTrue`/`XCTAssertFalse` on `BOOL` and `XCTAssert` for everything else – Bryan Chen May 29 '14 at 23:35
  • 4
    @BryanChen There is no different semantics whatever. They are 100% identical. – matt May 30 '14 at 01:12
  • @matt Code perform the same thing doesn't always mean they have same semantics. – Bryan Chen May 30 '14 at 01:43
  • 1
    @BryanChen XCTAssert still means you are asserting the condition in it to be true, so technically it has the same semantic as XCTAssertTrue, no? – Boon May 30 '14 at 01:45
  • @Boon at least _I_ am reading `XCTAssertTrue(var)` as `XCTAssert(var == true)`. and yes it doesn't make much difference – Bryan Chen May 30 '14 at 01:47
  • 2
    @BryanChen It isn't that it performs the same thing. It literally _is_ the same thing. The semantics are identical - they are synonyms. – matt May 30 '14 at 02:49
  • The distinction is important in terms of readability. I prefer `XCTAssert` where my tests use a comparison operator, and `XCTAssertTrue/False` where the return value of the tested method is boolean. Examples: `XCTAssert(hasSomething() == false)` or `XCTAssert(getThings().count == 5)` vs. `XCTAssertFalse(hasSomething())` – David James Apr 17 '17 at 10:41
  • But @DavidJames, in your example `XCTAssertFalse` *is* a different semantic than `XCTAssert` because it's the inverse. The difference is between `XCTAssert` and `XCTAssertTrue`. The former asserts something is true whereas the latter is totally different in that it asserts something is true! ;) – Mark A. Donohoe Jan 28 '19 at 22:42

1 Answers1

44

You are correct to suggest that there is redundancy here. They are in fact absolutely identical - that is, under the hood they both evaluate to one and the same macro, _XCTPrimitiveAssertTrue.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • See _XCTestAssertions.h_ for confirmation. – matt May 30 '14 at 01:13
  • 13
    Hmmm... DRY doesn't count in unit test frameworks? ;-) – race_carr May 30 '14 at 01:36
  • 9
    The functionally equivalent synonyms do provide flexibility for writing readable code. `XCTAssertTrue(someStateVariable)` benefits from the more verbose `XCTAssertTrue`. `XCTAssert(a == b)` reads clearly with the more compact `XCTAssert`. Use whichever enhances the statement's readability. – marc-medley Sep 28 '15 at 18:48
  • 6
    You should consider using `XCTAssertEqual(a, b)` for case `XCTAssert(a == b)` because `XCTAssertEqual` can provide better logs. – Apan Mar 18 '19 at 11:23