How is the Unit Test method that calls NSDate ()?

I am currently using Swift.

My question is simple, how do you unit test a method that creates an object in a database with NSDate () as a property?

The problem is that in my statement I will create a new NSDate () as follows:

let expectedObject = Object(data: NSDate())
XCTAssertEqual(database.objects(), [expectedObject])

And the statement will fail, because the 2 NSDates are a little different.

Thank.

+4
source share
2 answers

One simple way could be to use the following approach:

  • Create a mock class derived from the test class.
  • Add the getDate () → NSDate method to the class under the test, which returns "NSDate ()" - or any other value is expected.
  •   getDate() mockClass. mock   , getDate().    , .
  • , , ,    mock .
0

https://testdriven-ios.com

, NSDate.date ,

@implementation NSDate (custom)

+ (instancetype)date{
    NSDateFormatter* formatter = NSDateFormatter.new;
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ssZZZ"];
    return [formatter dateFromString:@"2017-12-28 13:00:10+0000"];
}

@end

, NSDate.date, 2017-12-28 13:00:10+0000

@implementation NSDate (custom)

+ (instancetype)date{
    NSDateFormatter* formatter = NSDateFormatter.new;
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ssZZZ"];
    return [formatter dateFromString:theDate];
}

@end

date,

-(void) test_something_out {
 theDate = @"2017-12-28 13:00:10+0000";
 //Test any function that uses nsdate.date
}
0

All Articles