How to use SourceInAnotherClassPassingParamsToField method of NUnit.Framework.Attributes.DataSourceClass class

Best Nunit code snippet using NUnit.Framework.Attributes.DataSourceClass.SourceInAnotherClassPassingParamsToField

Run Nunit automation tests on LambdaTest cloud grid

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

TestCaseSourceTests.cs

Source: TestCaseSourceTests.cs Github

copy
1// ***********************************************************************
2// Copyright (c) 2009-2015 Charlie Poole
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.Collections;
25using System.Collections.Generic;
26using System.Reflection;
27using System.Linq;
28using NUnit.Framework.Interfaces;
29using NUnit.Framework.Internal;
30using NUnit.TestData.TestCaseSourceAttributeFixture;
31using NUnit.TestUtilities;
32
33namespace NUnit.Framework.Attributes
34{
35    [TestFixture]
36    public class TestCaseSourceTests : TestSourceMayBeInherited
37    {
38        #region Tests With Static and Instance Members as Source
39
40        [Test, TestCaseSource("StaticProperty")]
41        public void SourceCanBeStaticProperty(string source)
42        {
43            Assert.AreEqual("StaticProperty", source);
44        }
45
46        [Test, TestCaseSource("InheritedStaticProperty")]
47#if !PORTABLE
48        [Platform(Exclude = "netcf", Reason = "Test hangs in CF")]
49#endif
50        public void TestSourceCanBeInheritedStaticProperty(bool source)
51        {
52            Assert.AreEqual(true, source);
53        }
54
55        static IEnumerable StaticProperty
56        {
57            get { return new object[] { new object[] { "StaticProperty" } }; }
58        }
59
60        [Test]
61        public void SourceUsingInstancePropertyIsNotRunnable()
62        {
63            var result = TestBuilder.RunParameterizedMethodSuite(typeof(TestCaseSourceAttributeFixture), "MethodWithInstancePropertyAsSource");
64            Assert.AreEqual(result.Children.ToArray()[0].ResultState, ResultState.NotRunnable);
65        }
66
67        [Test, TestCaseSource("StaticMethod")]
68        public void SourceCanBeStaticMethod(string source)
69        {
70            Assert.AreEqual("StaticMethod", source);
71        }
72
73        static IEnumerable StaticMethod()
74        {
75            return new object[] { new object[] { "StaticMethod" } };
76        }
77
78        [Test]
79        public void SourceUsingInstanceMethodIsNotRunnable()
80        {
81            var result = TestBuilder.RunParameterizedMethodSuite(typeof(TestCaseSourceAttributeFixture), "MethodWithInstanceMethodAsSource");
82            Assert.AreEqual(result.Children.ToArray()[0].ResultState, ResultState.NotRunnable);
83        }
84
85        IEnumerable InstanceMethod()
86        {
87            return new object[] { new object[] { "InstanceMethod" } };
88        }
89
90        [Test, TestCaseSource("StaticField")]
91        public void SourceCanBeStaticField(string source)
92        {
93            Assert.AreEqual("StaticField", source);
94        }
95
96        static object[] StaticField =
97            { new object[] { "StaticField" } };
98
99        [Test]
100        public void SourceUsingInstanceFieldIsNotRunnable()
101        {
102            var result = TestBuilder.RunParameterizedMethodSuite(typeof(TestCaseSourceAttributeFixture), "MethodWithInstanceFieldAsSource");
103            Assert.AreEqual(result.Children.ToArray()[0].ResultState, ResultState.NotRunnable);
104        }
105
106        #endregion
107
108        #region Test With IEnumerable Class as Source
109
110        [Test, TestCaseSource(typeof(DataSourceClass))]
111        public void SourceCanBeInstanceOfIEnumerable(string source)
112        {
113            Assert.AreEqual("DataSourceClass", source);
114        }
115
116        class DataSourceClass : IEnumerable
117        {
118            public DataSourceClass()
119            {
120            }
121
122            public IEnumerator GetEnumerator()
123            {
124                yield return "DataSourceClass";
125            }
126        }
127
128        #endregion
129
130        [Test, TestCaseSource("MyData")]
131        public void SourceMayReturnArgumentsAsObjectArray(int n, int d, int q)
132        {
133            Assert.AreEqual(q, n / d);
134        }
135
136        [TestCaseSource("MyData")]
137        public void TestAttributeIsOptional(int n, int d, int q)
138        {
139            Assert.AreEqual(q, n / d);
140        }
141
142        [Test, TestCaseSource("MyIntData")]
143        public void SourceMayReturnArgumentsAsIntArray(int n, int d, int q)
144        {
145            Assert.AreEqual(q, n / d);
146        }
147
148        [Test, TestCaseSource("EvenNumbers")]
149        public void SourceMayReturnSinglePrimitiveArgumentAlone(int n)
150        {
151            Assert.AreEqual(0, n % 2);
152        }
153
154        [Test, TestCaseSource("Params")]
155        public int SourceMayReturnArgumentsAsParamSet(int n, int d)
156        {
157            return n / d;
158        }
159
160        [Test]
161        [TestCaseSource("MyData")]
162        [TestCaseSource("MoreData", Category = "Extra")]
163        [TestCase(12, 2, 6)]
164        public void TestMayUseMultipleSourceAttributes(int n, int d, int q)
165        {
166            Assert.AreEqual(q, n / d);
167        }
168
169        [Test, TestCaseSource("FourArgs")]
170        public void TestWithFourArguments(int n, int d, int q, int r)
171        {
172            Assert.AreEqual(q, n / d);
173            Assert.AreEqual(r, n % d);
174        }
175
176        [Test, Category("Top"), TestCaseSource(typeof(DivideDataProvider), "HereIsTheData")]
177        public void SourceMayBeInAnotherClass(int n, int d, int q)
178        {
179            Assert.AreEqual(q, n / d);
180        }
181
182        [Test, Category("Top"), TestCaseSource(typeof(DivideDataProvider), "HereIsTheDataWithParameters", new object[] { 100, 4, 25 })]
183        public void SourceInAnotherClassPassingSomeDataToConstructor(int n, int d, int q)
184        {
185            Assert.AreEqual(q, n / d);
186        }
187
188        [Test, Category("Top"), TestCaseSource("StaticMethodDataWithParameters", new object[] { 8000, 8, 1000 })]
189        public void SourceCanBeStaticMethodPassingSomeDataToConstructor(int n, int d, int q)
190        {
191            Assert.AreEqual(q, n / d);
192        }
193
194        [Test]
195        public void SourceInAnotherClassPassingParamsToField()
196        {
197            var testMethod = (TestMethod)TestBuilder.MakeParameterizedMethodSuite(
198                typeof(TestCaseSourceAttributeFixture), "SourceInAnotherClassPassingParamsToField").Tests[0];
199            Assert.AreEqual(RunState.NotRunnable, testMethod.RunState);
200            ITestResult result = TestBuilder.RunTest(testMethod, null);
201            Assert.AreEqual(ResultState.NotRunnable, result.ResultState);
202            Assert.AreEqual("You have specified a data source field but also given a set of parameters. Fields cannot take parameters, " +
203                            "please revise the 3rd parameter passed to the TestCaseSourceAttribute and either remove " +
204                            "it or specify a method.", result.Message);
205        }
206
207        [Test]
208        public void SourceInAnotherClassPassingParamsToProperty()
209        {
210            var testMethod = (TestMethod)TestBuilder.MakeParameterizedMethodSuite(
211                typeof(TestCaseSourceAttributeFixture), "SourceInAnotherClassPassingParamsToProperty").Tests[0];
212            Assert.AreEqual(RunState.NotRunnable, testMethod.RunState);
213            ITestResult result = TestBuilder.RunTest(testMethod, null);
214            Assert.AreEqual(ResultState.NotRunnable, result.ResultState);
215            Assert.AreEqual("You have specified a data source property but also given a set of parameters. " +
216                            "Properties cannot take parameters, please revise the 3rd parameter passed to the " +
217                            "TestCaseSource attribute and either remove it or specify a method.", result.Message);
218        }
219
220        [Test]
221        public void SourceInAnotherClassPassingSomeDataToConstructorWrongNumberParam()
222        {
223            var testMethod = (TestMethod)TestBuilder.MakeParameterizedMethodSuite(
224                typeof(TestCaseSourceAttributeFixture), "SourceInAnotherClassPassingSomeDataToConstructorWrongNumberParam").Tests[0];
225            Assert.AreEqual(RunState.NotRunnable, testMethod.RunState);
226            ITestResult result = TestBuilder.RunTest(testMethod, null);
227            Assert.AreEqual(ResultState.NotRunnable, result.ResultState);
228            Assert.AreEqual("You have given the wrong number of arguments to the method in the TestCaseSourceAttribute" +
229                            ", please check the number of parameters passed in the object is correct in the 3rd parameter for the " +
230                            "TestCaseSourceAttribute and this matches the number of parameters in the target method and try again.", result.Message);
231        }
232
233        [Test, TestCaseSource(typeof(DivideDataProviderWithReturnValue), "TestCases")]
234        public int SourceMayBeInAnotherClassWithReturn(int n, int d)
235        {
236            return n / d;
237        }
238
239        [Test]
240        public void IgnoreTakesPrecedenceOverExpectedException()
241        {
242            var result = TestBuilder.RunParameterizedMethodSuite(
243                typeof(TestCaseSourceAttributeFixture), "MethodCallsIgnore").Children.ToArray()[0];
244            Assert.AreEqual(ResultState.Ignored, result.ResultState);
245            Assert.AreEqual("Ignore this", result.Message);
246        }
247
248        [Test]
249        public void CanIgnoreIndividualTestCases()
250        {
251            TestSuite suite = TestBuilder.MakeParameterizedMethodSuite(
252                typeof(TestCaseSourceAttributeFixture), "MethodWithIgnoredTestCases");
253
254            Test testCase = TestFinder.Find("MethodWithIgnoredTestCases(1)", suite, false);
255            Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable));
256
257            testCase = TestFinder.Find("MethodWithIgnoredTestCases(2)", suite, false);
258            Assert.That(testCase.RunState, Is.EqualTo(RunState.Ignored));
259            Assert.That(testCase.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Don't Run Me!"));
260        }
261
262        [Test]
263        public void CanMarkIndividualTestCasesExplicit()
264        {
265            TestSuite suite = TestBuilder.MakeParameterizedMethodSuite(
266                typeof(TestCaseSourceAttributeFixture), "MethodWithExplicitTestCases");
267
268            Test testCase = TestFinder.Find("MethodWithExplicitTestCases(1)", suite, false);
269            Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable));
270
271            testCase = TestFinder.Find("MethodWithExplicitTestCases(2)", suite, false);
272            Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit));
273
274            testCase = TestFinder.Find("MethodWithExplicitTestCases(3)", suite, false);
275            Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit));
276            Assert.That(testCase.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Connection failing"));
277        }
278
279        [Test]
280        public void HandlesExceptionInTestCaseSource()
281        {
282            var testMethod = (TestMethod)TestBuilder.MakeParameterizedMethodSuite(
283                typeof(TestCaseSourceAttributeFixture), "MethodWithSourceThrowingException").Tests[0];
284            Assert.AreEqual(RunState.NotRunnable, testMethod.RunState);
285            ITestResult result = TestBuilder.RunTest(testMethod, null);
286            Assert.AreEqual(ResultState.NotRunnable, result.ResultState);
287            Assert.AreEqual("System.Exception : my message", result.Message);
288        }
289
290        [TestCaseSource("exception_source"), Explicit("Used for GUI tests")]
291        public void HandlesExceptionInTestCaseSource_GuiDisplay(string lhs, string rhs)
292        {
293            Assert.AreEqual(lhs, rhs);
294        }
295
296        static object[] testCases =
297        {
298            new TestCaseData(
299                new string[] { "A" },
300                new string[] { "B" })
301        };
302
303        [Test, TestCaseSource("testCases")]
304        public void MethodTakingTwoStringArrays(string[] a, string[] b)
305        {
306            Assert.That(a, Is.TypeOf(typeof(string[])));
307            Assert.That(b, Is.TypeOf(typeof(string[])));
308        }
309
310        [TestCaseSource("SingleMemberArrayAsArgument")]
311        public void Issue1337SingleMemberArrayAsArgument(string[] args)
312        {
313            Assert.That(args.Length == 1 && args[0] == "1");
314        }
315
316        static string[][] SingleMemberArrayAsArgument = { new[] { "1" }  };
317
318        #region Sources used by the tests
319        static object[] MyData = new object[] {
320            new object[] { 12, 3, 4 },
321            new object[] { 12, 4, 3 },
322            new object[] { 12, 6, 2 } };
323
324        static object[] MyIntData = new object[] {
325            new int[] { 12, 3, 4 },
326            new int[] { 12, 4, 3 },
327            new int[] { 12, 6, 2 } };
328
329        public static IEnumerable StaticMethodDataWithParameters(int inject1, int inject2, int inject3)
330        {
331            yield return new object[] { inject1, inject2, inject3 };
332        }
333
334        static object[] FourArgs = new object[] {
335            new TestCaseData( 12, 3, 4, 0 ),
336            new TestCaseData( 12, 4, 3, 0 ),
337            new TestCaseData( 12, 5, 2, 2 ) };
338
339        static int[] EvenNumbers = new int[] { 2, 4, 6, 8 };
340
341        static object[] MoreData = new object[] {
342            new object[] { 12, 1, 12 },
343            new object[] { 12, 2, 6 } };
344
345        static object[] Params = new object[] {
346            new TestCaseData(24, 3).Returns(8),
347            new TestCaseData(24, 2).Returns(12) };
348
349        private class DivideDataProvider
350        {
351#pragma warning disable 0169    // x is never assigned
352            private static object[] myObject;
353#pragma warning restore 0169
354
355            public static IEnumerable HereIsTheDataWithParameters(int inject1, int inject2, int inject3)
356            {
357                yield return new object[] { inject1, inject2, inject3 };
358            }
359            public static IEnumerable HereIsTheData
360            {
361                get
362                {
363                    yield return new object[] { 100, 20, 5 };
364                    yield return new object[] { 100, 4, 25 };
365                }
366            }
367        }
368
369        public class DivideDataProviderWithReturnValue
370        {
371            public static IEnumerable TestCases
372            {
373                get
374                {
375                    return new object[] {
376                        new TestCaseData(12, 3).Returns(4).SetName("TC1"),
377                        new TestCaseData(12, 2).Returns(6).SetName("TC2"),
378                        new TestCaseData(12, 4).Returns(3).SetName("TC3")
379                    };
380                }
381            }
382        }
383
384        private static IEnumerable exception_source
385        {
386            get
387            {
388                yield return new TestCaseData("a", "a");
389                yield return new TestCaseData("b", "b");
390
391                throw new System.Exception("my message");
392            }
393        }
394        #endregion
395    }
396
397    public class TestSourceMayBeInherited
398    {
399        protected static IEnumerable<bool> InheritedStaticProperty
400        {
401            get { yield return true; }
402        }
403    }
404}
405
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
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)