1

Is there any way to share code among several OCUnit test cases? Maybe I'm missing something obvious, but I haven't been able to do it...

I have tried to put the common code in another class, but it seems you can only use STAssertxxx macros inside instance methods of classes inheriting from SenTestCase. Taking this into account, I put this common code in a singleton inheriting from SentTestCase with no test methods but this seems to break some internal assumption of OCUnit, as I'm not getting any errors from failed tests in the shared code.

My current code (not working) goes like this:

@interface TestHelper : SenTestCase
+ (TestHelper *)sharedHelper;
- (void)assertSomething:(id)object;
@end

@implementation TestHelper
+ (TestHelper *)sharedHelper
{
    // Typical singleton magic
}

- (void)assertSomething:(id)object
{
    STAssertWhateverOnObject(object, ...);
}
@end



@interface RealTestCase : SenTestCase
- (void)testWhatever;
- (void)testAnotherThing;
@end

@implementation RealTestCase
- (void)testWhatever
{
    [[TestHelper sharedHelper] assertSomething:someObject];
    STAssertOtherThings(someObject, ...);
}

- (void)testAnotherThing
{
    [[TestHelper sharedHelper] assertSomething:someSimilarObject];
    STAssertSomeOtherThings(someSimilarObject, ...);
}
@end

Please, note that this is a simple example. In this case I could put all the code in the RealTestCase class, but I would like a generic solution to share code among several test cases, not only among methods in the same test case.

By the way, I have a similar problem using Kiwi.

jgongo
  • 41
  • 4

2 Answers2

0

I think your choices are:

  • Use standalone helper functions, not a helper class. Or,
  • Use a different assertion mechanism like OCHamcrest that doesn't restrict you to SenTestCase subclasses.

You can write custom assertion macros similar to the ST ones, but it's a pain (and part of the reason I wrote OCHamcrest instead).

Jon Reid
  • 20,545
  • 2
  • 64
  • 95
0

My preferred way is using functions/methods to generate data to test (e.g. returning BOOL condition), not doing the actual tests.

In some cases I did use macro functions - it is unwrapped directly into your test case and doesn't have any limitations.

Sulthan
  • 128,090
  • 22
  • 218
  • 270