-1

I created the following class:

@implementation BCGlobalConstantBox

+ (instancetype)sharedInstance {

    static BCGlobalConstantBox *instance = nil;
    static dispatch_once_t predicate;
    dispatch_once( &predicate, ^{

        instance = [[self alloc] init];
    });
    return instance;
}

- (NSString *)someMethod {

    return nil;
}

@end

Then I added OCMock via sources (simply added files to my project). I use it not for testing but as temp data in usual debug target.

The following code works:

    id goalObj = [BCGlobalConstantBox class];
    id mock = [OCMockObject niceMockForClass:goalObj];
//    id mock = [OCMockObject partialMockForObject:[goalObj sharedInstance]];
    NSArray *arr = @[@1, @2, @3];
    [[[mock stub] andReturn:@"123"] someMethod];
    id obj = [[BCGlobalConstantBox sharedInstance] someMethod];

But if I uncomment the line with "mock" initialization instead of the working one then the whole code doesn't work properly (obj must be equal @"123").

I want to add the functionality for the whole class, not one object only. What is incorrect in my code?

P.S. mockForClass: and niceMockForClass: both don't work.

Gargo
  • 1,135
  • 1
  • 10
  • 21

1 Answers1

2

In your test the following line sets up a stub on the mock:

[[[mock stub] andReturn:@"123"] someMethod];

However, just below someMethod is invoked on the object returned by the sharedInstance class method on BCGGlobalConstantBox and that returns a real instance, not the mock. This means that the stub on the mock can't do its work.

You can make this work by adding another stub, a stub for the sharedInstance class method so that that returns the mock:

[[[mock stub] andReturn:mock] sharedInstance];

If there are many other methods called on the shared instance an alternative approach would be to retrieve the shared instance in the test and then create a partial mock for it, and use that partial mock for the stub.

Erik Doernenburg
  • 2,933
  • 18
  • 21