/
OCMockObjectTests.m
940 lines (691 loc) · 28.8 KB
/
OCMockObjectTests.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
/*
* Copyright (c) 2004-2015 Erik Doernenburg and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use these files except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#import <XCTest/XCTest.h>
#import <OCMock/OCMock.h>
#import "OCMBoxedReturnValueProvider.h"
// --------------------------------------------------------------------------------------
// Helper classes and protocols for testing
// --------------------------------------------------------------------------------------
@interface OCMBoxedReturnValueProvider (Private)
- (BOOL)isMethodReturnType:(const char *)returnType compatibleWithValueType:(const char *)valueType;
@end
@interface TestClassWithSelectorMethod : NSObject
- (void)doWithSelector:(SEL)aSelector;
@end
@implementation TestClassWithSelectorMethod
- (void)doWithSelector:(__unused SEL)aSelector
{
}
@end
@interface TestClassWithIntPointerMethod : NSObject
- (void)returnValueInPointer:(int *)ptr;
@end
@implementation TestClassWithIntPointerMethod
- (void)returnValueInPointer:(int *)ptr
{
*ptr = 555;
}
@end
@interface TestClassWithOpaquePointerMethod : NSObject
typedef struct TestOpaque *OpaquePtr;
- (OpaquePtr)opaquePtrValue;
@end
@implementation TestClassWithOpaquePointerMethod
typedef struct TestOpaque {
int i;
int j;
} TestOpaque;
TestOpaque myOpaque;
- (OpaquePtr)opaquePtrValue
{
myOpaque.i = 3;
myOpaque.i = 4;
return &myOpaque;
}
@end
@interface TestClassWithProperty : NSObject
@property (nonatomic, retain) NSString *title;
@end
@implementation TestClassWithProperty
@synthesize title;
@end
@interface NotificationRecorderForTesting : NSObject
{
@public
NSNotification *notification;
}
@end
@implementation NotificationRecorderForTesting
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)receiveNotification:(NSNotification *)aNotification
{
notification = aNotification;
}
@end
static NSString *TestNotification = @"TestNotification";
@interface OCMockObjectTests : XCTestCase
{
id mock;
}
@end
// --------------------------------------------------------------------------------------
// setup
// --------------------------------------------------------------------------------------
@implementation OCMockObjectTests
- (void)setUp
{
mock = [OCMockObject mockForClass:[NSString class]];
}
// --------------------------------------------------------------------------------------
// accepting stubbed methods / rejecting methods not stubbed
// --------------------------------------------------------------------------------------
- (void)testAcceptsStubbedMethod
{
[[mock stub] lowercaseString];
[mock lowercaseString];
}
- (void)testRaisesExceptionWhenUnknownMethodIsCalled
{
[[mock stub] lowercaseString];
XCTAssertThrows([mock uppercaseString], @"Should have raised an exception.");
}
- (void)testAcceptsStubbedMethodWithSpecificArgument
{
[[mock stub] hasSuffix:@"foo"];
[mock hasSuffix:@"foo"];
}
- (void)testAcceptsStubbedMethodWithConstraint
{
[[mock stub] hasSuffix:[OCMArg any]];
[mock hasSuffix:@"foo"];
[mock hasSuffix:@"bar"];
}
- (void)testAcceptsStubbedMethodWithBlockArgument
{
mock = [OCMockObject mockForClass:[NSArray class]];
[[mock stub] indexesOfObjectsPassingTest:[OCMArg any]];
[mock indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) { return YES; }];
}
- (void)testAcceptsStubbedMethodWithBlockConstraint
{
[[mock stub] hasSuffix:[OCMArg checkWithBlock:^(id value) { return [value isEqualToString:@"foo"]; }]];
XCTAssertNoThrow([mock hasSuffix:@"foo"], @"Should not have thrown a exception");
XCTAssertThrows([mock hasSuffix:@"bar"], @"Should have thrown a exception");
}
- (void)testAcceptsStubbedMethodWithNilArgument
{
[[mock stub] hasSuffix:nil];
[mock hasSuffix:nil];
}
- (void)testRaisesExceptionWhenMethodWithWrongArgumentIsCalled
{
[[mock stub] hasSuffix:@"foo"];
XCTAssertThrows([mock hasSuffix:@"xyz"], @"Should have raised an exception.");
}
- (void)testAcceptsStubbedMethodWithScalarArgument
{
[[mock stub] stringByPaddingToLength:20 withString:@"foo" startingAtIndex:5];
[mock stringByPaddingToLength:20 withString:@"foo" startingAtIndex:5];
}
- (void)testRaisesExceptionWhenMethodWithOneWrongScalarArgumentIsCalled
{
[[mock stub] stringByPaddingToLength:20 withString:@"foo" startingAtIndex:5];
XCTAssertThrows([mock stringByPaddingToLength:20 withString:@"foo" startingAtIndex:3], @"Should have raised an exception.");
}
- (void)testAcceptsStubbedMethodWithSelectorArgument
{
mock = [OCMockObject mockForClass:[TestClassWithSelectorMethod class]];
[[mock stub] doWithSelector:@selector(allKeys)];
[mock doWithSelector:@selector(allKeys)];
}
- (void)testRaisesExceptionWhenMethodWithWrongSelectorArgumentIsCalled
{
mock = [OCMockObject mockForClass:[TestClassWithSelectorMethod class]];
[[mock stub] doWithSelector:@selector(allKeys)];
XCTAssertThrows([mock doWithSelector:@selector(allValues)]);
}
- (void)testAcceptsStubbedMethodWithAnySelectorArgument
{
mock = [OCMockObject mockForClass:[TestClassWithSelectorMethod class]];
[[mock stub] doWithSelector:[OCMArg anySelector]];
[mock doWithSelector:@selector(allKeys)];
}
- (void)testAcceptsStubbedMethodWithPointerArgument
{
NSError __autoreleasing *error;
[[[mock stub] andReturnValue:@YES] writeToFile:[OCMArg any] atomically:YES encoding:NSMacOSRomanStringEncoding error:&error];
XCTAssertTrue([mock writeToFile:@"foo" atomically:YES encoding:NSMacOSRomanStringEncoding error:&error]);
}
- (void)testRaisesExceptionWhenMethodWithWrongPointerArgumentIsCalled
{
NSString *string;
NSString *anotherString;
NSArray *array;
[[mock stub] completePathIntoString:&string caseSensitive:YES matchesIntoArray:&array filterTypes:[OCMArg any]];
XCTAssertThrows([mock completePathIntoString:&anotherString caseSensitive:YES matchesIntoArray:&array filterTypes:[OCMArg any]]);
}
- (void)testAcceptsStubbedMethodWithAnyPointerArgument
{
[[mock stub] getCharacters:[OCMArg anyPointer]];
unichar buffer[10];
XCTAssertNoThrow([mock getCharacters:buffer], @"Should have stubbed method.");
}
- (void)testAcceptsStubbedMethodWithMatchingCharPointer
{
char buffer[10] = "foo";
[[[mock stub] andReturnValue:@YES] getCString:buffer maxLength:10 encoding:NSASCIIStringEncoding];
BOOL result = [mock getCString:buffer maxLength:10 encoding:NSASCIIStringEncoding];
XCTAssertEqual(YES, result, @"Should have stubbed method.");
}
- (void)testAcceptsStubbedMethodWithAnyPointerArgumentForCharPointer
{
[[[mock stub] andReturnValue:@YES] getCString:[OCMArg anyPointer] maxLength:10 encoding:NSASCIIStringEncoding];
char buffer[10] = "foo";
BOOL result = [mock getCString:buffer maxLength:10 encoding:NSASCIIStringEncoding];
XCTAssertEqual(YES, result, @"Should have stubbed method.");
}
- (void)testAcceptsStubbedMethodWithAnyObjectRefArgument
{
NSError *error;
[[[mock stub] andReturnValue:@YES] writeToFile:[OCMArg any] atomically:YES encoding:NSMacOSRomanStringEncoding error:[OCMArg anyObjectRef]];
XCTAssertTrue([mock writeToFile:@"foo" atomically:YES encoding:NSMacOSRomanStringEncoding error:&error]);
}
- (void)testAcceptsStubbedMethodWithVoidPointerArgument
{
mock = [OCMockObject mockForClass:[NSMutableData class]];
[[mock stub] appendBytes:NULL length:0];
[mock appendBytes:NULL length:0];
}
- (void)testRaisesExceptionWhenMethodWithWrongVoidPointerArgumentIsCalled
{
mock = [OCMockObject mockForClass:[NSMutableData class]];
[[mock stub] appendBytes:"foo" length:3];
XCTAssertThrows([mock appendBytes:"bar" length:3], @"Should have raised an exception.");
}
- (void)testAcceptsStubbedMethodWithPointerPointerArgument
{
NSError __autoreleasing *error = nil;
[[mock stub] writeToFile:@"foo.txt" atomically:NO encoding:NSASCIIStringEncoding error:&error];
[mock writeToFile:@"foo.txt" atomically:NO encoding:NSASCIIStringEncoding error:&error];
}
- (void)testRaisesExceptionWhenMethodWithWrongPointerPointerArgumentIsCalled
{
NSError *error = nil, *error2;
[[mock stub] writeToFile:@"foo.txt" atomically:NO encoding:NSASCIIStringEncoding error:&error];
XCTAssertThrows([mock writeToFile:@"foo.txt" atomically:NO encoding:NSASCIIStringEncoding error:&error2], @"Should have raised.");
}
- (void)testAcceptsStubbedMethodWithStructArgument
{
NSRange range = NSMakeRange(0,20);
[[mock stub] substringWithRange:range];
[mock substringWithRange:range];
}
- (void)testRaisesExceptionWhenMethodWithWrongStructArgumentIsCalled
{
NSRange range = NSMakeRange(0,20);
NSRange otherRange = NSMakeRange(0,10);
[[mock stub] substringWithRange:range];
XCTAssertThrows([mock substringWithRange:otherRange], @"Should have raised an exception.");
}
- (void)testCanPassMocksAsArguments
{
id mockArg = [OCMockObject mockForClass:[NSString class]];
[[mock stub] stringByAppendingString:[OCMArg any]];
[mock stringByAppendingString:mockArg];
}
- (void)testCanStubWithMockArguments
{
id mockArg = [OCMockObject mockForClass:[NSString class]];
[[mock stub] stringByAppendingString:mockArg];
[mock stringByAppendingString:mockArg];
}
- (void)testRaisesExceptionWhenStubbedMockArgIsNotUsed
{
id mockArg = [OCMockObject mockForClass:[NSString class]];
[[mock stub] stringByAppendingString:mockArg];
XCTAssertThrows([mock stringByAppendingString:@"foo"], @"Should have raised an exception.");
}
- (void)testRaisesExceptionWhenDifferentMockArgumentIsPassed
{
id expectedArg = [OCMockObject mockForClass:[NSString class]];
id otherArg = [OCMockObject mockForClass:[NSString class]];
[[mock stub] stringByAppendingString:otherArg];
XCTAssertThrows([mock stringByAppendingString:expectedArg], @"Should have raised an exception.");
}
- (void)testAcceptsStubbedMethodWithAnyNonObjectArgument
{
[[[mock stub] ignoringNonObjectArgs] rangeOfString:@"foo" options:0];
[mock rangeOfString:@"foo" options:NSRegularExpressionSearch];
}
- (void)testRaisesExceptionWhenMethodWithMixedArgumentsIsCalledWithWrongObjectArgument
{
[[[mock stub] ignoringNonObjectArgs] rangeOfString:@"foo" options:0];
XCTAssertThrows([mock rangeOfString:@"bar" options:NSRegularExpressionSearch], @"Should have raised an exception.");
}
// --------------------------------------------------------------------------------------
// returning values from stubbed methods
// --------------------------------------------------------------------------------------
- (void)testReturnsStubbedReturnValue
{
[[[mock stub] andReturn:@"megamock"] lowercaseString];
id returnValue = [mock lowercaseString];
XCTAssertEqualObjects(@"megamock", returnValue, @"Should have returned stubbed value.");
}
- (void)testReturnsStubbedIntReturnValue
{
[[[mock stub] andReturnValue:@42] intValue];
int returnValue = [mock intValue];
XCTAssertEqual(42, returnValue, @"Should have returned stubbed value.");
}
- (void)testReturnsStubbedUnsignedLongReturnValue
{
mock = [OCMockObject mockForClass:[NSNumber class]];
[[[mock expect] andReturnValue:@42LU] unsignedLongValue];
unsigned long returnValue = [mock unsignedLongValue];
XCTAssertEqual(returnValue, 42LU, @"Should have returned stubbed value.");
[[[mock expect] andReturnValue:@42] unsignedLongValue];
returnValue = [mock unsignedLongValue];
XCTAssertEqual(returnValue, 42LU, @"Should have returned stubbed value.");
[[[mock expect] andReturnValue:@42.0] unsignedLongValue];
returnValue = [mock unsignedLongValue];
XCTAssertEqual(returnValue, 42LU, @"Should have returned stubbed value.");
[[[mock expect] andReturnValue:OCMOCK_VALUE((char)42)] unsignedLongValue];
returnValue = [mock unsignedLongValue];
XCTAssertEqual(returnValue, 42LU, @"Should have returned stubbed value.");
[[[mock expect] andReturnValue:OCMOCK_VALUE((float)42)] unsignedLongValue];
returnValue = [mock unsignedLongValue];
XCTAssertEqual(returnValue, 42LU, @"Should have returned stubbed value.");
[[[mock expect] andReturnValue:OCMOCK_VALUE((float)42.5)] unsignedLongValue];
XCTAssertThrows([mock unsignedLongValue], @"Should not be able to convert non-integer float to long");
#if !__LP64__
[[[mock expect] andReturnValue:OCMOCK_VALUE((long long)LLONG_MAX)] unsignedLongValue];
XCTAssertThrows([mock unsignedLongValue], @"Should not be able to convert large long long to long");
#endif
}
- (void)testReturnsStubbedBoolReturnValue
{
[[[mock expect] andReturnValue:@YES] boolValue];
BOOL returnValue = [mock boolValue];
XCTAssertEqual(returnValue, YES, @"Should have returned stubbed value.");
[[[mock expect] andReturnValue:OCMOCK_VALUE(YES)] boolValue];
returnValue = [mock boolValue];
XCTAssertEqual(returnValue, YES, @"Should have returned stubbed value.");
[[[mock expect] andReturnValue:OCMOCK_VALUE(1)] boolValue];
returnValue = [mock boolValue];
XCTAssertEqual(returnValue, YES, @"Should have returned stubbed value.");
[[[mock expect] andReturnValue:OCMOCK_VALUE(300)] boolValue];
XCTAssertThrows([mock boolValue], @"Should not be able to convert large integer into BOOL");
}
- (void)testRaisesWhenBoxedValueTypesDoNotMatch
{
[[[mock stub] andReturnValue:[NSValue valueWithRange:NSMakeRange(0, 0)]] intValue];
XCTAssertThrows([mock intValue], @"Should have raised an exception.");
}
- (void)testOpaqueStructComparison
{
TestClassWithOpaquePointerMethod *obj = [TestClassWithOpaquePointerMethod new];
OpaquePtr val = [obj opaquePtrValue];
id mockVal = [OCMockObject partialMockForObject:obj];
[[[mockVal stub] andReturnValue:OCMOCK_VALUE(val)] opaquePtrValue];
OpaquePtr val2 = [obj opaquePtrValue];
XCTAssertEqual(val, val2);
// from https://github.com/erikdoe/ocmock/pull/97
const char *type1 =
"r^{GURL={basic_string<char, std::__1::char_traits<char>, std::__1::alloca"
"tor<char> >={__compressed_pair<std::__1::basic_string<char, std::__1::cha"
"r_traits<char>, std::__1::allocator<char> >::__rep, std::__1::allocator<c"
"har> >={__rep}}}B{Parsed={Component=ii}{Component=ii}{Component=ii}{Compo"
"nent=ii}{Component=ii}{Component=ii}{Component=ii}{Component=ii}^{Parsed}"
"}{scoped_ptr<GURL, base::DefaultDeleter<GURL> >={scoped_ptr_impl<GURL, ba"
"se::DefaultDeleter<GURL> >={Data=^{GURL}}}}}";
const char *type2 =
"r^{GURL={basic_string<char, std::__1::char_traits<char>, std::__1::alloca"
"tor<char> >={__compressed_pair<std::__1::basic_string<char, std::__1::cha"
"r_traits<char>, std::__1::allocator<char> >::__rep, std::__1::allocator<c"
"har> >={__rep=(?={__long=II*}{__short=(?=Cc)[11c]}{__raw=[3L]})}}}B{Parse"
"d={Component=ii}{Component=ii}{Component=ii}{Component=ii}{Component=ii}{"
"Component=ii}{Component=ii}{Component=ii}^{Parsed}}{scoped_ptr<GURL, base"
"::DefaultDeleter<GURL> >={scoped_ptr_impl<GURL, base::DefaultDeleter<GURL"
"> >={Data=^{GURL}}}}}";
const char *type3 =
"r^{GURL}";
OCMBoxedReturnValueProvider *boxed = [OCMBoxedReturnValueProvider new];
XCTAssertTrue([boxed isMethodReturnType:type1 compatibleWithValueType:type2]);
XCTAssertTrue([boxed isMethodReturnType:type1 compatibleWithValueType:type3]);
XCTAssertTrue([boxed isMethodReturnType:type2 compatibleWithValueType:type1]);
XCTAssertTrue([boxed isMethodReturnType:type2 compatibleWithValueType:type3]);
XCTAssertTrue([boxed isMethodReturnType:type3 compatibleWithValueType:type1]);
XCTAssertTrue([boxed isMethodReturnType:type3 compatibleWithValueType:type2]);
}
- (void)testReturnsStubbedNilReturnValue
{
[[[mock stub] andReturn:nil] uppercaseString];
id returnValue = [mock uppercaseString];
XCTAssertNil(returnValue, @"Should have returned stubbed value, which is nil.");
}
- (void)testReturnsStubbedValueForProperty
{
TestClassWithProperty *myMock = [OCMockObject mockForClass:[TestClassWithProperty class]];
[[[(id)myMock stub] andReturn:@"stubbed title"] title];
XCTAssertEqualObjects(@"stubbed title", myMock.title);
}
// --------------------------------------------------------------------------------------
// beyond stubbing: raising exceptions, posting notifications, etc.
// --------------------------------------------------------------------------------------
- (void)testRaisesExceptionWhenAskedTo
{
NSException *exception = [NSException exceptionWithName:@"TestException" reason:@"test" userInfo:nil];
[[[mock expect] andThrow:exception] lowercaseString];
XCTAssertThrows([mock lowercaseString], @"Should have raised an exception.");
}
- (void)testPostsNotificationWhenAskedTo
{
NotificationRecorderForTesting *observer = [[NotificationRecorderForTesting alloc] init];
[[NSNotificationCenter defaultCenter] addObserver:observer selector:@selector(receiveNotification:) name:TestNotification object:nil];
NSNotification *notification = [NSNotification notificationWithName:TestNotification object:self];
[[[mock stub] andPost:notification] lowercaseString];
[mock lowercaseString];
XCTAssertNotNil(observer->notification, @"Should have sent a notification.");
XCTAssertEqualObjects(TestNotification, [observer->notification name], @"Name should match posted one.");
XCTAssertEqualObjects(self, [observer->notification object], @"Object should match posted one.");
}
- (void)testPostsNotificationInAdditionToReturningValue
{
NotificationRecorderForTesting *observer = [[NotificationRecorderForTesting alloc] init];
[[NSNotificationCenter defaultCenter] addObserver:observer selector:@selector(receiveNotification:) name:TestNotification object:nil];
NSNotification *notification = [NSNotification notificationWithName:TestNotification object:self];
[[[[mock stub] andReturn:@"foo"] andPost:notification] lowercaseString];
XCTAssertEqualObjects(@"foo", [mock lowercaseString], @"Should have returned stubbed value.");
XCTAssertNotNil(observer->notification, @"Should have sent a notification.");
}
- (NSString *)valueForString:(NSString *)aString andMask:(NSStringCompareOptions)mask
{
return [NSString stringWithFormat:@"[%@, %ld]", aString, (long)mask];
}
- (void)testCallsAlternativeMethodAndPassesOriginalArgumentsAndReturnsValue
{
[[[mock stub] andCall:@selector(valueForString:andMask:) onObject:self] commonPrefixWithString:@"FOO" options:NSCaseInsensitiveSearch];
NSString *returnValue = [mock commonPrefixWithString:@"FOO" options:NSCaseInsensitiveSearch];
XCTAssertEqualObjects(@"[FOO, 1]", returnValue, @"Should have passed and returned invocation.");
}
- (void)testCallsBlockWhichCanSetUpReturnValue
{
void (^theBlock)(NSInvocation *) = ^(NSInvocation *invocation)
{
NSString *value;
[invocation getArgument:&value atIndex:2];
value = [NSString stringWithFormat:@"MOCK %@", value];
[invocation setReturnValue:&value];
};
[[[mock stub] andDo:theBlock] stringByAppendingString:[OCMArg any]];
XCTAssertEqualObjects(@"MOCK foo", [mock stringByAppendingString:@"foo"], @"Should have called block.");
XCTAssertEqualObjects(@"MOCK bar", [mock stringByAppendingString:@"bar"], @"Should have called block.");
}
- (void)testHandlesNilPassedAsBlock
{
[[[mock stub] andDo:nil] stringByAppendingString:[OCMArg any]];
XCTAssertNoThrow([mock stringByAppendingString:@"foo"], @"Should have done nothing.");
XCTAssertNil([mock stringByAppendingString:@"foo"], @"Should have returned default value.");
}
- (void)testThrowsWhenTryingToUseForwardToRealObjectOnNonPartialMock
{
XCTAssertThrows([[[mock expect] andForwardToRealObject] name], @"Should have raised and exception.");
}
// --------------------------------------------------------------------------------------
// returning values in pass-by-reference arguments
// --------------------------------------------------------------------------------------
- (void)testReturnsValuesInPassByReferenceArguments
{
NSString *expectedName = @"Test";
NSArray *expectedArray = [NSArray array];
[[mock expect] completePathIntoString:[OCMArg setTo:expectedName] caseSensitive:YES
matchesIntoArray:[OCMArg setTo:expectedArray] filterTypes:[OCMArg any]];
NSString *actualName = nil;
NSArray *actualArray = nil;
[mock completePathIntoString:&actualName caseSensitive:YES matchesIntoArray:&actualArray filterTypes:nil];
XCTAssertNoThrow([mock verify], @"An unexpected exception was thrown");
XCTAssertEqualObjects(expectedName, actualName, @"The two string objects should be equal");
XCTAssertEqualObjects(expectedArray, actualArray, @"The two array objects should be equal");
}
- (void)testReturnsValuesInNonObjectPassByReferenceArguments
{
mock = [OCMockObject mockForClass:[TestClassWithIntPointerMethod class]];
[[mock stub] returnValueInPointer:[OCMArg setToValue:@1234]];
int actualValue = 0;
[mock returnValueInPointer:&actualValue];
XCTAssertEqual(1234, actualValue, @"Should have returned value via pass by ref argument.");
}
// --------------------------------------------------------------------------------------
// accepting expected methods
// --------------------------------------------------------------------------------------
- (void)testAcceptsExpectedMethod
{
[[mock expect] lowercaseString];
[mock lowercaseString];
}
- (void)testAcceptsExpectedMethodAndReturnsValue
{
[[[mock expect] andReturn:@"Objective-C"] lowercaseString];
id returnValue = [mock lowercaseString];
XCTAssertEqualObjects(@"Objective-C", returnValue, @"Should have returned stubbed value.");
}
- (void)testAcceptsExpectedMethodsInRecordedSequence
{
[[mock expect] lowercaseString];
[[mock expect] uppercaseString];
[mock lowercaseString];
[mock uppercaseString];
}
- (void)testAcceptsExpectedMethodsInDifferentSequence
{
[[mock expect] lowercaseString];
[[mock expect] uppercaseString];
[mock uppercaseString];
[mock lowercaseString];
}
// --------------------------------------------------------------------------------------
// verifying expected methods
// --------------------------------------------------------------------------------------
- (void)testAcceptsAndVerifiesExpectedMethods
{
[[mock expect] lowercaseString];
[[mock expect] uppercaseString];
[mock lowercaseString];
[mock uppercaseString];
[mock verify];
}
- (void)testRaisesExceptionOnVerifyWhenNotAllExpectedMethodsWereCalled
{
[[mock expect] lowercaseString];
[[mock expect] uppercaseString];
[mock lowercaseString];
XCTAssertThrows([mock verify], @"Should have raised an exception.");
}
- (void)testAcceptsAndVerifiesTwoExpectedInvocationsOfSameMethod
{
[[mock expect] lowercaseString];
[[mock expect] lowercaseString];
[mock lowercaseString];
[mock lowercaseString];
[mock verify];
}
- (void)testAcceptsAndVerifiesTwoExpectedInvocationsOfSameMethodAndReturnsCorrespondingValues
{
[[[mock expect] andReturn:@"foo"] lowercaseString];
[[[mock expect] andReturn:@"bar"] lowercaseString];
XCTAssertEqualObjects(@"foo", [mock lowercaseString], @"Should have returned first stubbed value");
XCTAssertEqualObjects(@"bar", [mock lowercaseString], @"Should have returned seconds stubbed value");
[mock verify];
}
- (void)testReturnsStubbedValuesIndependentOfExpectations
{
[[mock stub] hasSuffix:@"foo"];
[[mock expect] hasSuffix:@"bar"];
[mock hasSuffix:@"foo"];
[mock hasSuffix:@"bar"];
[mock hasSuffix:@"foo"]; // Since it's a stub, shouldn't matter how many times we call this
[mock verify];
}
-(void)testAcceptsAndVerifiesMethodsWithSelectorArgument
{
[[mock expect] performSelector:@selector(lowercaseString)];
[mock performSelector:@selector(lowercaseString)];
[mock verify];
}
// --------------------------------------------------------------------------------------
// verify with delay
// --------------------------------------------------------------------------------------
- (void)testAcceptsAndVerifiesExpectedMethodsWithDelay
{
[[mock expect] lowercaseString];
[[mock expect] uppercaseString];
[mock lowercaseString];
[mock uppercaseString];
[mock verifyWithDelay:1];
}
- (void)testAcceptsAndVerifiesExpectedMethodsWithDelayBlock
{
dispatch_async(dispatch_queue_create("mockqueue", nil), ^{
[NSThread sleepForTimeInterval:0.1];
[mock lowercaseString];
});
[[mock expect] lowercaseString];
[mock verifyWithDelay:1];
}
- (void)testFailsVerifyExpectedMethodsWithoutDelay
{
dispatch_async(dispatch_queue_create("mockqueue", nil), ^{
[NSThread sleepForTimeInterval:0.1];
[mock lowercaseString];
});
[[mock expect] lowercaseString];
XCTAssertThrows([mock verify], @"Should have raised an exception because method was not called in time.");
}
- (void)testFailsVerifyExpectedMethodsWithDelay
{
[[mock expect] lowercaseString];
XCTAssertThrows([mock verifyWithDelay:0.1], @"Should have raised an exception because method was not called.");
}
- (void)testAcceptsAndVerifiesExpectedMethodsWithDelayBlockTimeout
{
dispatch_async(dispatch_queue_create("mockqueue", nil), ^{
[NSThread sleepForTimeInterval:1];
[mock lowercaseString];
});
[[mock expect] lowercaseString];
XCTAssertThrows([mock verifyWithDelay:0.1], @"Should have raised an exception because method was not called.");
}
// --------------------------------------------------------------------------------------
// ordered expectations
// --------------------------------------------------------------------------------------
- (void)testAcceptsExpectedMethodsInRecordedSequenceWhenOrderMatters
{
[mock setExpectationOrderMatters:YES];
[[mock expect] lowercaseString];
[[mock expect] uppercaseString];
XCTAssertNoThrow([mock lowercaseString], @"Should have accepted expected method in sequence.");
XCTAssertNoThrow([mock uppercaseString], @"Should have accepted expected method in sequence.");
}
- (void)testRaisesExceptionWhenSequenceIsWrongAndOrderMatters
{
[mock setExpectationOrderMatters:YES];
[[mock expect] lowercaseString];
[[mock expect] uppercaseString];
XCTAssertThrows([mock uppercaseString], @"Should have complained about wrong sequence.");
}
- (void)testRejectThenExpectWithExpectationOrdering
{
[mock setExpectationOrderMatters:YES];
[[mock reject] lowercaseString];
[[mock expect] uppercaseString];
XCTAssertNoThrow([mock uppercaseString], @"Since lowercaseString should be rejected, we shouldn't expect it to be called before uppercaseString.");
}
// --------------------------------------------------------------------------------------
// nice mocks don't complain about unknown methods, unless told to
// --------------------------------------------------------------------------------------
- (void)testReturnsDefaultValueWhenUnknownMethodIsCalledOnNiceClassMock
{
mock = [OCMockObject niceMockForClass:[NSString class]];
XCTAssertNil([mock lowercaseString], @"Should return nil on unexpected method call (for nice mock).");
[mock verify];
}
- (void)testRaisesAnExceptionWhenAnExpectedMethodIsNotCalledOnNiceClassMock
{
mock = [OCMockObject niceMockForClass:[NSString class]];
[[[mock expect] andReturn:@"HELLO!"] uppercaseString];
XCTAssertThrows([mock verify], @"Should have raised an exception because method was not called.");
}
- (void)testThrowsWhenRejectedMethodIsCalledOnNiceMock
{
mock = [OCMockObject niceMockForClass:[NSString class]];
[[mock reject] uppercaseString];
XCTAssertThrows([mock uppercaseString], @"Should have complained about rejected method being called.");
}
- (void)testUncalledRejectStubDoesNotCountAsExpectation
{
mock = [OCMockObject niceMockForClass:[NSString class]];
[[mock expect] lowercaseString];
[[mock reject] uppercaseString];
[mock lowercaseString];
XCTAssertNoThrow([mock verify], @"Should not have any unmet expectations.");
}
// --------------------------------------------------------------------------------------
// some internal tests
// --------------------------------------------------------------------------------------
- (void)testReRaisesFailFastExceptionsOnVerify
{
@try
{
[mock lowercaseString];
}
@catch(NSException *exception)
{
// expected
}
XCTAssertThrows([mock verify], @"Should have reraised the exception.");
}
- (void)testReRaisesRejectExceptionsOnVerify
{
mock = [OCMockObject niceMockForClass:[NSString class]];
[[mock reject] uppercaseString];
@try
{
[mock uppercaseString];
}
@catch(NSException *exception)
{
// expected
}
XCTAssertThrows([mock verify], @"Should have reraised the exception.");
}
- (void)testCanCreateExpectationsAfterInvocations
{
[[mock expect] lowercaseString];
[mock lowercaseString];
[mock expect];
}
- (void)testArgumentConstraintsAreOnlyCalledAsOftenAsTheMethodIsCalled
{
__block int count = 0;
[[mock stub] hasSuffix:[OCMArg checkWithBlock:^(id value) { count++; return YES; }]];
[mock hasSuffix:@"foo"];
[mock hasSuffix:@"bar"];
XCTAssertEqual(2, count, @"Should have evaluated constraint only twice");
}
@end