How to use TransactionService class of Telerik.JustMock.Tests package

Best JustMockLite code snippet using Telerik.JustMock.Tests.TransactionService

Run JustMockLite automation tests on LambdaTest cloud grid

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

NinjectAutoMockFixture.cs

Source: NinjectAutoMockFixture.cs Github

copy
1/*
2 JustMock Lite
3 Copyright © 2010-2015,2019 Progress Software Corporation
4
5   Licensed under the Apache License, Version 2.0 (the "License");
6   you may not use this file except in compliance with the License.
7   You may obtain a copy of the License at
8
9	 http://www.apache.org/licenses/LICENSE-2.0
10
11   Unless required by applicable law or agreed to in writing, software
12   distributed under the License is distributed on an "AS IS" BASIS,
13   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   See the License for the specific language governing permissions and
15   limitations under the License.
16*/
17
18using System;
19using System.Collections.Generic;
20using Telerik.JustMock.AutoMock;
21using Telerik.JustMock.AutoMock.Ninject;
22using Telerik.JustMock.AutoMock.Ninject.Parameters;
23using Telerik.JustMock.Core;
24
25
26#region JustMock Test Attributes
27#if NUNIT
28using NUnit.Framework;
29using TestCategory = NUnit.Framework.CategoryAttribute;
30using TestClass = NUnit.Framework.TestFixtureAttribute;
31using TestMethod = NUnit.Framework.TestAttribute;
32using TestInitialize = NUnit.Framework.SetUpAttribute;
33using TestCleanup = NUnit.Framework.TearDownAttribute;
34using AssertionException = NUnit.Framework.AssertionException;
35#elif XUNIT
36using Xunit;
37using Telerik.JustMock.XUnit.Test.Attributes;
38using TestCategory = Telerik.JustMock.XUnit.Test.Attributes.XUnitCategoryAttribute;
39using TestClass = Telerik.JustMock.XUnit.Test.Attributes.EmptyTestClassAttribute;
40using TestMethod = Xunit.FactAttribute;
41using TestInitialize = Telerik.JustMock.XUnit.Test.Attributes.EmptyTestInitializeAttribute;
42using TestCleanup = Telerik.JustMock.XUnit.Test.Attributes.EmptyTestCleanupAttribute;
43using AssertionException = Telerik.JustMock.XUnit.AssertFailedException;
44#elif VSTEST_PORTABLE
45using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
46using AssertionException = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.AssertFailedException;
47#else
48using Microsoft.VisualStudio.TestTools.UnitTesting;
49using AssertionException = Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException;
50#endif
51#endregion
52
53
54namespace Telerik.JustMock.Tests
55{
56	[TestClass]
57	public class NinjectAutoMockFixture
58	{
59		public interface IFileSystem
60		{
61			void Refresh();
62			bool Exists(string file);
63		}
64
65		public interface ICalendar
66		{
67			DateTime Now { get; }
68		}
69
70		public class FileLog
71		{
72			private readonly IFileSystem fs;
73			private readonly ICalendar calendar;
74
75			public FileLog(IFileSystem fs, ICalendar calendar)
76			{
77				this.fs = fs;
78				this.calendar = calendar;
79			}
80
81			public bool LogExists()
82			{
83				fs.Refresh();
84				return fs.Exists(calendar.Now.Ticks.ToString());
85			}
86		}
87
88		[TestMethod, TestCategory("Lite"), TestCategory("Ninject")]
89		public void ShouldCreateMocksOfDependencies()
90		{
91			var container = new MockingContainer<FileLog>();
92
93			container.Arrange<IFileSystem>(x => x.Exists("123")).Returns(true);
94			container.Arrange<ICalendar>(x => x.Now).Returns(new DateTime(123));
95
96			Assert.True(container.Instance.LogExists());
97		}
98
99		[TestMethod, TestCategory("Lite"), TestCategory("Ninject")]
100		public void ShouldAssertArrangedExpectations()
101		{
102			var container = new MockingContainer<FileLog>();
103
104			container.Arrange<IFileSystem>(x => x.Refresh()).MustBeCalled();
105			container.Arrange<IFileSystem>(x => x.Exists("123")).Returns(true).MustBeCalled();
106			container.Arrange<ICalendar>(x => x.Now).Returns(new DateTime(123)).MustBeCalled();
107
108			Assert.Throws<AssertionException>(() => container.Assert());
109
110			container.Instance.LogExists();
111
112			container.Assert();
113		}
114
115		[TestMethod, TestCategory("Lite"), TestCategory("Ninject")]
116		public void ShouldAssertDependenciesDirectly()
117		{
118			var container = new MockingContainer<FileLog>();
119
120			container.Arrange<ICalendar>(x => x.Now).Returns(new DateTime(123));
121
122			Assert.Throws<AssertionException>(() => container.Assert<IFileSystem>(x => x.Refresh(), Occurs.Once()));
123			Assert.Throws<AssertionException>(() => container.Assert<IFileSystem>(x => x.Exists("123"), Occurs.Once()));
124			Assert.Throws<AssertionException>(() => container.Assert<ICalendar>(x => x.Now, Occurs.Once()));
125
126			container.Instance.LogExists();
127
128			container.Assert<IFileSystem>(x => x.Refresh(), Occurs.Once());
129			container.Assert<IFileSystem>(x => x.Exists("123"), Occurs.Once());
130			container.Assert<ICalendar>(x => x.Now, Occurs.Once());
131		}
132
133		[TestMethod, TestCategory("Lite"), TestCategory("Ninject")]
134		public void ShouldSpecifyDependencyBehavior()
135		{
136			var container = new MockingContainer<FileLog>(new AutoMockSettings { MockBehavior = Behavior.Strict });
137
138			Assert.Throws<StrictMockException>(() => container.Instance.LogExists());
139		}
140
141		public interface IAccount
142		{
143			int Id { get; }
144			void Withdraw(decimal amount);
145			void Deposit(decimal amount);
146		}
147
148		public class TransactionService
149		{
150			public readonly IAccount From;
151			public readonly IAccount To;
152
153			public TransactionService(IAccount fromAccount, IAccount toAccount)
154			{
155				this.From = fromAccount;
156				this.To = toAccount;
157			}
158
159			[Inject]
160			public IAccount BillingAccount { get; set; }
161
162			public void TransferFunds(decimal amount)
163			{
164				const decimal Fee = 1;
165				From.Withdraw(amount + Fee);
166				To.Deposit(amount);
167				BillingAccount.Deposit(Fee);
168			}
169		}
170
171		[TestMethod, TestCategory("Lite"), TestCategory("Ninject")]
172		public void ShouldArrangeSingletonInstances()
173		{
174			var container = new MockingContainer<TransactionService>();
175			container.Arrange<IAccount>(x => x.Id).Returns(10);
176
177			var inst = container.Instance;
178			Assert.NotNull(inst.From);
179			Assert.Same(inst.From, inst.To);
180			Assert.Same(inst.From, inst.BillingAccount);
181		}
182
183		[TestMethod, TestCategory("Lite"), TestCategory("Ninject")]
184		public void ShouldArrangeMultipleInstancesSeparatelyByParameterName()
185		{
186			var container = new MockingContainer<TransactionService>();
187			container.Bind<IAccount>().ToMock().InjectedIntoParameter("fromAccount").AndArrange(x => Mock.Arrange(() => x.Id).Returns(10));
188			container.Bind<IAccount>().ToMock().InjectedIntoParameter("toAccount").AndArrange(x => Mock.Arrange(() => x.Id).Returns(20));
189			container.Bind<IAccount>().ToMock().InjectedIntoProperty((TransactionService s) => s.BillingAccount).AndArrange(x => Mock.Arrange(() => x.Id).Returns(30));
190
191			var inst = container.Instance;
192			Assert.Equal(10, inst.From.Id);
193			Assert.Equal(20, inst.To.Id);
194			Assert.Equal(30, inst.BillingAccount.Id);
195		}
196
197		[TestMethod, TestCategory("Lite"), TestCategory("Ninject")]
198		public void ShouldArrangeMultipleInstancesSeparatelyByPropertyName()
199		{
200			var container = new MockingContainer<TransactionService>();
201			container.Bind<IAccount>().ToMock().InjectedIntoProperty("BillingAccount").AndArrange(x => Mock.Arrange(() => x.Id).Returns(30));
202
203			var inst = container.Instance;
204			Assert.Equal(30, inst.BillingAccount.Id);
205		}
206
207		[TestMethod, TestCategory("Lite"), TestCategory("Ninject")]
208		public void ShouldAssertMultipleInstancesByName()
209		{
210			var container = new MockingContainer<TransactionService>();
211			container.Bind<IAccount>().ToMock().InjectedIntoParameter("fromAccount").Named("from")
212				.AndArrange(x => Mock.Arrange(() => x.Id).Returns(10));
213			container.Bind<IAccount>().ToMock().InjectedIntoParameter("toAccount").Named("to")
214				.AndArrange(x => Mock.Arrange(() => x.Id).Returns(20));
215			container.Bind<IAccount>().ToMock().InjectedIntoProperty((TransactionService s) => s.BillingAccount).Named("bill")
216				.AndArrange(x => Mock.Arrange(() => x.Id).Returns(30));
217
218			var inst = container.Instance;
219
220			inst.TransferFunds(10);
221
222			container.Assert<IAccount>("from", x => x.Withdraw(11), Occurs.Once());
223			container.Assert<IAccount>("to", x => x.Deposit(10), Occurs.Once());
224			container.Assert<IAccount>("bill", x => x.Deposit(1), Occurs.Once());
225		}
226
227		public class VariousCtors
228		{
229			public VariousCtors(IFileSystem fs)
230			{
231			}
232
233			public VariousCtors(IFileSystem fs, ICalendar calendar)
234			{
235				throw new InvalidOperationException();
236			}
237		}
238
239		[TestMethod, TestCategory("Lite"), TestCategory("Ninject")]
240		public void ShouldSelectConstructorBasedOnSettings()
241		{
242			// assert the default NInject behavior that injects into the constructor with most parameters
243			var container = new MockingContainer<VariousCtors>();
244			Assert.Throws<InvalidOperationException>(() => { var inst = container.Instance; });
245
246			// assert the overriden constructor lookup behavior
247			var container2 = new MockingContainer<VariousCtors>(new AutoMockSettings { ConstructorArgTypes = new[] { typeof(IFileSystem) } });
248			Assert.NotNull(container2.Instance);
249
250			// assert that specifying an invalid constructor throws
251			Assert.Throws<MockException>(() => new MockingContainer<VariousCtors>(new AutoMockSettings { ConstructorArgTypes = new[] { typeof(ICalendar) } }));
252		}
253
254		public interface IService
255		{
256			int Value { get; set; }
257		}
258
259		public class Module
260		{
261			public IService service;
262
263			public Module(IService service)
264			{
265				this.service = service;
266			}
267		}
268
269		[TestMethod, TestCategory("Lite"), TestCategory("Ninject")]
270		public void ShouldMakeSingletonExplicitlyRequestedServices()
271		{
272			var container = new MockingContainer<Module>();
273			var s1 = container.Get<IService>();
274			var s2 = container.Instance.service;
275			Assert.Same(s1, s2);
276		}
277
278		[TestMethod, TestCategory("Lite"), TestCategory("Ninject")]
279		public void ShouldArrangePropertySet()
280		{
281			// Arrange
282			var container = new MockingContainer<Module>();
283			container.ArrangeSet<IService>(x => x.Value = 99).MustBeCalled();
284			var service = container.Get<IService>();
285
286			// Act 
287			service.Value = 99;
288
289			// Assert
290			container.Assert<IService>();
291		}
292
293		[TestMethod, TestCategory("Lite"), TestCategory("Ninject")]
294		public void ShouldArrangePropertySetWithMatcher()
295		{
296			// Arrange
297			var container = new MockingContainer<Module>();
298			container.ArrangeSet<IService>(x => x.Value = Arg.AnyInt).MustBeCalled();
299			var service = container.Get<IService>();
300
301			// Act 
302			service.Value = 99;
303
304			// Assert
305			container.Assert<IService>();
306		}
307
308		[TestMethod, TestCategory("Lite"), TestCategory("Ninject")]
309		public void ShouldAssertPropertySet()
310		{
311			// Arrange
312			var container = new MockingContainer<Module>();
313
314			// Act 
315			container.Get<IService>().Value = 99;
316
317			// Assert
318			container.AssertSet<IService>(x => x.Value = 99);
319		}
320
321		[TestMethod, TestCategory("Lite"), TestCategory("Ninject")]
322		public void ShouldAssertPropertySetWithMatcher()
323		{
324			// Arrange
325			var container = new MockingContainer<Module>();
326
327			// Act 
328			container.Get<IService>().Value = 99;
329
330			// Assert
331			container.AssertSet<IService>(x => x.Value = Arg.AnyInt);
332		}
333
334		[TestMethod, TestCategory("Lite"), TestCategory("Ninject")]
335		public void ShouldAssertPropertySetNegative()
336		{
337            DebugView.IsTraceEnabled = true;
338
339			// Arrange
340			var container = new MockingContainer<Module>();
341
342			// Assert
343			container.AssertSet<IService>(x => x.Value = 99, Occurs.Never());
344		}
345
346		[TestMethod, TestCategory("Lite"), TestCategory("Ninject")]
347		public void ShouldAssertPropertySetNegativeWithMatcher()
348		{
349			// Arrange
350			var container = new MockingContainer<Module>();
351
352			// Assert
353			container.AssertSet<IService>(x => x.Value = Arg.AnyInt, Occurs.Never());
354		}
355
356		[TestMethod, TestCategory("Lite"), TestCategory("AutoMock")]
357		public void ShouldAssertRaisesAgainstMethod()
358		{
359			var container = new MockingContainer<Executor>();
360
361			bool raised = false;
362
363			container.Arrange<IExecutor>(x => x.Submit()).Raises(() => container.Get<IExecutor>().Done += null, EventArgs.Empty);
364
365			container.Get<IExecutor>().Done += delegate { raised = true; };
366
367			container.Instance.Submit();
368
369			Assert.True(raised);
370		}
371
372		public class Executor
373		{
374			public Executor(IExecutor executor)
375			{
376				this.executor = executor;
377			}
378
379			public void Submit()
380			{
381				this.executor.Submit();
382			}
383
384			private IExecutor executor;
385		}
386
387		public interface IExecutor
388		{
389			event EventHandler<EventArgs> Done;
390			event EventHandler Executed;
391			void Submit();
392		}
393
394		[TestMethod, TestCategory("Lite"), TestCategory("AutoMock")]
395		public void ShouldAssertMockingNestedDependency()
396		{
397			var container = new MockingContainer<Foo>();
398			container.Bind<Bar>().ToSelf();
399
400			container.Arrange<IUnitOfWork>(uow => uow.DoWork()).MustBeCalled();
401
402			Assert.Throws<AssertionException>(() => container.Assert());
403
404			container.Instance.DoWork();
405
406			container.Assert();
407		}
408
409		public class Foo
410		{
411			public Foo(Bar bar)
412			{
413				this.bar = bar;
414			}
415
416			public void DoWork()
417			{
418				this.bar.DoWork();
419			}
420
421			private readonly Bar bar;
422		}
423
424		public class Bar
425		{
426			public Bar(IUnitOfWork unitOfWork)
427			{
428				this.unitOfWork = unitOfWork;
429			}
430
431			public void DoWork()
432			{
433				this.unitOfWork.DoWork();
434			}
435
436			private readonly IUnitOfWork unitOfWork;
437		}
438
439		public interface IUnitOfWork
440		{
441			void DoWork();
442		}
443
444		[TestMethod, TestCategory("Lite"), TestCategory("AutoMock")]
445		public void ShouldResolveTargetTypeWithInterfaceAndConcreteDependencies()
446		{
447			var container = new MockingContainer<Unit>();
448
449			container.Arrange<IUnitOfWork>(uow => uow.DoWork()).MustBeCalled();
450
451			// this is where it resolves.
452			container.Instance.DoWork();
453
454			container.Assert();
455		}
456
457		public class Unit
458		{
459			public Unit(IUnitOfWork unitOfWork, WorkItem workItem)
460			{
461				this.unitOfWork = unitOfWork;
462				this.workItem = workItem;
463			}
464
465			public void DoWork()
466			{
467				workItem.DoWork();
468				unitOfWork.DoWork();
469			}
470
471			private readonly IUnitOfWork unitOfWork;
472			private readonly WorkItem workItem;
473		}
474
475		public class WorkItem
476		{
477			public void DoWork()
478			{
479
480			}
481		}
482
483		[TestMethod, TestCategory("Lite"), TestCategory("AutoMock")]
484		public void ShouldAssertOccurrenceFromContainerWithoutPriorArrangement()
485		{
486			var c = new MockingContainer<Unit>();
487			c.Instance.DoWork();
488			c.Assert<IUnitOfWork>(x => x.DoWork());
489		}
490
491		public class DisposableContainer : IDisposable
492		{
493			public IList<IDisposable> Disposables;
494
495			public DisposableContainer(IList<IDisposable> disposables)
496			{
497				this.Disposables = disposables;
498			}
499
500			public void Dispose()
501			{
502				this.Disposables.Clear();
503			}
504		}
505
506		[TestMethod, TestCategory("Lite"), TestCategory("AutoMock")]
507		public void ShouldInjectContainers()
508		{
509			var c = new MockingContainer<DisposableContainer>();
510			var disposables = new List<IDisposable> { Mock.Create<IDisposable>(), Mock.Create<IDisposable>() };
511			var i = c.Get<DisposableContainer>(new ConstructorArgument("disposables", disposables));
512			i.Dispose();
513
514			Assert.Equal(0, disposables.Count);
515		}
516
517		public abstract class DependencyBase
518		{
519			public IDisposable Dep { get; set; }
520
521			protected DependencyBase(IDisposable dep)
522			{
523				this.Dep = dep;
524			}
525
526			public abstract int Value { get; }
527			public abstract string Name { get; set; }
528
529			public int baseValue;
530			public virtual int BaseValue
531			{
532				get { return baseValue; }
533				set { baseValue = value; }
534			}
535		}
536
537		[TestMethod, TestCategory("Lite"), TestCategory("AutoMock")]
538		public void ShouldInjectAbstractType()
539		{
540			var c = new MockingContainer<DependencyBase>();
541			var obj = c.Instance;
542			Assert.NotNull(obj.Dep);
543		}
544
545		[TestMethod, TestCategory("Lite"), TestCategory("AutoMock")]
546		public void ShouldArrangeMethodsOnInjectedAbstractType()
547		{
548			var c = new MockingContainer<DependencyBase>();
549			var obj = c.Instance;
550			Mock.Arrange(() => obj.Value).Returns(5);
551			Assert.Equal(5, obj.Value);
552		}
553
554		[TestMethod, TestCategory("Lite"), TestCategory("AutoMock")]
555		public void ShouldCheckPropertyMixinOnNonabstractPropertyOnInjectedAbstractType()
556		{
557			var c = new MockingContainer<DependencyBase>();
558			var obj = c.Instance;
559			obj.BaseValue = 10;
560			Assert.Equal(10, obj.baseValue);
561		}
562
563		[TestMethod, TestCategory("Lite"), TestCategory("AutoMock")]
564		public void ShouldInjectAbstractTypeWithSpecifiedCtor()
565		{
566			var c = new MockingContainer<DependencyBase>(
567				new AutoMockSettings { ConstructorArgTypes = new[] { typeof(IDisposable) } });
568			var obj = c.Instance;
569			Assert.NotNull(obj.Dep);
570		}
571
572		[TestMethod, TestCategory("Lite"), TestCategory("AutoMock")]
573		public void ShouldIncludeAssertionMessageWhenAssertingContainer()
574		{
575			var c = new MockingContainer<FileLog>();
576			c.Arrange<ICalendar>(x => x.Now).MustBeCalled("Calendar must be used!");
577			c.Arrange<IFileSystem>(x => x.Refresh()).MustBeCalled("Should use latest data!");
578
579			var ex = Assert.Throws<AssertionException>(() => c.Assert("Container must be alright!"));
580
581			Assert.True(ex.Message.Contains("Calendar must be used!"));
582			Assert.True(ex.Message.Contains("Should use latest data!"));
583			Assert.True(ex.Message.Contains("Container must be alright!"));
584		}
585	}
586}
587
Full Screen

