3

I'm build a set of XCTestCase methods to exercise the code around my core data model. I am planning on calling some of the test methods from other test methods so I can see different combinations of data while keeping the code to a minimum. I can't imagine why this would not work, but I'm wondering what the world thinks and whether this is considered to be good practice.

Here's what it would look like:

@interface sessionTests : XCTestCase
@property (strong) Model *model;
@end
- (void)setUp
{
    [super setUp];    
    _model = [[Model alloc]init];
}

- (void) testValue1
{
    _model.value = 1;
    XCTAssertTrue(_model.value == 1, @"model.value is not 1");
}

- (void) testValue2
{
    _model.value = 2;
    XCTAssertTrue(_model.value == 2, @"model.value is not 2");
}

- (void) testStringHello
{
    _model.str = @"Hello";
    XCTAssertTrue([_model.str isEqualToString:@"Hello"], @"model.str is not Hello");
}

- (void) testHello1
{
    [self testValue1];
    [self testStringHello];
}

- (void) testHello2
{
    [self testValue2];
    [self testStringHello];
}
Dan Loughney
  • 4,647
  • 3
  • 25
  • 40

1 Answers1

4

Its not considered good practice for tests to depend on each other. They should be able to execute in their own right.

The problem is that if tests depend on each other it can be difficult to pinpoint where something has gone wrong.

So, unit tests should be self contained and as easy to understand as possible. In fact we often forgo some of the practices we might normally adhere to, such as with code duplication, in order to achieve this self-contained, easy to understand goal. Take a look at this DAMP vs DRY tests answer.

Community
  • 1
  • 1
Jasper Blues
  • 28,258
  • 22
  • 102
  • 185
  • Thanks Jasper, great perspective. – Dan Loughney Feb 22 '14 at 15:08
  • Xcode has been able to run single tests since 2013. Also, the individual tests should still be run as a unit, but then can be used as a normal method in other tests. Which should actually help to pinpoint what failed. – Michael Ozeryansky May 02 '17 at 13:20
  • Interesting perspective. When I started TDD (using the loose definition), I was taught that tests should never depend on other tests. Haven't revisited that question, until now, but here's a good counter point of view: http://stackoverflow.com/a/1781858/404201 – Jasper Blues May 02 '17 at 22:20
  • What about the first test being am i able to login? and all other tests doesn't make sense to run? – LetynSOFT Feb 03 '20 at 10:36
  • @LetynSOFT https://github.com/appsquickly/typhoon/wiki/integration-testing with unit tests, that won't be a problem. With integration tests, you can either: 1) Path the system to support the scenario or 2) create a util method. – Jasper Blues Feb 03 '20 at 10:56