dimanche 31 mai 2015

OCMock test category methods

I may not completely understand mocking as I have a burning question about a very basic scenario. How does one test an instance method of a class OR how does one test a category method for a class?

Consider a class PeerMessage which defines a few properties, etc. I create my own custom category for PeerMessage called Type where I define a method, isTextMessage:. isTextMessage returns a boolean value based on the contents of a PeerMessage. (Please not that this is just an sample type.)

In a test with OCMock, I configure a mock of type PeerMessage and set it's content to some valid value as follows:

id peerMessage = [OCMockObject mockForClass:[PeerMessage class]];
[[[peerMessage stub] andReturn:@"<valid>"] content];

And then assert that peerMessage is a text message:

XCTAssert([peerMessage isTextMessage]);

Considering how mocking works, this results in: 'Unexpected method invoked'. Clearly, as I didn't specify that I was expecting it; neither did I stub it. As I just wanted to verify this API.

How does one test these instance methods (in this case, category instance methods). One way to do this is to redesign the category as follows:

Instead of

- (BOOL)isTextMessage;

do:

+ (BOOL)isTextMessage:(PeerMessage *)message;

But this is to me is very unnatural and I don't feel like writing this code although I don't see anything wrong with it. It doesn't need to be class method. :/

(If my explanation for the question is a bit ambiguous, I'd be happy to update.)

Aucun commentaire:

Enregistrer un commentaire