1

all:

I've the following unit tests class (implementation file shown):

@implementation SampleTests {
    A* c;
    NSString* token;
}

- (void)setUp
{
    [super setUp];

    // Set-up code here.
    c = [[A alloc] init];
}

- (void)tearDown
{
    // Tear-down code here.

    [super tearDown];
}

- (void)testA
{
    token = @"sample";
}

-(void)testB
{
    [c method:token]; // <-- fails because token is nil, but c has a correct value. Why!
}

@end

When I run my tests, testB fails because token is nil, but c it's ok, so why is it token destroyed?

neutrino
  • 2,297
  • 4
  • 20
  • 28

3 Answers3

2

Every time you run your unit tests, each test case is invoked independently. Before each test case runs, the setUp method is called, and afterwards the tearDown method is called.

So if you want to share token among tests, you should add

token = @"sample"; // or smth else 

to your setUp method.

Dmitry Zhukov
  • 1,809
  • 2
  • 27
  • 35
1

As far as I know, the current implementation runs the test methods in their alphabetic order, so your example should run without problems.

Usually, if I want something to be tested first, I name the methods test1_criticalFeature, test2_dependentFeatures etc.

Sulthan
  • 128,090
  • 22
  • 218
  • 270
  • Thank you Sulthan. That's right, but anyway the variables were destroyed. I think that a new instance of the `SampleTests` was created for each test. – neutrino Apr 08 '13 at 19:13
  • @neutrino I don't think this is true. I am pretty sure I am sharing some objects between my tests in one test class. This is the whole concept of having several test methods in one class. – Sulthan Apr 08 '13 at 19:17
  • Then I don't know what is happening... What do you think that is wrong with my code? – neutrino Apr 08 '13 at 19:22
  • I did it, and I see that at the end of the `testA` test method, the variable is destroyed, and set to nil. – neutrino Apr 08 '13 at 19:42
0

The order that test methods are executed in is not guaranteed, so it could be the case that testB is run before testA or even in the future that they are run in parallel.

Mike Weller
  • 45,401
  • 15
  • 131
  • 151
  • I don't think that running tests in parallel is possible because it would break on shared resources (e.g. singletons). Running tests in parallel makes sense only if the thing you test is the synchronization. – Sulthan Apr 08 '13 at 15:10
  • Yeah, the point was more of a theoretical one. A better example may be that the test runner could theoretically figure out which tests don't need to be run again based on what code has changed since they were last run. – Mike Weller Apr 08 '13 at 15:13