How to use TestSameValueDifferentTypeUsingGenericTypes method of ExampleTest.DummyGenericClass class

Best Nunit code snippet using ExampleTest.DummyGenericClass.TestSameValueDifferentTypeUsingGenericTypes

Run Nunit automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

EqualConstraintTests.cs

Source: EqualConstraintTests.cs Github

copy
1// ***********************************************************************
2// Copyright (c) 2007-2013 Charlie Poole, Rob Prouse
3//
4// Permission is hereby granted, free of charge, to any person obtaining
5// a copy of this software and associated documentation files (the
6// "Software"), to deal in the Software without restriction, including
7// without limitation the rights to use, copy, modify, merge, publish,
8// distribute, sublicense, and/or sell copies of the Software, and to
9// permit persons to whom the Software is furnished to do so, subject to
10// the following conditions:
11//
12// The above copyright notice and this permission notice shall be
13// included in all copies or substantial portions of the Software.
14//
15// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22// ***********************************************************************
23
24using System;
25using System.Collections;
26using System.Collections.Generic;
27using System.Globalization;
28using NUnit.Framework.Internal;
29using NUnit.TestUtilities.Comparers;
30
31namespace NUnit.Framework.Constraints
32{
33    [TestFixture]
34    public class EqualConstraintTests : ConstraintTestBase
35    {
36        [SetUp]
37        public void SetUp()
38        {
39            theConstraint = new EqualConstraint(4);
40            expectedDescription = "4";
41            stringRepresentation = "<equal 4>";
42        }
43
44        static object[] SuccessData = new object[] {4, 4.0f, 4.0d, 4.0000m};
45
46        static object[] FailureData = new object[]
47            {
48                new TestCaseData(5, "5"),
49                new TestCaseData(null, "null"),
50                new TestCaseData("Hello", "\"Hello\""),
51                new TestCaseData(double.NaN, double.NaN.ToString()),
52                new TestCaseData(double.PositiveInfinity, double.PositiveInfinity.ToString())
53            };
54
55        #region DateTimeEquality
56
57        public class DateTimeEquality
58        {
59            [Test]
60            public void CanMatchDates()
61            {
62                DateTime expected = new DateTime(2007, 4, 1);
63                DateTime actual = new DateTime(2007, 4, 1);
64                Assert.That(actual, new EqualConstraint(expected));
65            }
66
67            [Test]
68            public void CanMatchDatesWithinTimeSpan()
69            {
70                DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0);
71                DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0);
72                TimeSpan tolerance = TimeSpan.FromMinutes(5.0);
73                Assert.That(actual, new EqualConstraint(expected).Within(tolerance));
74            }
75
76            [Test]
77            public void CanMatchDatesWithinDays()
78            {
79                DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0);
80                DateTime actual = new DateTime(2007, 4, 4, 13, 0, 0);
81                Assert.That(actual, new EqualConstraint(expected).Within(5).Days);
82            }
83
84            [Test]
85            public void CanMatchDatesWithinHours()
86            {
87                DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0);
88                DateTime actual = new DateTime(2007, 4, 1, 16, 0, 0);
89                Assert.That(actual, new EqualConstraint(expected).Within(5).Hours);
90            }
91
92
93            [Test]
94            public void CanMatchUsingIsEqualToWithinTimeSpan()
95            {
96                DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0);
97                DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0);
98                Assert.That(actual, Is.EqualTo(expected).Within(TimeSpan.FromMinutes(2)));
99            }
100
101
102            [Test]
103            public void CanMatchDatesWithinMinutes()
104            {
105                DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0);
106                DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0);
107                Assert.That(actual, new EqualConstraint(expected).Within(5).Minutes);
108            }
109
110            [Test]
111            public void CanMatchTimeSpanWithinMinutes()
112            {
113                TimeSpan expected = new TimeSpan(10, 0, 0);
114                TimeSpan actual = new TimeSpan(10, 2, 30);
115                Assert.That(actual, new EqualConstraint(expected).Within(5).Minutes);
116            }
117
118            [Test]
119            public void CanMatchDatesWithinSeconds()
120            {
121                DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0);
122                DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0);
123                Assert.That(actual, new EqualConstraint(expected).Within(300).Seconds);
124            }
125
126            [Test]
127            public void CanMatchDatesWithinMilliseconds()
128            {
129                DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0);
130                DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0);
131                Assert.That(actual, new EqualConstraint(expected).Within(300000).Milliseconds);
132            }
133
134            [Test]
135            public void CanMatchDatesWithinTicks()
136            {
137                DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0);
138                DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0);
139                Assert.That(actual, new EqualConstraint(expected).Within(TimeSpan.TicksPerMinute*5).Ticks);
140            }
141
142            [Test]
143            public void ErrorIfDaysPrecedesWithin()
144            {
145                Assert.Throws<InvalidOperationException>(() => Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Days.Within(5)));
146            }
147
148            [Test]
149            public void ErrorIfHoursPrecedesWithin()
150            {
151                Assert.Throws<InvalidOperationException>(() => Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Hours.Within(5)));
152            }
153
154            [Test]
155            public void ErrorIfMinutesPrecedesWithin()
156            {
157                Assert.Throws<InvalidOperationException>(() => Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Minutes.Within(5)));
158            }
159
160            [Test]
161            public void ErrorIfSecondsPrecedesWithin()
162            {
163                Assert.Throws<InvalidOperationException>(() => Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Seconds.Within(5)));
164            }
165
166            [Test]
167            public void ErrorIfMillisecondsPrecedesWithin()
168            {
169                Assert.Throws<InvalidOperationException>(() => Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Milliseconds.Within(5)));
170            }
171
172            [Test]
173            public void ErrorIfTicksPrecedesWithin()
174            {
175                Assert.Throws<InvalidOperationException>(() => Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Ticks.Within(5)));
176            }
177        }
178
179        #endregion
180
181        #region DateTimeOffsetEquality
182
183        public class DateTimeOffsetShouldBeSame
184        {
185
186            [Datapoints]
187            public static readonly DateTimeOffset[] sameDateTimeOffsets =
188                {
189                    new DateTimeOffset(new DateTime(2014, 1, 30, 12, 34, 56), new TimeSpan(6, 15, 0)),
190                    new DateTimeOffset(new DateTime(2014, 1, 30, 9, 19, 56), new TimeSpan(3, 0, 0)),
191                    new DateTimeOffset(new DateTime(2014, 1, 30, 9, 19, 56), new TimeSpan(3, 1, 0)),
192                    new DateTimeOffset(new DateTime(2014, 1, 30, 9, 19, 55), new TimeSpan(3, 0, 0)),
193                    new DateTimeOffset(new DateTime(2014, 1, 30, 9, 19, 55), new TimeSpan(3, 50, 0))
194                };
195
196            [Theory]
197            public void PositiveEqualityTest(DateTimeOffset value1, DateTimeOffset value2)
198            {
199                Assume.That(value1 == value2);
200
201                Assert.That(value1, Is.EqualTo(value2));
202            }
203
204            [Theory]
205            public void NegativeEqualityTest(DateTimeOffset value1, DateTimeOffset value2)
206            {
207                Assume.That(value1 != value2);
208
209                Assert.That(value1, Is.Not.EqualTo(value2));
210            }
211
212            [Theory]
213            public void PositiveEqualityTestWithTolerance(DateTimeOffset value1, DateTimeOffset value2)
214            {
215                Assume.That((value1 - value2).Duration() <= new TimeSpan(0, 1, 0));
216
217                Assert.That(value1, Is.EqualTo(value2).Within(1).Minutes);
218            }
219
220            [Theory]
221            public void NegativeEqualityTestWithTolerance(DateTimeOffset value1, DateTimeOffset value2)
222            {
223                Assume.That((value1 - value2).Duration() > new TimeSpan(0, 1, 0));
224
225                Assert.That(value1, Is.Not.EqualTo(value2).Within(1).Minutes);
226            }
227
228            [Theory]
229            public void NegativeEqualityTestWithToleranceAndWithSameOffset(DateTimeOffset value1, DateTimeOffset value2)
230            {
231                Assume.That((value1 - value2).Duration() > new TimeSpan(0, 1, 0));
232
233                Assert.That(value1, Is.Not.EqualTo(value2).Within(1).Minutes.WithSameOffset);
234            }
235
236            [Theory]
237            public void PositiveEqualityTestWithToleranceAndWithSameOffset(DateTimeOffset value1, DateTimeOffset value2)
238            {
239                Assume.That((value1 - value2).Duration() <= new TimeSpan(0, 1, 0));
240                Assume.That(value1.Offset == value2.Offset);
241
242                Assert.That(value1, Is.EqualTo(value2).Within(1).Minutes.WithSameOffset);
243            }
244
245            [Theory]
246            public void NegativeEqualityTestWithinToleranceAndWithSameOffset(DateTimeOffset value1, DateTimeOffset value2)
247            {
248                Assume.That((value1 - value2).Duration() <= new TimeSpan(0, 1, 0));
249                Assume.That(value1.Offset != value2.Offset);
250
251                Assert.That(value1, Is.Not.EqualTo(value2).Within(1).Minutes.WithSameOffset);
252            }
253        }
254
255        public class DateTimeOffSetEquality
256        {
257            [Test]
258            public void CanMatchDates()
259            {
260                var expected = new DateTimeOffset(new DateTime(2007, 4, 1));
261                var actual = new DateTimeOffset(new DateTime(2007, 4, 1));
262                Assert.That(actual, new EqualConstraint(expected));
263            }
264
265            [Test]
266            public void CanMatchDatesWithinTimeSpan()
267            {
268                var expected = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 0, 0));
269                var actual = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 1, 0));
270                var tolerance = TimeSpan.FromMinutes(5.0);
271                Assert.That(actual, new EqualConstraint(expected).Within(tolerance));
272            }
273
274            [Test]
275            public void CanMatchDatesWithinDays()
276            {
277                var expected = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 0, 0));
278                var actual = new DateTimeOffset(new DateTime(2007, 4, 4, 13, 0, 0));
279                Assert.That(actual, new EqualConstraint(expected).Within(5).Days);
280            }
281
282            [Test]
283            public void CanMatchUsingIsEqualToWithinTimeSpan()
284            {
285                var expected = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 0, 0));
286                var actual = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 1, 0));
287                Assert.That(actual, Is.EqualTo(expected).Within(TimeSpan.FromMinutes(2)));
288            }
289
290            [Test]
291            public void CanMatchDatesWithinMinutes()
292            {
293                var expected = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 0, 0));
294                var actual =  new DateTimeOffset(new DateTime(2007, 4, 1, 13, 1, 0));
295                Assert.That(actual, new EqualConstraint(expected).Within(5).Minutes);
296            }
297
298            [Test]
299            public void CanMatchDatesWithinSeconds()
300            {
301                var expected = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 0, 0));
302                var actual =  new DateTimeOffset(new DateTime(2007, 4, 1, 13, 1, 0));
303                Assert.That(actual, new EqualConstraint(expected).Within(300).Seconds);
304            }
305
306            [Test]
307            public void CanMatchDatesWithinMilliseconds()
308            {
309                var expected = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 0, 0));
310                var actual =  new DateTimeOffset(new DateTime(2007, 4, 1, 13, 1, 0));
311                Assert.That(actual, new EqualConstraint(expected).Within(300000).Milliseconds);
312            }
313
314            [Test]
315            public void CanMatchDatesWithinTicks()
316            {
317                var expected = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 0, 0));
318                var actual =  new DateTimeOffset(new DateTime(2007, 4, 1, 13, 1, 0));
319                Assert.That(actual, new EqualConstraint(expected).Within(TimeSpan.TicksPerMinute*5).Ticks);
320            }
321
322            [Test]
323            public void DTimeOffsetCanMatchDatesWithinHours()
324            {
325                var a = DateTimeOffset.Parse("2012-01-01T12:00Z");
326                var b = DateTimeOffset.Parse("2012-01-01T12:01Z");
327                Assert.That(a, Is.EqualTo(b).Within(TimeSpan.FromMinutes(2)));
328            }
329        }
330
331        #endregion
332
333        #region DictionaryEquality
334
335        public class DictionaryEquality
336        {
337            [Test]
338            public void CanMatchDictionaries_SameOrder()
339            {
340                Assert.AreEqual(new Dictionary<int, int> {{0, 0}, {1, 1}, {2, 2}},
341                                new Dictionary<int, int> {{0, 0}, {1, 1}, {2, 2}});
342            }
343
344            [Test]
345            public void CanMatchDictionaries_Failure()
346            {
347                Assert.Throws<AssertionException>(
348                    () => Assert.AreEqual(new Dictionary<int, int> {{0, 0}, {1, 1}, {2, 2}},
349                                          new Dictionary<int, int> {{0, 0}, {1, 5}, {2, 2}}));
350            }
351
352            [Test]
353            public void CanMatchDictionaries_DifferentOrder()
354            {
355                Assert.AreEqual(new Dictionary<int, int> {{0, 0}, {1, 1}, {2, 2}},
356                                new Dictionary<int, int> {{0, 0}, {2, 2}, {1, 1}});
357            }
358
359#if !NETSTANDARD1_3 && !NETSTANDARD1_6
360            [Test]
361            public void CanMatchHashtables_SameOrder()
362            {
363                Assert.AreEqual(new Hashtable {{0, 0}, {1, 1}, {2, 2}},
364                                new Hashtable {{0, 0}, {1, 1}, {2, 2}});
365            }
366
367            [Test]
368            public void CanMatchHashtables_Failure()
369            {
370                Assert.Throws<AssertionException>(
371                    () => Assert.AreEqual(new Hashtable {{0, 0}, {1, 1}, {2, 2}},
372                                          new Hashtable {{0, 0}, {1, 5}, {2, 2}}));
373            }
374
375            [Test]
376            public void CanMatchHashtables_DifferentOrder()
377            {
378                Assert.AreEqual(new Hashtable {{0, 0}, {1, 1}, {2, 2}},
379                                new Hashtable {{0, 0}, {2, 2}, {1, 1}});
380            }
381
382            [Test]
383            public void CanMatchHashtableWithDictionary()
384            {
385                Assert.AreEqual(new Hashtable {{0, 0}, {1, 1}, {2, 2}},
386                                new Dictionary<int, int> {{0, 0}, {2, 2}, {1, 1}});
387            }
388#endif
389        }
390
391        #endregion
392
393        #region FloatingPointEquality
394
395        public class FloatingPointEquality
396        {
397            [TestCase(double.NaN)]
398            [TestCase(double.PositiveInfinity)]
399            [TestCase(double.NegativeInfinity)]
400            [TestCase(float.NaN)]
401            [TestCase(float.PositiveInfinity)]
402            [TestCase(float.NegativeInfinity)]
403            public void CanMatchSpecialFloatingPointValues(object value)
404            {
405                Assert.That(value, new EqualConstraint(value));
406            }
407
408            [TestCase(20000000000000004.0)]
409            [TestCase(19999999999999996.0)]
410            public void CanMatchDoublesWithUlpTolerance(object value)
411            {
412                Assert.That(value, new EqualConstraint(20000000000000000.0).Within(1).Ulps);
413            }
414
415            [TestCase(20000000000000008.0)]
416            [TestCase(19999999999999992.0)]
417            public void FailsOnDoublesOutsideOfUlpTolerance(object value)
418            {
419                var ex = Assert.Throws<AssertionException>(() => Assert.That(value, new EqualConstraint(20000000000000000.0).Within(1).Ulps));
420                Assert.That(ex.Message, Does.Contain("+/- 1 Ulps"));
421            }
422
423            [TestCase(19999998.0f)]
424            [TestCase(20000002.0f)]
425            public void CanMatchSinglesWithUlpTolerance(object value)
426            {
427                Assert.That(value, new EqualConstraint(20000000.0f).Within(1).Ulps);
428            }
429
430            [TestCase(19999996.0f)]
431            [TestCase(20000004.0f)]
432            public void FailsOnSinglesOutsideOfUlpTolerance(object value)
433            {
434                var ex = Assert.Throws<AssertionException>(() => Assert.That(value, new EqualConstraint(20000000.0f).Within(1).Ulps));
435                Assert.That(ex.Message, Does.Contain("+/- 1 Ulps"));
436            }
437
438            [TestCase(9500.0)]
439            [TestCase(10000.0)]
440            [TestCase(10500.0)]
441            public void CanMatchDoublesWithRelativeTolerance(object value)
442            {
443                Assert.That(value, new EqualConstraint(10000.0).Within(10.0).Percent);
444            }
445
446            [TestCase(8500.0)]
447            [TestCase(11500.0)]
448            public void FailsOnDoublesOutsideOfRelativeTolerance(object value)
449            {
450                var ex = Assert.Throws<AssertionException>(() => Assert.That(value, new EqualConstraint(10000.0).Within(10.0).Percent));
451                Assert.That(ex.Message, Does.Contain("+/- 10.0d Percent"));
452            }
453
454            [TestCase(9500.0f)]
455            [TestCase(10000.0f)]
456            [TestCase(10500.0f)]
457            public void CanMatchSinglesWithRelativeTolerance(object value)
458            {
459                Assert.That(value, new EqualConstraint(10000.0f).Within(10.0f).Percent);
460            }
461
462            [TestCase(8500.0f)]
463            [TestCase(11500.0f)]
464            public void FailsOnSinglesOutsideOfRelativeTolerance(object value)
465            {
466                var ex = Assert.Throws<AssertionException>(() => Assert.That(value, new EqualConstraint(10000.0f).Within(10.0f).Percent));
467                Assert.That(ex.Message, Does.Contain("+/- 10.0f Percent"));
468            }
469
470            /// <summary>Applies both the Percent and Ulps modifiers to cause an exception</summary>
471            [Test]
472            public void ErrorWithPercentAndUlpsToleranceModes()
473            {
474                Assert.Throws<InvalidOperationException>(() =>
475                {
476                    var shouldFail = new EqualConstraint(100.0f).Within(10.0f).Percent.Ulps;
477                });
478            }
479
480            /// <summary>Applies both the Ulps and Percent modifiers to cause an exception</summary>
481            [Test]
482            public void ErrorWithUlpsAndPercentToleranceModes()
483            {
484                Assert.Throws<InvalidOperationException>(() =>
485                {
486                    EqualConstraint shouldFail = new EqualConstraint(100.0f).Within(10.0f).Ulps.Percent;
487                });
488            }
489
490            [Test]
491            public void ErrorIfPercentPrecedesWithin()
492            {
493                Assert.Throws<InvalidOperationException>(() => Assert.That(1010, Is.EqualTo(1000).Percent.Within(5)));
494            }
495
496            [Test]
497            public void ErrorIfUlpsPrecedesWithin()
498            {
499                Assert.Throws<InvalidOperationException>(() => Assert.That(1010.0, Is.EqualTo(1000.0).Ulps.Within(5)));
500            }
501
502            [TestCase(1000, 1010)]
503            [TestCase(1000U, 1010U)]
504            [TestCase(1000L, 1010L)]
505            [TestCase(1000UL, 1010UL)]
506            public void ErrorIfUlpsIsUsedOnIntegralType(object x, object y)
507            {
508                Assert.Throws<InvalidOperationException>(() => Assert.That(y, Is.EqualTo(x).Within(2).Ulps));
509            }
510
511            [Test]
512            public void ErrorIfUlpsIsUsedOnDecimal()
513            {
514                Assert.Throws<InvalidOperationException>(() => Assert.That(100m, Is.EqualTo(100m).Within(2).Ulps));
515            }
516        }
517
518        #endregion
519
520        #region UsingModifier
521
522        public class UsingModifier
523        {
524            [Test]
525            public void UsesProvidedIComparer()
526            {
527                var comparer = new ObjectComparer();
528                Assert.That(2 + 2, Is.EqualTo(4).Using(comparer));
529                Assert.That(comparer.WasCalled, "Comparer was not called");
530            }
531
532            [Test]
533            public void CanCompareUncomparableTypes()
534            {
535                Assert.That(2 + 2, Is.Not.EqualTo("4"));
536                var comparer = new ConvertibleComparer();
537                Assert.That(2 + 2, Is.EqualTo("4").Using(comparer));
538            }
539
540            [Test]
541            public void UsesProvidedEqualityComparer()
542            {
543                var comparer = new ObjectEqualityComparer();
544                Assert.That(2 + 2, Is.EqualTo(4).Using(comparer));
545                Assert.That(comparer.Called, "Comparer was not called");
546            }
547
548            [Test]
549            public void UsesProvidedGenericEqualityComparer()
550            {
551                var comparer = new GenericEqualityComparer<int>();
552                Assert.That(2 + 2, Is.EqualTo(4).Using(comparer));
553                Assert.That(comparer.WasCalled, "Comparer was not called");
554            }
555
556            [Test]
557            public void UsesProvidedGenericComparer()
558            {
559                var comparer = new GenericComparer<int>();
560                Assert.That(2 + 2, Is.EqualTo(4).Using(comparer));
561                Assert.That(comparer.WasCalled, "Comparer was not called");
562            }
563
564            [Test]
565            public void UsesProvidedGenericComparison()
566            {
567                var comparer = new GenericComparison<int>();
568                Assert.That(2 + 2, Is.EqualTo(4).Using(comparer.Delegate));
569                Assert.That(comparer.WasCalled, "Comparer was not called");
570            }
571
572            [Test]
573            public void UsesProvidedGenericEqualityComparison()
574            {
575                var comparer = new GenericEqualityComparison<int>();
576                Assert.That(2 + 2, Is.EqualTo(4).Using<int>(comparer.Delegate));
577                Assert.That(comparer.WasCalled, "Comparer was not called");
578            }
579
580            [Test]
581            public void UsesBooleanReturningDelegate()
582            {
583                Assert.That(2 + 2, Is.EqualTo(4).Using<int>((x, y) => x.Equals(y)));
584            }
585
586            [Test]
587            public void UsesProvidedLambda_IntArgs()
588            {
589                Assert.That(2 + 2, Is.EqualTo(4).Using<int>((x, y) => x.CompareTo(y)));
590            }
591
592            [Test]
593            public void UsesProvidedLambda_StringArgs()
594            {
595                Assert.That("hello", Is.EqualTo("HELLO").Using<string>((x, y) => StringUtil.Compare(x, y, true)));
596            }
597
598            [Test]
599            public void UsesProvidedListComparer()
600            {
601                var list1 = new List<int>() {2, 3};
602                var list2 = new List<int>() {3, 4};
603
604                var list11 = new List<List<int>>() {list1};
605                var list22 = new List<List<int>>() {list2};
606                var comparer = new IntListEqualComparer();
607
608                Assert.That(list11, new CollectionEquivalentConstraint(list22).Using(comparer));
609            }
610
611            public class IntListEqualComparer : IEqualityComparer<List<int>>
612            {
613                public bool Equals(List<int> x, List<int> y)
614                {
615                    return x.Count == y.Count;
616                }
617
618                public int GetHashCode(List<int> obj)
619                {
620                    return obj.Count.GetHashCode();
621                }
622            }
623
624            [Test]
625            public void UsesProvidedArrayComparer()
626            {
627                var array1 = new int[] {2, 3};
628                var array2 = new int[] {3, 4};
629
630                var list11 = new List<int[]>() {array1};
631                var list22 = new List<int[]>() {array2};
632                var comparer = new IntArrayEqualComparer();
633
634                Assert.That(list11, new CollectionEquivalentConstraint(list22).Using(comparer));
635            }
636
637            public class IntArrayEqualComparer : IEqualityComparer<int[]>
638            {
639                public bool Equals(int[] x, int[] y)
640                {
641                    return x.Length == y.Length;
642                }
643
644                public int GetHashCode(int[] obj)
645                {
646                    return obj.Length.GetHashCode();
647                }
648            }
649
650            [Test]
651            public void HasMemberHonorsUsingWhenCollectionsAreOfDifferentTypes()
652            {
653                ICollection strings = new List<string> { "1", "2", "3" };
654                Assert.That(strings, Has.Member(2).Using<string, int>((s, i) => i.ToString() == s));
655            }
656        }
657
658        #endregion
659
660        #region TypeEqualityMessages
661        private readonly string NL = Environment.NewLine;
662        private static IEnumerable DifferentTypeSameValueTestData
663        {
664            get
665            {
666                var ptr = new System.IntPtr(0);
667                var ExampleTestA = new ExampleTest.classA(0);
668                var ExampleTestB = new ExampleTest.classB(0);
669                var clipTestA = new ExampleTest.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Clip.ReallyLongClassNameShouldBeHere();
670                var clipTestB = new ExampleTest.Clip.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Clip.ReallyLongClassNameShouldBeHere();
671                yield return new object[] { 0, ptr };
672                yield return new object[] { ExampleTestA, ExampleTestB };
673                yield return new object[] { clipTestA, clipTestB };
674            }
675        }
676        [Test]
677        public void SameValueDifferentTypeExactMessageMatch()
678        {
679            var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(0, new System.IntPtr(0)));
680            Assert.AreEqual(ex.Message, "  Expected: 0 (Int32)"+ NL + "  But was:  0 (IntPtr)"+ NL);
681        }
682
683        class Dummy
684        {
685            internal readonly int value;
686
687            public Dummy(int value)
688            {
689                this.value = value;
690            }
691
692            public override string ToString()
693            {
694                return "Dummy " + value;
695            }
696        }
697
698        class Dummy1
699        {
700            internal readonly int value;
701
702            public Dummy1(int value)
703            {
704                this.value = value;
705            }
706
707            public override string ToString()
708            {
709                return "Dummy " + value;
710            }
711        }
712
713        class DummyGenericClass<T>
714        {
715            private object _obj;
716            public DummyGenericClass(object obj)
717            {
718                _obj = obj;
719            }
720
721            public override string ToString()
722            {
723                return _obj.ToString();
724            }
725        }
726
727        [Test]
728        public void TestSameValueDifferentTypeUsingGenericTypes()
729        {
730            var d1 = new Dummy(12);
731            var d2 = new Dummy1(12);
732            var dc1 = new DummyGenericClass<Dummy>(d1);
733            var dc2 = new DummyGenericClass<Dummy1>(d2);
734
735            var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(dc1, dc2));
736            var expectedMsg =
737                "  Expected: <Dummy 12> (EqualConstraintTests+DummyGenericClass`1[EqualConstraintTests+Dummy])" + Environment.NewLine +
738                "  But was:  <Dummy 12> (EqualConstraintTests+DummyGenericClass`1[EqualConstraintTests+Dummy1])" + Environment.NewLine;
739
740            Assert.AreEqual(expectedMsg, ex.Message);
741        }
742
743        [Test]
744        public void SameValueAndTypeButDifferentReferenceShowNotShowTypeDifference()
745        {
746            var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(Is.Zero, Is.Zero));
747            Assert.AreEqual(ex.Message, "  Expected: <<equal 0>>"+ NL + "  But was:  <<equal 0>>"+ NL);
748        }
749
750        [Test, TestCaseSource("DifferentTypeSameValueTestData")]
751        public void SameValueDifferentTypeRegexMatch(object expected, object actual)
752        {
753            var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(expected, actual));
754            Assert.That(ex.Message, Does.Match(@"\s*Expected\s*:\s*.*\s*\(.+\)\r?\n\s*But\s*was\s*:\s*.*\s*\(.+\)"));
755        }
756    }
757    namespace ExampleTest.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Clip {
758        class ReallyLongClassNameShouldBeHere {
759            public override bool Equals(object obj)
760            {
761                if (obj == null || GetType() != obj.GetType())
762                {
763                    return false;
764                }
765                return obj.ToString() == this.ToString();
766            }
767            public override int GetHashCode()
768            {
769                return "a".GetHashCode();
770            }
771            public override string ToString()
772            {
773                return "a";
774            }
775
776        }
777
778    }
779    namespace ExampleTest.Clip.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Clip
780    {
781        class ReallyLongClassNameShouldBeHere {
782            public override bool Equals(object obj)
783            {
784                if (obj == null || GetType() != obj.GetType())
785                {
786                    return false;
787                }
788                return obj.ToString()==this.ToString();
789            }
790            public override int GetHashCode()
791            {
792                return "a".GetHashCode();
793            }
794
795            public override string ToString()
796            {
797                return "a";
798            }
799        }
800
801    }
802    namespace ExampleTest {
803        class baseTest {
804            readonly int _value;
805            public baseTest()
806            {
807                _value = 0;
808            }
809            public baseTest(int value) {
810                _value = value;
811            }
812            public override bool Equals(object obj)
813            {
814                if (obj == null || GetType() != obj.GetType())
815                {
816                    return false;
817                }
818                return _value.Equals(((baseTest)obj)._value);
819            }
820
821            public override string ToString()
822            {
823                return _value.ToString();
824            }
825
826            public override int GetHashCode()
827            {
828                return _value.GetHashCode();
829            }
830        }
831
832        class classA : baseTest {
833            public classA(int x) : base(x) { }
834
835        }
836
837        class classB : baseTest
838        {
839             public classB(int x) : base(x) { }
840        }
841    }
842    #endregion
843
844    /// <summary>
845    /// ConvertibleComparer is used in testing to ensure that objects
846    /// of different types can be compared when appropriate.
847    /// </summary>
848    /// <remark>Introduced when testing issue 1897.
849    /// https://github.com/nunit/nunit/issues/1897
850    /// </remark>
851    public class ConvertibleComparer : IComparer<IConvertible>
852    {
853        public int Compare(IConvertible x, IConvertible y)
854        {
855            var str1 = Convert.ToString(x, CultureInfo.InvariantCulture);
856            var str2 = Convert.ToString(y, CultureInfo.InvariantCulture);
857            return string.Compare(str1, str2, StringComparison.Ordinal);
858        }
859    }
860}
861
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Trigger TestSameValueDifferentTypeUsingGenericTypes code on LambdaTest Cloud Grid

Execute automation tests with TestSameValueDifferentTypeUsingGenericTypes on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)