Wednesday, December 23, 2015

Improve Unit Test with OCMock

Adding OCMock to your project:

  • Step 1: Download a release from the downloads page.
  • Step 2: Setup OCMock from the iOS page.
  • Step 3: Add an import to your unit tests.
#import <OCMock/OCMock.h>

Contents:

  • 1. Example classes

Let's assume we are writing a little application. Our application have two classes as ClassA and ClassB. ClassB inherit from ClassA. They have some methods as below:
  • 2. Expect-run-verify

This is the original approach to mocking. First the mock object is set up with expectations, then the code under test is run, and afterwards the expectations are verified. If an expected method has not been invoked, or has not been invoked with the right arguments, then an error is reported. As shown it is possible to use argument constraints in the expect statement. Strict mocks can be created for classes and protocols.
Example codes:

  • 3. Verify after running

Verifies that some method has been called by the code under test. If the method has not been invoked an error is reported. In Xcode and AppCode the error is reported on the line of the verify, for other test environments an exception is thrown.
Base on the example of "Expect-Run-Verify", I rewrite as below:

  • 4. Void-Method

You can use ClassMock, PartialMock for test void method.
  • 5. Return-Method

You can use ClassMock, PartialMock for simulate the value is returned.
  • 6. Block

You can use ClassMock, PartialMock, andDo for simulate the value is returned from a block.
  • 7. Delegate and DataSource

You can use ProtocolMock for simulate a delegate or a datasource. Simulate the datasource of TableView
  • 8. Notification (Observer)

You can use ObserverMock for test NotificationCenter.
  • 9. Exception

You can use StrictClassMock for test Exception.
  • 10. Advanced topics

Verifying in order:The mock can be told to verify that expected methods are called in the same order as the expectations are set up. As soon as a method is called that is not next on the “expected list” the mock will fail fast and throw an exception. Using reject method: Using expect and return: Test to open an url:
Tools: XCode 7, OCMock 3.0

Reference documents:

- OCMock
- Engineering
- StackOverflow

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.