iOS - Unit Testing Asynchoronous code

对着背影说爱祢 提交于 2019-12-07 10:28:51

问题


The part of a method that I am trying to test is as follows:

- (void)configureTableFooterView {
    dispatch_async(dispatch_get_main_queue(), ^{
        self.tableView.tableFooterView = nil;

        if ([self.parser.resultSet isLastPage]) {
            return;
        }
    });
}

I have written the unit test as follows:

- (void)testTableFooterViewConfigurationAfterLastPageLoaded {

    id mockTableView = OCMClassMock([GMGFlatTableView class]);

    OCMExpect([mockTableView setTableFooterView:[OCMArg isNil]]);

    id resultSet = OCMClassMock([GMGResultSetInfo class]);

    OCMStub([resultSet isLastPage]).andReturn(YES);

    OCMStub([self.mockParser resultSet]).andReturn(resultSet);

    id partialMockSUT = OCMPartialMock(self.sut);

    OCMStub([partialMockSUT tableView]).andReturn(mockTableView);

    [self.sut configureTableFooterView];

    OCMVerifyAllWithDelay(mockTableView, 2.0);

    //OCMVerifyAllWithDelay(partialMockSUT, 2.0); 
}

I have another test in the same class which is testing the same things from with in the dispatch_async call on the main thread. The test expectations and verification setup in that test match this one. While that test passes, this one gets stuck in an infinite loop at the delayed verification step.

Interestingly, if I only run this 1 test, it passes with out any problems. Its only when this test is run with other tests that I see the problem.

UPDATE:

In unit test, execute the block passed in queue with dispatch_asyc

This is a much more relevant post. However, this fails almost in the exact same way as the original test method:

- (void)testTableFooterViewConfigurationAfterLastPageLoaded {

    id mockTableView = OCMClassMock([GMGFlatTableView class]);

    OCMExpect([mockTableView setTableFooterView:[OCMArg isNil]]);

    id resultSet = OCMClassMock([GMGResultSetInfo class]);

    OCMStub([resultSet isLastPage]).andReturn(YES);

    OCMStub([self.mockParser resultSet]).andReturn(resultSet);

    id partialMockSUT = OCMPartialMock(self.sut);

    OCMStub([partialMockSUT tableView]).andReturn(mockTableView);

    [self.sut configureTableFooterView];

    [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]];

    OCMVerifyAll(mockTableView);
}

The line with NSRunLoop crashes with EXC_BAD_ACCESS when run as suite but runs fine alone!


回答1:


You can make class wrapper around dispatch_async, and pass it as dependency. Also you can make fake wrapper, and pass it in tests. If you interested in, I can provide much more detailed explanation.



来源:https://stackoverflow.com/questions/39453643/ios-unit-testing-asynchoronous-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!