TransactionBuilderServiceTests.cs

Source: TransactionBuilderServiceTests.cs Github

copy
1// Copyright 2020 New Relic, Inc. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4using MoreLinq;
5using NewRelic.Agent.Core.Attributes;
6using NewRelic.Agent.Core.CallStack;
7using NewRelic.Agent.Core.Database;
8using NewRelic.Agent.Core.DistributedTracing;
9using NewRelic.Agent.Core.Errors;
10using NewRelic.Agent.Core.Timing;
11using NewRelic.Agent.Core.Wrapper.AgentWrapperApi.Builders;
12using NewRelic.Agent.Extensions.Providers;
13using NewRelic.Core.DistributedTracing;
14using NUnit.Framework;
15using System;
16using System.Collections.Generic;
17using System.Linq;
18using Telerik.JustMock;
19
20namespace NewRelic.Agent.Core.Transactions.UnitTest
21{
22    [TestFixture]
23    public class TransactionBuilderServiceTests
24    {
25        private TransactionService _transactionService;
26        private IContextStorage<IInternalTransaction> _lowPriorityTransactionContext;
27        private IContextStorage<IInternalTransaction> _highPriorityTransactionContext;
28        private readonly TransactionName _initialTransactionName = TransactionName.ForWebTransaction("initialCategory", "initialName");
29
30        [SetUp]
31        public void SetUp()
32        {
33            _lowPriorityTransactionContext = Mock.Create<IContextStorage<IInternalTransaction>>();
34            Mock.Arrange(() => _lowPriorityTransactionContext.Priority).Returns(1);
35            DictionaryTransactionContext(_lowPriorityTransactionContext);
36
37            _highPriorityTransactionContext = Mock.Create<IContextStorage<IInternalTransaction>>();
38            Mock.Arrange(() => _highPriorityTransactionContext.Priority).Returns(2);
39            DictionaryTransactionContext(_highPriorityTransactionContext);
40
41            var factory1 = CreateFactoryForTransactionContext(_highPriorityTransactionContext);
42            var factory2 = CreateFactoryForTransactionContext(_lowPriorityTransactionContext);
43
44            IAttributeDefinitionService _attribDefSvc = new AttributeDefinitionService((f) => new AttributeDefinitions(f));
45
46            _transactionService = new TransactionService(new[] { factory1, factory2 }, Mock.Create<ITimerFactory>(), Mock.Create<ICallStackManagerFactory>(), Mock.Create<IDatabaseService>(), Mock.Create<ITracePriorityManager>(), Mock.Create<IDatabaseStatementParser>(), Mock.Create<IErrorService>(), Mock.Create<IDistributedTracePayloadHandler>(), _attribDefSvc);
47        }
48
49        [TearDown]
50        public void TearDown()
51        {
52            _transactionService.Dispose();
53        }
54
55        [Test]
56        public void GetCurrentTransactionBuilder_ReturnsNull_IfNoCurrentTransactionBuilder()
57        {
58            // ACT
59            var transaction = _transactionService.GetCurrentInternalTransaction();
60
61            // ASSERT
62            Assert.IsNull(transaction);
63        }
64
65        [Test]
66        public void GetCurrentTransactionBuilder_ReturnsCurrentTransactionBuilder_IfCurrentTransactionBuilderExists()
67        {
68            // ARRANGE
69            var oldTransaction = _transactionService.GetOrCreateInternalTransaction(_initialTransactionName);
70
71            // ACT
72            var newTransaction = _transactionService.GetCurrentInternalTransaction();
73
74            // ASSERT
75            Assert.IsNotNull(newTransaction);
76            Assert.AreSame(oldTransaction, newTransaction);
77        }
78
79        [Test]
80        public void GetOrCreateTransactionBuilder_ReturnsNewTransactionBuilder_IfNoCurrentTransactionBuilder()
81        {
82            // ACT
83            var newTransaction = _transactionService.GetOrCreateInternalTransaction(_initialTransactionName);
84
85            // ASSERT
86            Assert.IsNotNull(newTransaction);
87
88            var transactionName = newTransaction.ConvertToImmutableTransaction().TransactionName;
89            Assert.AreEqual(_initialTransactionName.Name, transactionName.Name);
90        }
91
92        [Test]
93        public void GetOrCreateTransactionBuilder_ReturnsCurrentTransactionBuilder_IfCurrentTransactionBuilderExists()
94        {
95            // ARRANGE
96            var oldTransaction = _transactionService.GetOrCreateInternalTransaction(_initialTransactionName);
97
98            // ACT
99            var newTransaction = _transactionService.GetOrCreateInternalTransaction(_initialTransactionName);
100
101            // ASSERT
102            Assert.IsNotNull(newTransaction);
103            Assert.AreSame(oldTransaction, newTransaction);
104        }
105
106        [Test]
107        public void GetOrCreateTransactionBuilder_RunsProvidedAction_IfNoCurrentTransactionBuilder()
108        {
109            // ARRANGE
110            var wasRun = false;
111
112            // ACT
113            _transactionService.GetOrCreateInternalTransaction(_initialTransactionName, () => wasRun = true);
114
115            // ASSERT
116            Assert.True(wasRun);
117        }
118
119        [Test]
120        public void GetOrCreateTransactionBuilder_DoesNotRunProvidedAction_IfCurrentTransactionBuilderExists()
121        {
122            // ARRANGE
123            var wasRun = false;
124            _transactionService.GetOrCreateInternalTransaction(_initialTransactionName);
125
126            // ACT
127            _transactionService.GetOrCreateInternalTransaction(_initialTransactionName, () => wasRun = true);
128
129            // ASSERT
130            Assert.False(wasRun);
131        }
132
133        [Test]
134        public void GetOrCreateTransactionBuilder_IncrementsUnitOfWorkCount_IfCurrentTransactionBuilderExistsAndDoNotTrackAsUnitOfWorkIsFalse()
135        {
136            // ARRANGE
137            var transaction = _transactionService.GetOrCreateInternalTransaction(_initialTransactionName);
138
139            Assert.AreEqual(1, transaction.UnitOfWorkCount);
140
141            // ACT
142            _transactionService.GetOrCreateInternalTransaction(_initialTransactionName, doNotTrackAsUnitOfWork: false);
143
144            // ASSERT
145            Assert.AreEqual(2, transaction.UnitOfWorkCount);
146        }
147
148        [Test]
149        public void GetOrCreateTransactionBuilder_DoesNotIncrementsUnitOfWorkCount_IfCurrentTransactionBuilderExistsAndDoNotTrackAsUnitOfWorkIsTrue()
150        {
151            // ARRANGE
152            var transaction = _transactionService.GetOrCreateInternalTransaction(_initialTransactionName);
153
154            Assert.AreEqual(1, transaction.UnitOfWorkCount);
155
156            // ACT
157            _transactionService.GetOrCreateInternalTransaction(_initialTransactionName, doNotTrackAsUnitOfWork: true);
158
159            // ASSERT
160            Assert.AreEqual(1, transaction.UnitOfWorkCount);
161        }
162
163        [Test]
164        public void GetOrCreateTransactionBuilder_ReplacesExistingTransaction_IfCurrentTransactionBuilderExistsAndRecreateCountIsOver100()
165        {
166            // ARRANGE
167            var oldTransaction = _transactionService.GetOrCreateInternalTransaction(_initialTransactionName);
168            Enumerable.Range(0, 101).ForEach(_ => oldTransaction.NoticeNestedTransactionAttempt());
169
170            Assert.AreEqual(101, oldTransaction.NestedTransactionAttempts);
171
172            // ACT
173            var newTransaction = _transactionService.GetOrCreateInternalTransaction(_initialTransactionName);
174            var newTransaction2 = _transactionService.GetOrCreateInternalTransaction(_initialTransactionName);
175
176            // ASSERT
177            Assert.AreNotSame(oldTransaction, newTransaction);
178            Assert.AreSame(newTransaction, newTransaction2);
179        }
180
181        [Test]
182        public void when_multiple_transactionContexts_are_available_with_higher_provided_first_then_highest_priority_is_used()
183        {
184            // ARRANGE
185            DictionaryTransactionContext(_highPriorityTransactionContext);
186            ThrowingTransactionContext(_lowPriorityTransactionContext);
187
188            // ACT
189            var transaction = _transactionService.GetOrCreateInternalTransaction(_initialTransactionName);
190
191            // ASSERT
192            Assert.IsNotNull(transaction);
193        }
194
195        [Test]
196        public void when_multiple_transactionContexts_are_available_with_lower_provided_first_then_highest_priority_is_used()
197        {
198            // ARRANGE
199            DictionaryTransactionContext(_highPriorityTransactionContext);
200            ThrowingTransactionContext(_lowPriorityTransactionContext);
201
202            // ACT
203            var transaction = _transactionService.GetOrCreateInternalTransaction(_initialTransactionName);
204
205            // ASSERT
206            Assert.IsNotNull(transaction);
207        }
208
209        [Test]
210        public void when_TransactionContextFactory_throws_then_current_transaction_builder_is_null()
211        {
212            // ARRANGE
213            ThrowingTransactionContext(_highPriorityTransactionContext);
214
215            // ACT
216            var transaction = _transactionService.GetOrCreateInternalTransaction(_initialTransactionName);
217
218            // ASSERT
219            Assert.IsNull(transaction);
220        }
221
222        private static void ThrowingTransactionContext(IContextStorage<IInternalTransaction> transactionContext)
223        {
224            Mock.Arrange(() => transactionContext.CanProvide).Returns(true);
225            Mock.Arrange(() => transactionContext.SetData((IInternalTransaction)Arg.AnyObject)).Throws<Exception>();
226            Mock.Arrange(() => transactionContext.GetData()).Throws<Exception>();
227        }
228
229        private static void DictionaryTransactionContext(IContextStorage<IInternalTransaction> transactionContext)
230        {
231            const string key = "TEST";
232            var dictionary = new Dictionary<string, object>();
233            Mock.Arrange(() => transactionContext.CanProvide).Returns(true);
234            Mock.Arrange(() => transactionContext.SetData((IInternalTransaction)Arg.AnyObject)).DoInstead((object value) =>
235            {
236                dictionary[key] = value;
237            });
238            Mock.Arrange(() => transactionContext.GetData()).Returns(() =>
239            {
240                if (!dictionary.ContainsKey(key))
241                    return null;
242
243                object value;
244                dictionary.TryGetValue(key, out value);
245                return value as IInternalTransaction;
246
247            });
248        }
249
250        private static IContextStorageFactory CreateFactoryForTransactionContext(IContextStorage<IInternalTransaction> transactionContext)
251        {
252            var transactionContextFactory = Mock.Create<IContextStorageFactory>();
253            Mock.Arrange(() => transactionContextFactory.CreateContext<IInternalTransaction>(Arg.AnyString)).Returns(transactionContext);
254            return transactionContextFactory;
255        }
256    }
257}
258
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)