Question

I am fairly new to unit testing, and in iOS in particular

I have a testcase which should succeed if i see two objects are NOT equal

I cannot find a method that gives me that, besides requesting the test to fail upon checking that they are equal.

I do not wish to have a test fail for objects that are not equal,

i wish the test to succeed if the objects are not equal.

Which method will accomplish that ?

This is my test method:

-(void)testServerProtocolSetting{

ServerProtocol *server = [ServerProtocol sharedInstance];

id stub = [OCMockObject mockForClass:[ServerProtocol class]];

ServerProtocol *server1 = server;

[[stub expect]isNULL];

[ServerProtocol setSharedInstance:stub];

[stub verify];

server = [ServerProtocol sharedInstance];

XCTAssertEqualObjects(server1, server, @"server and server1 are not equal");

}

Was it helpful?

Solution

Just test what you actually want to happen, no need to overcomplicate your test:

XCTAssertFalse(server1 == server, @"The objects should not be equal");

the == operator on objects tests for pointer equality, so if server1 is the same objects as server2 then your test will fail as you want.

Alternatively

XCTAssertTrue(server1 != server, @"The objects should not be equal");

If you want to test for a different type of equality, such as done with isEqual, which returns true if the attributes of the object are equal, even if the objects are not the same instance, then:

XCTAssertFalse([server1 isEqual:server], @"The objects should not be equal");

It all depends on what type of equality you are testing for.

OTHER TIPS

XCTest macros generally support true conditions, not false ones. So while you can say

XCTAssertEqualObjects(server1, server);

to test for equality, and

XCTAssertEqual(server1, server);

to test for identity, it's not easy to invert them. You have to fall back on XCTAssertTrue/False, which isn't as good because it simply tells you that the assertion failed, but doesn't tell you the values unless you explicitly include them in the message:

XCTAssertFalse([server1 isEqual:server], @"Oops, both objects equal %@", server);

This is where more expressive matchers are handy, found in frameworks like OCHamcrest, Kiwi, Expecta and Cedar. In OCHamcrest, for example, matchers can be composed from other matchers, so you can wrap isNot(…) around any matcher. To test that server1 and server2 are not equal, it's

assertThat(server, isNot(equalTo(server1))));

Likewise, to test that server1 and server2 are not identical, it's

assertThat(server, isNot(sameInstance(server1))));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top