OCMock and NSFileManager
Asked Answered
B

2

6

I am trying to unit test a method which uses NSFileManager to check if a file exists and delete the file. I'm not sure I am correctly setting up the mock object.

I'm getting "Method was not invoked" even though I'm certain it was. Am I missing something in the way I set it up?

I set the mock object up as follows:

- (void)testdeleteFileWithPath {

    id fileManagerMock = OCMClassMock([NSFileManager class]);

    OCMStub([NSFileManager defaultManager]).andReturn(fileManagerMock);

    NSString *filePath = @"testPDF.pdf";
    NSURL *fileURL = [self.documentsDirectory URLByAppendingPathComponent:filePath];

    [self.fileDAO deleteFileWithPath:filePath];

    OCMVerify([fileManagerMock fileExistsAtPath:[fileURL path]]);
}

- (void)deleteFileWithPath:(NSString *)filePath
{    
    if (filePath) {
        NSURL *fileURL = [self.documentsDirectory URLByAppendingPathComponent:filePath];

        NSError *error = nil;
        if (![[NSFileManager defaultManager] fileExistsAtPath:[fileURL path]]) {
            NSLog(@"File to delete does not exist. \nPath: %@", [fileURL absoluteString]);

        } else
        {
            [[NSFileManager defaultManager] removeItemAtURL:fileURL error:&error];

            NSLog(@"Error: %@", [error description]);
        }
    }
}
Beaubeauchamp answered 25/3, 2015 at 16:52 Comment(0)
B
6

Got this working now. I was not stubbing the method on the mock object. The code should read as follows:

id fileManagerMock = OCMClassMock([NSFileManager class]); 
OCMStub([fileManagerMock defaultManager]).andReturn(fileManagerMock);
Beaubeauchamp answered 15/4, 2015 at 10:50 Comment(0)
T
2

You really should be doing a partial mock of the Object instance [fileManagerMock defaultManager] instead of the class: [NSFileManager class]:

id fileManagerMock = [OCMockObject partialMockForObject[fileManagerMock defaultManager]];

Seems likely that would affect the results

Theory answered 17/4, 2015 at 20:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.