Skip to content

Remove stubs after each test

Klein Lieu edited this page Jul 30, 2015 · 3 revisions

When you use OHHTTPStubs to stub network requests for your Unit Tests, keep in mind that each stub that you may add in a test case is still in place when the next test executes.

This is the reason why I strongly suggest to remove all stubs after each of your test cases to be sure they don't interfere with other test cases.

You may do this by calling [OHHTTPStubs removeAllStubs] either in -(void)setUp (executed before each test case) or -(void)tearDown (executed after each test case) if you use OCUnit or XCTest.

- (void)tearDown
{
  [super tearDown];
  [OHHTTPStubs removeAllStubs];
}

Likewise, you may call [OHHTTPStubs removeAllStubs] in afterEach if you are using Test frameworks like Specta/Expecta:

afterEach(^{
    [OHHTTPStubs removeAllStubs];
});

Warning

If you forgot to follow instructions in the OHHTTPStubs and asynchronous tests page, you may encounter some unexpected behavior. In particular, if you call [OHHTTPStubs removeAllStubs] in tearDown but didn't make your test case wait for the request to get its response, the test will end — stub will be removed by tearDownbefore the request had enough time to execute and OHHTTPStubs had time to stub the response.

For that reason, be sure you implement asynchronous tests correctly, making them wait until the asynchronous response has arrived before finishing.