0

I am using cocoapods-keys and trying to test if the method returns valid url with secret API key.

Test suite looks like this:

it(@"should return valid url for api", ^{
    NSURL *url = [APIRoutes apiURLWithPath:path parameters:nil];
    expect([url absoluteString]).to.equal([NSString stringWithFormat:@"http://www.api.com/api/v2/places?api_key=MY_API_KEY"]);
});

But the real method is returning my valid API key which is hash (e.g. 8s97f89asf89asf987saf) and my test fails. How can I test this? Should I create fake implementation of my class in my test file?

tailec
  • 630
  • 1
  • 7
  • 20

1 Answers1

1

The way to go would be to mock the URL and API key that APIRoutes holds and test that you get the expected complete mock URL. This way you only test the logic and not the specific value of the URL.

Artal
  • 8,933
  • 2
  • 27
  • 30
  • Thank you. Do you think is it OK to 'inject' API key as a method argument? I mean something like [this](https://gist.github.com/tailec/79d695aa52162ec26efb#file-gistfile1-m) – tailec Jun 02 '15 at 21:15
  • 1
    @tailec it will get the job done, but it's not ideal. You don't want tests to dictate changes in your methods. Plus, you might run into more complex cases in the future. I recommend that you look into integrating a library like OCMock or something similar. – Artal Jun 02 '15 at 21:27
  • I read [this](http://www.objc.io/issue-15/dependency-injection.html) article so thats how I came up with this solution. I am using OCMock but I don't quite understand how the test suite would look like with mocked URL, API key and expected URL. – tailec Jun 02 '15 at 21:31
  • 1
    @tailec well, you're not exactly injecting a dependency, as in a complex object (that you might even want to mock), you're just passing a value. And you probably don't want to expose this method like that and provide the key externally anyway. Regarding how to mock it - it really depends on the implementation of APIRoutes which I don't exactly know.. But if you hold the URL and key in a property for example, you can create a partial mock of APIRoutes, stub the property's get method and return your mock value. – Artal Jun 02 '15 at 21:49
  • I created another [question](http://stackoverflow.com/questions/30608038/how-to-partially-mock-external-object) about this. – tailec Jun 02 '15 at 23:02