-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathConstraintExample.cs
More file actions
996 lines (843 loc) · 38.5 KB
/
ConstraintExample.cs
File metadata and controls
996 lines (843 loc) · 38.5 KB
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
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
// Copyright (c) 2021-2023 Koji Hasegawa.
// This software is released under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using NUnit.Framework;
using NUnit.Framework.Constraints;
using UnityEngine;
using UnityEngine.TestTools;
using AssertionException = UnityEngine.Assertions.AssertionException;
#if UNITY_EDITOR
using UnityEditor;
#endif
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
// ReSharper disable AccessToStaticMemberViaDerivedType
// ReSharper disable ConditionIsAlwaysTrueOrFalse
// ReSharper disable ExpressionIsAlwaysNull
// ReSharper disable ConvertClosureToMethodGroup
namespace APIExamples.NUnit
{
/// <summary>
/// <see cref="Constraint"/>の記述例
/// </summary>
/// <remarks>
/// ネストしたTestFixtureは、Test Runnerウィンドウの"Run Selected"で個別実行できない場合があります
/// </remarks>
[TestFixture]
public class ConstraintExample
{
[TestFixture]
public class 等価
{
[Test]
public void EqualConstraint_文字列が等しいこと()
{
var actual = "Semper Paratus!";
Assert.That(actual, Is.EqualTo("Semper Paratus!"));
// 失敗時メッセージ例:
// String lengths are both 15. Strings differ at index 7.
// Expected: "Semper Paratus!"
// But was: "Semper paratus!"
// ------------------^
}
[Test]
public void EqualConstraint_文字列比較にIgnoreCase修飾子を使用_大文字小文字を無視して比較()
{
var actual = "semper paratus!";
Assert.That(actual, Is.EqualTo("Semper Paratus!").IgnoreCase);
// 失敗時メッセージ例:
// String lengths are both 15. Strings differ at index 3.
// Expected: "Semper Paratus!", ignoring case
// But was: "sember paratus!"
// --------------^
}
[Test]
public void EqualConstraint_文字列比較にNoClip修飾子を使用_失敗時メッセージがクリップされず出力される()
{
var actual = "Spam, spam, spam, spam, spam, spam, spam, spam, lovely spam! Wonderful spam!";
Assert.That(actual,
Is.EqualTo("Spam, spam, spam, spam, spam, spam, spam, spam, lovely spam! Wonderful spam!").NoClip);
// 失敗時メッセージ例:
// Expected string length 76 but was 82. Strings differ at index 48.
// Expected: "Spam, spam, spam, spam, spam, spam, spam, spam, lovely spam! Wonderful spam!"
// But was: "Spam, spam, spam, spam, spam, spam, spam, spam, spam, lovely spam! Wonderful spam!"
// -----------------------------------------------------------^
// 失敗時メッセージ例(NoClipなしの場合):
// Expected string length 76 but was 82. Strings differ at index 48.
// Expected: "...m, spam, spam, spam, spam, lovely spam! Wonderful spam!"
// But was: "...m, spam, spam, spam, spam, spam, lovely spam! Wonderful spam!"
// -----------------------------------------^
}
[Test]
public void EqualConstraint_数値が等しいこと()
{
var actual = 42;
Assert.That(actual, Is.EqualTo(42));
// 失敗時メッセージ例:
// Expected: 42
// But was: 41
}
[Test]
public void EqualConstraint_数値比較にWithin修飾子を使用_誤差を許容()
{
var actual = 42;
Assert.That(actual, Is.EqualTo(44.0f).Within(2)); // +/- 2まで許容
Assert.That(actual, Is.EqualTo(44.0f).Within(5).Percent); // +/- 5%まで許容
// 失敗時メッセージ例:
// Expected: 44.0f +/- 5 Percent
// But was: 41
}
[Test]
public void EqualConstraint_浮動小数点比較にWithin修飾子を使用_丸め誤差を許容()
{
var actual = 20000000000000004.0d;
Assert.That(actual, Is.EqualTo(20000000000000000.0d).Within(1).Ulps); // ULPs: Units in the Last Place
// 失敗時メッセージ例:
// Expected: 20000000000000000.0d +/- 1 Ulps
// But was: 20000000000000008.0d
}
[Test]
public void EqualConstraint_日時比較にWithin修飾子を使用_誤差を許容()
{
var actual = new DateTime(2021, 7, 25, 0, 0, 0, 0);
Assert.That(actual, Is.EqualTo(
new DateTime(2021, 7, 25, 0, 5, 0, 0)).Within(TimeSpan.FromSeconds(300))); // +/- 300秒まで許容
Assert.That(actual, Is.EqualTo(
new DateTime(2021, 7, 24, 22, 00, 0, 0)).Within(120).Minutes); // +/- 120分まで許容
Assert.That(actual, Is.EqualTo(
new DateTime(2021, 7, 10, 10, 0, 0, 0)).Within(15).Days); // +/- 15日まで許容
// 失敗時メッセージ例:
// Expected: 2021-07-10 10:00:00.000 +/- 15.00:00:00
// But was: 2021-07-25 23:59:59.999
}
[Test]
public void EqualConstraint_配列が等しいこと()
{
var actual = new[] { "Katsuro", "Jenny", "Lindsay" };
Assert.That(actual, Is.EqualTo(new[] { "Katsuro", "Jenny", "Lindsay" }));
// 失敗時メッセージ例:
// Expected and actual are both <System.String[3]>
// Values differ at index [1]
// Expected string length 5 but was 7. Strings differ at index 0.
// Expected: "Jenny"
// But was: "Lindsay"
// -----------^
}
[Test]
public void EqualConstraint_要素数の異なるコレクションにAsCollection修飾子を使用()
{
var actual = new[,] { { 2, 3 }, { 5, 6 } };
var expected = new[] { 2, 3, 5, 6 };
Assert.That(actual, Is.EqualTo(expected).AsCollection);
// 失敗時メッセージ例:
// Expected is <System.Int32[4]>, actual is <System.Int32[3,2]>
// Values differ at expected index [2], actual index [1,0]
// Expected: 5
// But was: 4
}
[Test]
public void SameAsConstraint_オブジェクトが同一であるとみなせること()
{
var actual = new ArgumentException();
var expected = actual;
Assert.That(actual, Is.SameAs(expected));
// 失敗時メッセージ例:
// Expected: same as <System.ArgumentException: Value does not fall within the expected range.>
// But was: <System.ArgumentException: Value does not fall within the expected range.>
}
}
[TestFixture]
public class コレクション
{
[Test]
public void AllItemsConstraint_すべての要素が条件を満たすこと()
{
var actual = new[] { 2, 3, 5, 6 };
Assert.That(actual, Is.All.InstanceOf<int>());
Assert.That(actual, Is.All.GreaterThanOrEqualTo(2));
Assert.That(actual, Is.All.LessThanOrEqualTo(6));
Assert.That(actual, Is.All.Not.EqualTo(4));
// 失敗時メッセージ例:
// Expected: all items not equal to 4
// But was: < 2, 3, 4, 5, 6 >
}
// AnyOfConstraint は未実装
[Test]
public void CollectionContainsConstraint_要素に含まれること()
{
var actual = new[] { "Katsuro", "Jenny", "Lindsay" };
Assert.That(actual, Has.Member("Katsuro"));
Assert.That(actual, Contains.Item("Jenny"));
Assert.That(actual, Does.Contain("Lindsay"));
// 失敗時メッセージ例:
// Expected: collection containing "Lindsay"
// But was: < "Katsuro", "Jenny" >
// SomeItemsConstraint も使用できます
}
[Test]
public void CollectionEquivalentConstraint_要素が順不同で一致すること()
{
var actual = new[] { "Katsuro", "Jenny", "Lindsay" };
Assert.That(actual, Is.EquivalentTo(new[] { "Jenny", "Lindsay", "Katsuro" }));
// 失敗時メッセージ例:
// Expected: equivalent to < "Jenny", "Lindsay", "Katsuro" >
// But was: < "Bill", "Jenny", "Lindsay" >
}
[Test]
public void CollectionOrderedConstraint_要素がソートされていること()
{
var ascended = new[] { 2, 3, 5, 6 };
var descended = new[] { 6, 5, 3, 2 };
Assert.That(ascended, Is.Ordered);
Assert.That(descended, Is.Ordered.Descending);
// 失敗時メッセージ例:
// Expected: collection ordered, descending
// But was: < 6, 5, 3, 4 >
}
[Test]
public void CollectionSubsetConstraint_サブセットであること()
{
var actual = new[] { 2, 3 };
Assert.That(actual, Is.SubsetOf(new[] { 2, 3, 5, 6 }));
// 失敗時メッセージ例:
// Expected: subset of < 2, 3, 5, 6 >
// But was: < 2, 3, 4 >
}
[Test]
public void CollectionSupersetConstraint_スーパーセットであること()
{
var actual = new[] { 4, 5, 6, 1, 2, 3, 7, 8, 9 };
Assert.That(actual, Is.SupersetOf(new[] { 2, 3, 5, 6 }));
// 失敗時メッセージ例:
// Expected: superset of < 2, 3, 5, 6 >
// But was: < 4, 5, 6, 7, 8, 9 >
}
[Test]
public void DictionaryContainsKeyConstraint_Dictionaryにキーが含まれること()
{
var actual = new Dictionary<int, string>
{
{ 1, "Aquatica" }, { 2, "Akheilos" }, { 3, "Little Happy" },
};
Assert.That(actual, Contains.Key(3));
// 失敗時メッセージ例:
// Expected: dictionary containing key 3
// But was: < [1, Aquatica], [2, Akheilos] >
// Does.ContainKey(object) は未実装
// Does.Not.ContainKey(object) は未実装
}
// DictionaryContainsKeyValuePairConstraint は未実装
[Test]
public void DictionaryContainsValueConstraint_Dictionaryに値が含まれること()
{
var actual = new Dictionary<int, string>
{
{ 1, "Aquatica" }, { 2, "Akheilos" }, { 3, "Little Happy" },
};
Assert.That(actual, Contains.Value("Little Happy"));
// 失敗時メッセージ例:
// Expected: dictionary containing value "Little Happy"
// But was: < [1, Aquatica], [2, Akheilos] >
// Does.ContainValue(object) は未実装
// Does.Not.ContainValue(object) は未実装
}
[Test]
public void EmptyConstraint_要素が空であること()
{
var actual = new int[] { };
Assert.That(actual, Is.Empty);
// 失敗時メッセージ例:
// Expected: <empty>
// But was: < 0 >
}
[Test]
public void HasCount_コレクションの個数を検証()
{
var actual = new List<int> { 2, 3, 5, 6 };
Assert.That(actual, Has.Count.EqualTo(4));
// 失敗時メッセージ例:
// Expected: property Count equal to 4
// But was: 5
}
[Test]
public void HasLength_配列の個数を検証()
{
var actual = new int[] { 2, 3, 5, 6 };
Assert.That(actual, Has.Length.EqualTo(4));
// 失敗時メッセージ例:
// Expected: property Length equal to 4
// But was: 5
}
[Test]
public void ExactCountConstraint_条件を満たす要素数を検証する()
{
var actual = new[] { 2, 3, 5, 6 };
Assert.That(actual, Has.Exactly(3).GreaterThan(2), "2より大きい要素が3件あること");
// 失敗時メッセージ例:
// Expected: exactly 3 items greater than 2
// But was: < 2, 3, 4, 5, 6 >
}
[Test]
public void NoItemConstraint_条件を満たす要素が含まれないこと()
{
var actual = new[] { "Katsuro", "Jenny", "Lindsay" };
Assert.That(actual, Has.None.Null);
Assert.That(actual, Has.None.EqualTo("Bill"));
// 失敗時メッセージ例:
// Expected: no item equal to "Bill"
// But was: < "Bill", "Jenny", "Lindsay" >
}
[Test]
public void SomeItemsConstraint_条件を満たす要素が含まれること()
{
var actual = new[] { 2, 3, 5, 6 };
Assert.That(actual, Has.Some.GreaterThan(5));
// 失敗時メッセージ例:
// Expected: some item greater than 5
// But was: < 2, 3, 5 >
}
[Test]
public void UniqueItemsConstraint_重複する要素がないこと()
{
var actual = new[] { 2, 3, 5, 6 };
Assert.That(actual, Is.Unique);
// 失敗時メッセージ例:
// Expected: all items unique
// But was: < 2, 3, 5, 3 >
}
}
[TestFixture]
public class 比較
{
[Test]
public void GreaterThanConstraint_より大きい()
{
var actual = 42;
Assert.That(actual, Is.GreaterThan(41));
// 失敗時メッセージ例:
// Expected: greater than 41
// But was: 41
}
[Test]
public void GreaterThanOrEqualConstraint_以上()
{
var actual = 42;
Assert.That(actual, Is.GreaterThanOrEqualTo(42));
// 失敗時メッセージ例:
// Expected: greater than or equal to 42
// But was: 41
}
[Test]
public void LessThanConstraint_より小さい()
{
var actual = 42;
Assert.That(actual, Is.LessThan(43));
// 失敗時メッセージ例:
// Expected: less than 43
// But was: 43
}
[Test]
public void LessThanOrEqualConstraint_以下()
{
var actual = 42;
Assert.That(actual, Is.LessThanOrEqualTo(42));
// 失敗時メッセージ例:
// Expected: less than or equal to 42
// But was: 43
}
[Test]
public void RangeConstraint_範囲内()
{
var actual = 42;
Assert.That(actual, Is.InRange(40, 44));
// 失敗時メッセージ例:
// Expected: in range (40,44)
// But was: 39
}
}
[TestFixture]
public class 合成
{
[Test]
public void AndConstraint_AND条件()
{
var actual = 42;
Assert.That(actual, Is.GreaterThan(40).And.LessThan(44));
// 失敗時メッセージ例:
// Expected: greater than 40 and less than 44
// But was: 40
}
[Test]
public void AndConstraint_OR条件が優先される()
{
var actual = 0;
Assert.That(actual, Is.GreaterThan(40).And.LessThan(44).Or.EqualTo(0));
}
[Test]
public void NotConstraint_NOT条件()
{
var actual = 42;
Assert.That(actual, Is.Not.EqualTo(0));
// 失敗時メッセージ例:
// Expected: not equal to 0
// But was: 0
}
[Test]
public void OrConstraint_OR条件()
{
var actual = 42;
Assert.That(actual, Is.GreaterThan(40).Or.LessThan(30));
// 失敗時メッセージ例:
// Expected: greater than 40 or less than 30
// But was: 40
}
}
[TestFixture]
public class 条件
{
[Test]
public void EmptyConstraint_空であること()
{
var actual = "";
Assert.That(actual, Is.Empty);
// 失敗時メッセージ例:
// Expected: <empty>
// But was: "Semper Paratus!"
}
[Test]
public void FalseConstraint_Falseであること()
{
var actual = false;
Assert.That(actual, Is.False);
// 失敗時メッセージ例:
// Expected: False
// But was: True
}
[Test]
public void NaNConstraint_NaNであること()
{
var actual = float.NaN;
Assert.That(actual, Is.NaN);
// 失敗時メッセージ例:
// Expected: NaN
// But was: 42.0f
}
[Test]
public void NullConstraint_Nullであること()
{
string actual = null;
Assert.That(actual, Is.Null);
// 失敗時メッセージ例:
// Expected: null
// But was: <string.Empty>
}
[Test]
public void TrueConstraint_Trueであること()
{
var actual = true;
Assert.That(actual, Is.True);
Assert.That(actual); // Constraintなしのとき、TrueConstraintで評価される
// 失敗時メッセージ例:
// Expected: True
// But was: False
}
}
[TestFixture]
public class ファイルとディレクトリ
{
[Test]
[UnityPlatform(RuntimePlatform.LinuxEditor, RuntimePlatform.WindowsEditor, RuntimePlatform.OSXEditor)]
public void EmptyDirectoryConstraint_ディレクトリが空であること()
{
#if UNITY_EDITOR
var dir = FileUtil.GetUniqueTempPathInProject();
var actual = Directory.CreateDirectory(dir);
Assert.That(actual, Is.Empty);
// 失敗時メッセージ例:
// Expected: an empty directory
// But was: <UnityTempFile-113d9721b8aa84bb0a7bf0b6e31e2638>
Directory.Delete(dir, true);
#endif
}
[Test]
[UnityPlatform(RuntimePlatform.LinuxEditor, RuntimePlatform.WindowsEditor, RuntimePlatform.OSXEditor)]
public void FileOrDirectoryExistsConstraint_ファイルまたはディレクトリが存在すること()
{
#if UNITY_EDITOR
var dir = Path.GetFileName(FileUtil.GetUniqueTempPathInProject());
var directoryInfo = Directory.CreateDirectory(dir);
var file = Path.Combine(dir, "test");
var fileInfo = new FileInfo(file);
using (var writer = File.CreateText(file))
{
writer.Close();
}
Assert.That(directoryInfo, Does.Exist);
Assert.That(dir, Does.Exist.IgnoreFiles); // ファイルは除外する
Assert.That(fileInfo, Does.Exist);
Assert.That(file, Does.Exist.IgnoreDirectories); // ディレクトリは除外する
// 失敗時メッセージ例:
// Expected: file or directory exists
// But was: "Temp/UnityTempFile-ac03ee62865a042748c6f54723c2e51b/test"
Directory.Delete(dir, true);
#endif
}
[Test]
public void SamePathConstraint_パス文字列が等しいこと()
{
Assert.That("\\folder1\\.\\junk\\..\\folder2", Is.SamePath("/folder1/folder2"));
// 失敗時メッセージ例:
// Expected: Path matching "/folder1/folder2"
// But was: "\folder1\.\junk\..\folder2\xxx"
}
[Test]
public void SamePathConstraint_パス文字列が等しいこと_IgnoreCase修飾子も有効()
{
Assert.That("\\folder1\\.\\junk\\..\\Folder2", Is.SamePath("/Folder1/folder2").IgnoreCase);
// 失敗時メッセージ例:
// Expected: Path matching "/Folder1/folder2"
// But was: "\folder1\.\junk\..\Folder2"
}
[Test]
public void SamePathOrUnderConstraint_パス文字列が期待値と同じかその配下であること()
{
Assert.That("\\folder1\\.\\junk\\..\\folder2", Is.SamePathOrUnder("/folder1/folder2"));
Assert.That("\\folder1\\.\\junk\\..\\folder2\\folder3", Is.SamePathOrUnder("/folder1/folder2"));
// 失敗時メッセージ例:
// Expected: Path under or matching "/folder1/folder2"
// But was: "\folder1\.\junk\..\folder3\folder2"
}
[Test]
public void SamePathOrUnderConstraint_パス文字列が期待値と同じかその配下であること_IgnoreCase修飾子も有効()
{
Assert.That("\\folder1\\.\\junk\\..\\Folder2\\folder3",
Is.SamePathOrUnder("/Folder1/folder2").IgnoreCase);
// 失敗時メッセージ例:
// Expected: Path under or matching "/Folder1/folder2"
// But was: "\folder1\.\junk\..\Folder2\folder3"
}
[Test]
public void SubPathConstraint_パス文字列が期待値のサブパスであること()
{
Assert.That("/folder1/folder2/folder3", Is.SubPathOf("/folder1/folder2"));
// Note: 最新のNUnitでは`Is.SubPath()`で、実装も異なっている。NUnitのドキュメントにある例がNUnit 3.5では通らない
}
}
[TestFixture]
public class 文字列
{
[Test]
public void EmptyStringConstraint_空文字列であること()
{
var actual = "";
Assert.That(actual, Is.Empty);
// 失敗時メッセージ例:
// Expected: <empty>
// But was: "Semper Paratus!"
}
[Test]
public void EndsWithConstraint_末尾が一致すること()
{
var actual = "Semper Paratus!";
Assert.That(actual, Does.EndWith("s!"));
Assert.That(actual, Does.EndWith("S!").IgnoreCase);
// 失敗時メッセージ例:
// Expected: String ending with "s!"
// But was: "Semper Paratus!!"
}
[Test]
public void RegexConstraint_正規表現に適合すること()
{
var actual = "Semper Paratus!";
Assert.That(actual, Does.Match("^Sem.*s!$"));
Assert.That(actual, Does.Match("^sem.*s!$").IgnoreCase);
// 失敗時メッセージ例:
// Expected: String matching "^Sem.*s!$"
// But was: "Semper Paratus!!"
}
[Test]
public void StartsWithConstraint_先頭が一致すること()
{
var actual = "Semper Paratus!";
Assert.That(actual, Does.StartWith("Se"));
Assert.That(actual, Does.StartWith("se").IgnoreCase);
// 失敗時メッセージ例:
// Expected: String starting with "Se"
// But was: "Samper Paratus!"
}
[Test]
public void SubstringConstraint_文字列を含む()
{
var actual = "Semper Paratus!";
Assert.That(actual, Does.Contain("per"));
Assert.That(actual, Does.Contain("para").IgnoreCase);
// 失敗時メッセージ例:
// Expected: String containing "per"
// But was: "Sember Paratus!"
}
}
[TestFixture]
public class 型
{
private interface IFoo
{
}
private class Foo : IFoo
{
}
// ReSharper disable once ClassNeverInstantiated.Local
private class Bar : Foo
{
}
[Test]
public void AssignableFromConstraint_型が期待値と同じまたはスーパークラスであること()
{
var actual = new Foo();
Assert.That(actual, Is.Not.AssignableFrom<IFoo>());
Assert.That(actual, Is.AssignableFrom<Foo>());
Assert.That(actual, Is.AssignableFrom<Bar>());
// 失敗時メッセージ例:
// Expected: assignable from <APIExamples.NUnit.ConstraintExample+型+IFoo>
// But was: <APIExamples.NUnit.ConstraintExample+型+Foo>
}
[Test]
public void AssignableToConstraint_型が期待値と同じまたはサブクラスであること()
{
var actual = new Foo();
Assert.That(actual, Is.AssignableTo<IFoo>());
Assert.That(actual, Is.AssignableTo<Foo>());
Assert.That(actual, Is.Not.AssignableTo<Bar>());
// 失敗時メッセージ例:
// Expected: assignable to <APIExamples.NUnit.ConstraintExample+型+Bar>
// But was: <APIExamples.NUnit.ConstraintExample+型+Foo>
}
[Test]
public void ExactTypeConstraint_型が期待値と一致すること()
{
var actual = new Foo();
Assert.That(actual, Is.Not.TypeOf<IFoo>());
Assert.That(actual, Is.TypeOf<Foo>());
Assert.That(actual, Is.Not.TypeOf<Bar>());
// 失敗時メッセージ例:
// Expected: <APIExamples.NUnit.ConstraintExample+型+IFoo>
// But was: <APIExamples.NUnit.ConstraintExample+型+Foo>
}
[Test]
public void InstanceOfTypeConstraint_インスタンスの型が期待値と同じまたはサブクラスであること()
{
var actual = new Foo();
Assert.That(actual, Is.InstanceOf<IFoo>());
Assert.That(actual, Is.InstanceOf<Foo>());
Assert.That(actual, Is.Not.InstanceOf<Bar>());
// 失敗時メッセージ例:
// Expected: instance of <APIExamples.NUnit.ConstraintExample+型+Bar>
// But was: <APIExamples.NUnit.ConstraintExample+型+Foo>
}
}
[TestFixture]
public class 例外
{
[Test]
public void ThrowsConstraint_期待する例外がスローされる()
{
void GetThrow() => throw new ArgumentException();
Assert.That(() => GetThrow(), Throws.TypeOf<ArgumentException>());
// 失敗時メッセージ例:
// Expected: <System.ArgumentException>
// But was: <System.NullReferenceException>
}
[Test]
public void ThrowsConstraint_期待するメッセージを持つ例外がスローされる()
{
void GetThrowWithMessage() => throw new ArgumentException("Semper Paratus!");
Assert.That(() => GetThrowWithMessage(),
Throws.TypeOf<ArgumentException>().And.Message.EqualTo("Semper Paratus!"));
// 失敗時メッセージ例:
// Expected: <System.ArgumentException> and property Message equal to "Semper Paratus!"
// But was: "sember paratus!"
}
[Test]
public void ThrowsConstraint_UnityEngineのAssert失敗を期待する()
{
void GetAssert() => UnityEngine.Assertions.Assert.IsTrue(false);
Assert.That(() => GetAssert(), Throws.TypeOf<AssertionException>());
// 失敗時メッセージ例:
// Expected: <NUnit.Framework.AssertionException>
// But was: <UnityEngine.Assertions.AssertionException>
}
[Test]
public void ThrowsNothingConstraint_例外がスローされないことを期待する()
{
void GetNotThrow() { }
Assert.That(() => GetNotThrow(), Throws.Nothing);
// 失敗時メッセージ例:
// Expected: No Exception to be thrown
// But was: <System.NullReferenceException: Object reference not set to an instance of an object.
}
[Ignore("Throws制約をasyncメソッドに使用するとUnityエディターがフリーズ(Unity Test Framework v1.4.0時点)")]
[Test]
public async Task 非同期メソッドの例外捕捉を制約モデルで行なうことはできない_Unityエディターがフリーズ()
{
async Task GetThrowWithMessageAsync()
{
await Task.Yield();
throw new ArgumentException("message!");
}
Assert.That(async () => await GetThrowWithMessageAsync(),
Throws.TypeOf<ArgumentException>().And.Message.EqualTo("message!"));
// Note: 非同期(async)メソッドに対してThrows制約が使用できない
// See: https://unity3d.atlassian.net/servicedesk/customer/portal/2/IN-28107
}
[Ignore("ThrowsAsyncをasyncメソッドに使用するとUnityエディターがフリーズ(Unity Test Framework v1.4.0時点)")]
[Test]
public async Task 非同期メソッドの例外捕捉をクラシックモデルで行なうことはできない_Unityエディターがフリーズ()
{
async Task GetThrowWithMessageAsync()
{
await Task.Yield();
throw new ArgumentException("message!");
}
Assert.ThrowsAsync<ArgumentException>(async () => await GetThrowWithMessageAsync());
// Note: 非同期(async)メソッドに対してThrowsAsyncも使用できない
// Note: クラシックモデルではMessage文字列の評価はできない
}
[Test]
public async Task 非同期メソッドの例外捕捉をTryCatchで行なう例()
{
async Task GetThrowWithMessageAsync()
{
await Task.Yield();
throw new ArgumentException("message!");
}
try
{
await GetThrowWithMessageAsync();
Assert.Fail("例外が出ることを期待しているのでテスト失敗とする");
}
catch (ArgumentException expectedException)
{
Assert.That(expectedException.Message, Is.EqualTo("message!"));
}
}
}
[TestFixture, Description("Attribute and Property")]
public class 属性とプロパティ
{
public string Foo { get; } = "Bar";
[Test]
public void AttributeExistsConstraint_属性がつけられていること()
{
var actual = typeof(属性とプロパティ);
Assert.That(actual, Has.Attribute<DescriptionAttribute>());
// 失敗時メッセージ例:
// Expected: type with attribute <NUnit.Framework.DescriptionAttribute>
// But was: <APIExamples.NUnit.ConstraintExample+属性とプロパティ>
}
[Test]
public void PropertyExistsConstraint_プロパティを持っていること()
{
var actual = new 属性とプロパティ();
Assert.That(actual, Has.Property("Foo"));
// 失敗時メッセージ例:
// Expected: property Bar
// But was: <APIExamples.NUnit.ConstraintExample+属性とプロパティ>
}
[Test]
public void PropertyConstraint_プロパティの値が正しい()
{
var actual = new 属性とプロパティ();
Assert.That(actual, Has.Property("Foo").EqualTo("Bar"));
// 失敗時メッセージ例:
// Expected: property Foo equal to "Bar"
// But was: "Baz"
}
}
[TestFixture]
public class シリアル化
{
[Serializable]
private class BinarySerializableSample
{
// ReSharper disable once UnusedMember.Local
public string S { get; set; } = "Semper Paratus!";
}
[Test]
public void BinarySerializableConstraint_バイナリシリアル化が可能であること()
{
var actual = new BinarySerializableSample();
Assert.That(actual, Is.BinarySerializable);
// 失敗時メッセージ例:
// Expected: binary serializable
// But was: <APIExamples.NUnit.ConstraintExample+シリアル化+BinarySerializableSample>
}
// ReSharper disable once MemberCanBePrivate.Global
public class XmlSerializableSample
{
public string S { get; set; } = "Semper Paratus!";
}
[Test]
public void XmlSerializableConstraint_XMLシリアル化が可能であること()
{
var actual = new XmlSerializableSample();
Assert.That(actual, Is.XmlSerializable);
// 失敗時メッセージ例:
// Expected: xml serializable
// But was: <APIExamples.NUnit.ConstraintExample+シリアル化+XmlSerializableSample>
}
}
[TestFixture]
public class 破棄されたGameObject
{
[Test]
[UnityPlatform(RuntimePlatform.OSXEditor, RuntimePlatform.WindowsEditor, RuntimePlatform.LinuxEditor)]
// Note: プレイヤーではnull判定されるため除外
public void Boolキャストオペレーターで破棄されたGameObjectを検証する例()
{
var cube = new GameObject("Cube");
GameObject.DestroyImmediate(cube);
Assume.That(cube, Is.Not.Null); // Note: 破棄されていても参照はnullではない
Assert.That((bool)cube, Is.False); // Note: GameObjectが破棄されているとき、boolキャストオペレーターはfalseを返す
}
}
[TestFixture]
public class 遅延
{
[Test]
[Explicit("Test属性のテストでは期待通り動作しないので除外")]
public void DelayedConstraint_Test属性のテストでは無効()
{
var start = Time.time; // The time at the beginning of this frame
Assert.That(() => Time.time, Is.GreaterThan(start + 2.0f).After(2500)); // ミリ秒しか指定できない模様
// 失敗時メッセージ例:
// Expected: greater than 2.33228302f after 2500 millisecond delay
// But was: 0.33228299f
}
[Test]
[Explicit("Asyncテストでも期待通り動作しないので除外(Unity Test Framework v1.4.0時点)")]
// https://unity3d.atlassian.net/servicedesk/customer/portal/2/IN-30529
public async Task DelayedConstraint_AsyncTestでも無効()
{
var start = Time.time; // The time at the beginning of this frame
await Task.Delay(0);
Assert.That(() => Time.time, Is.GreaterThan(start + 2.0f).After(2500)); // ミリ秒しか指定できない模様
// 失敗時メッセージ例:
// Expected: greater than 2.33228302f after 2500 millisecond delay
// But was: 0.33228299f
}
[UnityTest]
[Explicit("UnityTest属性のテストでも期待通り動作しないので除外")]
public IEnumerator DelayedConstraint_UnityTest属性のテストでも無効()
{
var start = Time.time; // The time at the beginning of this frame
yield return null;
Assert.That(() => Time.time, Is.GreaterThan(start + 2.0f).After(2500)); // ミリ秒しか指定できない模様
// 失敗時メッセージ例:
// Expected: greater than 2.39063787f after 2500 millisecond delay
// But was: 0.390637904f
}
}
}
}