iosunit-testingmockingstubs

How to practically use Stub or Mocking objects in iOS testing?


My question has two parts.

First I know very basic of testing in iOS and I am trying to learn when we using mocking. As far as I know mocking object is a simulation of fake objects when it is difficult to access that object such as querying a database or unpredictable situations. Can you explain a simple example how to mock a behaviour of database?

In my situation I want to test JSON packets I receive from API calls from Facebook API. I want to make sure these packets are not null and specific nodes are existed. What is the best method to test this?


Solution

  • A stub is a fake that provides a canned response when it is called. A mock is a fake that records how it was called. That's why mock object frameworks (such as OCMock or OCMockito) basically let you:

    I recommend not using a mock object framework at first. Instead, create them by hand by subclassing NSObject and defining the subset of methods you need. A stub will simply return the canned response. A mock will record the arguments to a method. Once you get the hang of it (and get tired of writing boilerplate code), then switch to a mock object framework. But you'll learn a lot by doing it by hand.

    The next thing you'll need is a way to get your stubs/mocks in to where they're called. This is done with Dependency Injection. Ideally, you pass them into your object's initializer — a test would pass in the fake, production code would pass in the real thing.

    Then each test should set up a single scenario. For example, you can pretend you got valid JSON with various parameters. You can pretend to get various error responses.