Best JustMockLite code snippet using Telerik.JustMock.Tests.Executor.Unit
NinjectAutoMockFixture.cs
Source:NinjectAutoMockFixture.cs
...18using Telerik.JustMock.AutoMock.Ninject.Parameters;19using Telerik.JustMock.Core;20#region JustMock Test Attributes21#if NUNIT22using NUnit.Framework;23using TestCategory = NUnit.Framework.CategoryAttribute;24using TestClass = NUnit.Framework.TestFixtureAttribute;25using TestMethod = NUnit.Framework.TestAttribute;26using TestInitialize = NUnit.Framework.SetUpAttribute;27using TestCleanup = NUnit.Framework.TearDownAttribute;28using AssertionException = NUnit.Framework.AssertionException;29#elif XUNIT30using Xunit;31using Telerik.JustMock.XUnit.Test.Attributes;32using TestCategory = Telerik.JustMock.XUnit.Test.Attributes.XUnitCategoryAttribute;33using TestClass = Telerik.JustMock.XUnit.Test.Attributes.EmptyTestClassAttribute;34using TestMethod = Xunit.FactAttribute;35using TestInitialize = Telerik.JustMock.XUnit.Test.Attributes.EmptyTestInitializeAttribute;36using TestCleanup = Telerik.JustMock.XUnit.Test.Attributes.EmptyTestCleanupAttribute;37using AssertionException = Telerik.JustMock.XUnit.AssertFailedException;38#elif VSTEST_PORTABLE39using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;40using AssertionException = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.AssertFailedException;41#else42using Microsoft.VisualStudio.TestTools.UnitTesting;43using AssertionException = Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException;44#endif45#endregion46namespace Telerik.JustMock.Tests47{48 [TestClass]49 public class NinjectAutoMockFixture50 {51 public interface IFileSystem52 {53 void Refresh();54 bool Exists(string file);55 }56 public interface ICalendar57 {58 DateTime Now { get; }59 }60 public class FileLog61 {62 private readonly IFileSystem fs;63 private readonly ICalendar calendar;64 public FileLog(IFileSystem fs, ICalendar calendar)65 {66 this.fs = fs;67 this.calendar = calendar;68 }69 public bool LogExists()70 {71 fs.Refresh();72 return fs.Exists(calendar.Now.Ticks.ToString());73 }74 }75 [TestMethod, TestCategory("Lite"), TestCategory("Ninject")]76 public void ShouldCreateMocksOfDependencies()77 {78 var container = new MockingContainer<FileLog>();79 container.Arrange<IFileSystem>(x => x.Exists("123")).Returns(true);80 container.Arrange<ICalendar>(x => x.Now).Returns(new DateTime(123));81 Assert.True(container.Instance.LogExists());82 }83 [TestMethod, TestCategory("Lite"), TestCategory("Ninject")]84 public void ShouldAssertArrangedExpectations()85 {86 var container = new MockingContainer<FileLog>();87 container.Arrange<IFileSystem>(x => x.Refresh()).MustBeCalled();88 container.Arrange<IFileSystem>(x => x.Exists("123")).Returns(true).MustBeCalled();89 container.Arrange<ICalendar>(x => x.Now).Returns(new DateTime(123)).MustBeCalled();90 Assert.Throws<AssertionException>(() => container.Assert());91 container.Instance.LogExists();92 container.Assert();93 }94 [TestMethod, TestCategory("Lite"), TestCategory("Ninject")]95 public void ShouldAssertDependenciesDirectly()96 {97 var container = new MockingContainer<FileLog>();98 container.Arrange<ICalendar>(x => x.Now).Returns(new DateTime(123));99 Assert.Throws<AssertionException>(() => container.Assert<IFileSystem>(x => x.Refresh(), Occurs.Once()));100 Assert.Throws<AssertionException>(() => container.Assert<IFileSystem>(x => x.Exists("123"), Occurs.Once()));101 Assert.Throws<AssertionException>(() => container.Assert<ICalendar>(x => x.Now, Occurs.Once()));102 container.Instance.LogExists();103 container.Assert<IFileSystem>(x => x.Refresh(), Occurs.Once());104 container.Assert<IFileSystem>(x => x.Exists("123"), Occurs.Once());105 container.Assert<ICalendar>(x => x.Now, Occurs.Once());106 }107 [TestMethod, TestCategory("Lite"), TestCategory("Ninject")]108 public void ShouldSpecifyDependencyBehavior()109 {110 var container = new MockingContainer<FileLog>(new AutoMockSettings { MockBehavior = Behavior.Strict });111 Assert.Throws<StrictMockException>(() => container.Instance.LogExists());112 }113 public interface IAccount114 {115 int Id { get; }116 void Withdraw(decimal amount);117 void Deposit(decimal amount);118 }119 public class TransactionService120 {121 public readonly IAccount From;122 public readonly IAccount To;123 public TransactionService(IAccount fromAccount, IAccount toAccount)124 {125 this.From = fromAccount;126 this.To = toAccount;127 }128 [Inject]129 public IAccount BillingAccount { get; set; }130 public void TransferFunds(decimal amount)131 {132 const decimal Fee = 1;133 From.Withdraw(amount + Fee);134 To.Deposit(amount);135 BillingAccount.Deposit(Fee);136 }137 }138 [TestMethod, TestCategory("Lite"), TestCategory("Ninject")]139 public void ShouldArrangeSingletonInstances()140 {141 var container = new MockingContainer<TransactionService>();142 container.Arrange<IAccount>(x => x.Id).Returns(10);143 var inst = container.Instance;144 Assert.NotNull(inst.From);145 Assert.Same(inst.From, inst.To);146 Assert.Same(inst.From, inst.BillingAccount);147 }148 [TestMethod, TestCategory("Lite"), TestCategory("Ninject")]149 public void ShouldArrangeMultipleInstancesSeparatelyByParameterName()150 {151 var container = new MockingContainer<TransactionService>();152 container.Bind<IAccount>().ToMock().InjectedIntoParameter("fromAccount").AndArrange(x => Mock.Arrange(() => x.Id).Returns(10));153 container.Bind<IAccount>().ToMock().InjectedIntoParameter("toAccount").AndArrange(x => Mock.Arrange(() => x.Id).Returns(20));154 container.Bind<IAccount>().ToMock().InjectedIntoProperty((TransactionService s) => s.BillingAccount).AndArrange(x => Mock.Arrange(() => x.Id).Returns(30));155 var inst = container.Instance;156 Assert.Equal(10, inst.From.Id);157 Assert.Equal(20, inst.To.Id);158 Assert.Equal(30, inst.BillingAccount.Id);159 }160 [TestMethod, TestCategory("Lite"), TestCategory("Ninject")]161 public void ShouldArrangeMultipleInstancesSeparatelyByPropertyName()162 {163 var container = new MockingContainer<TransactionService>();164 container.Bind<IAccount>().ToMock().InjectedIntoProperty("BillingAccount").AndArrange(x => Mock.Arrange(() => x.Id).Returns(30));165 var inst = container.Instance;166 Assert.Equal(30, inst.BillingAccount.Id);167 }168 [TestMethod, TestCategory("Lite"), TestCategory("Ninject")]169 public void ShouldAssertMultipleInstancesByName()170 {171 var container = new MockingContainer<TransactionService>();172 container.Bind<IAccount>().ToMock().InjectedIntoParameter("fromAccount").Named("from")173 .AndArrange(x => Mock.Arrange(() => x.Id).Returns(10));174 container.Bind<IAccount>().ToMock().InjectedIntoParameter("toAccount").Named("to")175 .AndArrange(x => Mock.Arrange(() => x.Id).Returns(20));176 container.Bind<IAccount>().ToMock().InjectedIntoProperty((TransactionService s) => s.BillingAccount).Named("bill")177 .AndArrange(x => Mock.Arrange(() => x.Id).Returns(30));178 var inst = container.Instance;179 inst.TransferFunds(10);180 container.Assert<IAccount>("from", x => x.Withdraw(11), Occurs.Once());181 container.Assert<IAccount>("to", x => x.Deposit(10), Occurs.Once());182 container.Assert<IAccount>("bill", x => x.Deposit(1), Occurs.Once());183 }184 public class VariousCtors185 {186 public VariousCtors(IFileSystem fs)187 {188 }189 public VariousCtors(IFileSystem fs, ICalendar calendar)190 {191 throw new InvalidOperationException();192 }193 }194 [TestMethod, TestCategory("Lite"), TestCategory("Ninject")]195 public void ShouldSelectConstructorBasedOnSettings()196 {197 // assert the default NInject behavior that injects into the constructor with most parameters198 var container = new MockingContainer<VariousCtors>();199 Assert.Throws<InvalidOperationException>(() => { var inst = container.Instance; });200 // assert the overriden constructor lookup behavior201 var container2 = new MockingContainer<VariousCtors>(new AutoMockSettings { ConstructorArgTypes = new[] { typeof(IFileSystem) } });202 Assert.NotNull(container2.Instance);203 // assert that specifying an invalid constructor throws204 Assert.Throws<MockException>(() => new MockingContainer<VariousCtors>(new AutoMockSettings { ConstructorArgTypes = new[] { typeof(ICalendar) } }));205 }206 public interface IService207 {208 int Value { get; set; }209 }210 public class Module211 {212 public IService service;213 public Module(IService service)214 {215 this.service = service;216 }217 }218 [TestMethod, TestCategory("Lite"), TestCategory("Ninject")]219 public void ShouldMakeSingletonExplicitlyRequestedServices()220 {221 var container = new MockingContainer<Module>();222 var s1 = container.Get<IService>();223 var s2 = container.Instance.service;224 Assert.Same(s1, s2);225 }226 [TestMethod, TestCategory("Lite"), TestCategory("Ninject")]227 public void ShouldArrangePropertySet()228 {229 // Arrange230 var container = new MockingContainer<Module>();231 container.ArrangeSet<IService>(x => x.Value = 99).MustBeCalled();232 var service = container.Get<IService>();233 // Act 234 service.Value = 99;235 // Assert236 container.Assert<IService>();237 }238 [TestMethod, TestCategory("Lite"), TestCategory("Ninject")]239 public void ShouldArrangePropertySetWithMatcher()240 {241 // Arrange242 var container = new MockingContainer<Module>();243 container.ArrangeSet<IService>(x => x.Value = Arg.AnyInt).MustBeCalled();244 var service = container.Get<IService>();245 // Act 246 service.Value = 99;247 // Assert248 container.Assert<IService>();249 }250 [TestMethod, TestCategory("Lite"), TestCategory("Ninject")]251 public void ShouldAssertPropertySet()252 {253 // Arrange254 var container = new MockingContainer<Module>();255 // Act 256 container.Get<IService>().Value = 99;257 // Assert258 container.AssertSet<IService>(x => x.Value = 99);259 }260 [TestMethod, TestCategory("Lite"), TestCategory("Ninject")]261 public void ShouldAssertPropertySetWithMatcher()262 {263 // Arrange264 var container = new MockingContainer<Module>();265 // Act 266 container.Get<IService>().Value = 99;267 // Assert268 container.AssertSet<IService>(x => x.Value = Arg.AnyInt);269 }270 [TestMethod, TestCategory("Lite"), TestCategory("Ninject")]271 public void ShouldAssertPropertySetNegative()272 {273 DebugView.IsTraceEnabled = true;274 // Arrange275 var container = new MockingContainer<Module>();276 // Assert277 container.AssertSet<IService>(x => x.Value = 99, Occurs.Never());278 }279 [TestMethod, TestCategory("Lite"), TestCategory("Ninject")]280 public void ShouldAssertPropertySetNegativeWithMatcher()281 {282 // Arrange283 var container = new MockingContainer<Module>();284 // Assert285 container.AssertSet<IService>(x => x.Value = Arg.AnyInt, Occurs.Never());286 }287 [TestMethod, TestCategory("Lite"), TestCategory("AutoMock")]288 public void ShouldAssertRaisesAgainstMethod()289 {290 var container = new MockingContainer<Executor>();291 bool raised = false;292 container.Arrange<IExecutor>(x => x.Submit()).Raises(() => container.Get<IExecutor>().Done += null, EventArgs.Empty);293 container.Get<IExecutor>().Done += delegate { raised = true; };294 container.Instance.Submit();295 Assert.True(raised);296 }297 public class Executor298 {299 public Executor(IExecutor executor)300 {301 this.executor = executor;302 }303 public void Submit()304 {305 this.executor.Submit();306 }307 private IExecutor executor;308 }309 public interface IExecutor310 {311 event EventHandler<EventArgs> Done;312 event EventHandler Executed;313 void Submit();314 }315 [TestMethod, TestCategory("Lite"), TestCategory("AutoMock")]316 public void ShouldAssertMockingNestedDependency()317 {318 var container = new MockingContainer<Foo>();319 container.Bind<Bar>().ToSelf();320 container.Arrange<IUnitOfWork>(uow => uow.DoWork()).MustBeCalled();321 Assert.Throws<AssertionException>(() => container.Assert());322 container.Instance.DoWork();323 container.Assert();324 }325 public class Foo326 {327 public Foo(Bar bar)328 {329 this.bar = bar;330 }331 public void DoWork()332 {333 this.bar.DoWork();334 }335 private readonly Bar bar;336 }337 public class Bar338 {339 public Bar(IUnitOfWork unitOfWork)340 {341 this.unitOfWork = unitOfWork;342 }343 public void DoWork()344 {345 this.unitOfWork.DoWork();346 }347 private readonly IUnitOfWork unitOfWork;348 }349 public interface IUnitOfWork350 {351 void DoWork();352 }353 [TestMethod, TestCategory("Lite"), TestCategory("AutoMock")]354 public void ShouldResolveTargetTypeWithInterfaceAndConcreteDependencies()355 {356 var container = new MockingContainer<Unit>();357 container.Arrange<IUnitOfWork>(uow => uow.DoWork()).MustBeCalled();358 // this is where it resolves.359 container.Instance.DoWork();360 container.Assert();361 }362 public class Unit363 {364 public Unit(IUnitOfWork unitOfWork, WorkItem workItem)365 {366 this.unitOfWork = unitOfWork;367 this.workItem = workItem;368 }369 public void DoWork()370 {371 workItem.DoWork();372 unitOfWork.DoWork();373 }374 private readonly IUnitOfWork unitOfWork;375 private readonly WorkItem workItem;376 }377 public class WorkItem378 {379 public void DoWork()380 {381 }382 }383 [TestMethod, TestCategory("Lite"), TestCategory("AutoMock")]384 public void ShouldAssertOccurrenceFromContainerWithoutPriorArrangement()385 {386 var c = new MockingContainer<Unit>();387 c.Instance.DoWork();388 c.Assert<IUnitOfWork>(x => x.DoWork());389 }390 public class DisposableContainer : IDisposable391 {392 public IList<IDisposable> Disposables;393 public DisposableContainer(IList<IDisposable> disposables)394 {395 this.Disposables = disposables;396 }397 public void Dispose()398 {399 this.Disposables.Clear();400 }401 }402 [TestMethod, TestCategory("Lite"), TestCategory("AutoMock")]...
EventsFixture.cs
Source:EventsFixture.cs
...18using Telerik.JustMock.Core;19using Telerik.JustMock.Tests.EventFixureDependencies;20#region JustMock Test Attributes21#if NUNIT22using NUnit.Framework;23using TestCategory = NUnit.Framework.CategoryAttribute;24using TestClass = NUnit.Framework.TestFixtureAttribute;25using TestMethod = NUnit.Framework.TestAttribute;26using TestInitialize = NUnit.Framework.SetUpAttribute;27using TestCleanup = NUnit.Framework.TearDownAttribute;28using AssertionException = NUnit.Framework.AssertionException;29#elif XUNIT30using Xunit;31using Telerik.JustMock.XUnit.Test.Attributes;32using TestCategory = Telerik.JustMock.XUnit.Test.Attributes.XUnitCategoryAttribute;33using TestClass = Telerik.JustMock.XUnit.Test.Attributes.EmptyTestClassAttribute;34using TestMethod = Xunit.FactAttribute;35using TestInitialize = Telerik.JustMock.XUnit.Test.Attributes.EmptyTestInitializeAttribute;36using TestCleanup = Telerik.JustMock.XUnit.Test.Attributes.EmptyTestCleanupAttribute;37using AssertionException = Telerik.JustMock.XUnit.AssertFailedException;38#elif VSTEST_PORTABLE39using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;40using AssertionException = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.AssertFailedException;41#else42using Microsoft.VisualStudio.TestTools.UnitTesting;43using AssertionException = Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException;44#endif45#endregion46#if XUNIT247#pragma warning disable xUnit1013 48#endif49namespace Telerik.JustMock.Tests50{51 [TestClass]52 public class EventsFixture53 {54 private ProjectNavigatorViewModel viewModel;55 private ISolutionService solutionService;56#if XUNIT57 public EventsFixture()58 {59 Initialize();60 }61#endif62 [TestInitialize]63 public void Initialize()64 {65 this.solutionService = Mock.Create<ISolutionService>();66 this.viewModel = new ProjectNavigatorViewModel(this.solutionService);67 }68 [TestMethod, TestCategory("Lite"), TestCategory("Events")]69 public void ShouldRaiseCustomEventOnMethodCall()70 {71 var foo = Mock.Create<IFoo>();72 const string expected = "ping";73 string actual = string.Empty;74 Mock.Arrange(() => foo.RaiseMethod()).Raises(() => foo.CustomEvent += null, expected);75 foo.CustomEvent += (s) => { actual = s; };76 foo.RaiseMethod();77 Assert.Equal(expected, actual);78 }79 [TestMethod, TestCategory("Lite"), TestCategory("Events")]80 public void ShoulRaiseCustomEventForFuncCalls()81 {82 bool echoed = false;83 var foo = Mock.Create<IFoo>();84 Mock.Arrange(() => foo.Echo("string")).Raises(() => foo.EchoEvent += null, true).Returns("echoed");85 foo.EchoEvent += (c) => { echoed = c; };86 Assert.Equal(foo.Echo("string"), "echoed");87 Assert.True(echoed);88 }89 [TestMethod, TestCategory("Lite"), TestCategory("Events")]90 public void ShouldRaiseEventWhenExpectationIsMet()91 {92 var executor = Mock.Create<IExecutor<int>>();93 bool raised = false;94 Mock.Arrange(() => executor.Execute(Arg.IsAny<int>())).Raises(() => executor.Executed += null, EventArgs.Empty);95 executor.Executed += delegate { raised = true; };96 executor.Execute(1);97 Assert.True(raised);98 }99 [TestMethod, TestCategory("Lite"), TestCategory("Events")]100 public void ShouldRaiseEventForEventArgsLambdaWithOneArgument()101 {102 var executor = Mock.Create<IExecutor<int>>();103 Mock.Arrange(() => executor.Execute(Arg.IsAny<string>()))104 .Raises(() => executor.Done += null, (string s) => new FooArgs { Value = s });105 FooArgs args = null;106 executor.Done += (sender, e) => args = e;107 executor.Execute("done");108 Assert.Equal(args.Value, "done");109 }110 [TestMethod, TestCategory("Lite"), TestCategory("Events")]111 public void ShouldRaiseEventForEventArgsLambdaWithTwoArguments()112 {113 var executor = Mock.Create<IExecutor<int>>();114 Mock.Arrange(() => executor.Execute(Arg.IsAny<string>(), Arg.IsAny<int>()))115 .Raises(() => executor.Done += null, (string s, int i) => new FooArgs { Value = s + i });116 FooArgs args = null;117 executor.Done += (sender, e) => args = e;118 executor.Execute("done", 2);119 Assert.Equal(args.Value, "done2");120 }121 [TestMethod, TestCategory("Lite"), TestCategory("Events")]122 public void ShouldRaiseEventForEventArgsLambdaWithThreeArguments()123 {124 var executor = Mock.Create<IExecutor<int>>();125 Mock.Arrange(() => executor.Execute(Arg.IsAny<string>(), Arg.IsAny<int>(), Arg.IsAny<bool>()))126 .Raises(() => executor.Done += null, (string s, int i, bool b) => new FooArgs { Value = s + i + b });127 FooArgs args = null;128 executor.Done += (sender, e) => args = e;129 executor.Execute("done", 3, true);130 Assert.Equal(args.Value, "done3True");131 }132 [TestMethod, TestCategory("Lite"), TestCategory("Events")]133 public void ShouldRaiseEventForEventArgsLambdaWithFourArguments()134 {135 var executor = Mock.Create<IExecutor<int>>();136 Mock.Arrange(() => executor.Execute(Arg.IsAny<string>(), Arg.IsAny<int>(), Arg.IsAny<bool>(), Arg.IsAny<string>()))137 .Raises(() => executor.Done += null, (string s, int i, bool b, string s1) => new FooArgs { Value = s + i + b + s1 });138 FooArgs args = null;139 executor.Done += (sender, e) => args = e;140 executor.Execute("done", 4, true, "ok");141 Assert.Equal(args.Value, "done4Trueok");142 }143 [TestMethod, TestCategory("Lite"), TestCategory("Events")]144 public void ShouldAssertRaiseAndReturnForFuncCallWithOneArg()145 {146 var executor = Mock.Create<IExecutor<int>>();147 Mock.Arrange(() => executor.Echo(Arg.IsAny<string>()))148 .Raises(() => executor.Done += null, (string s) => new FooArgs { Value = s })149 .Returns((string s) => s);150 FooArgs args = null;151 executor.Done += (sender, e) => args = e;152 Assert.Equal(executor.Echo("echo"), args.Value);153 }154 [TestMethod, TestCategory("Lite"), TestCategory("Events")]155 public void ShouldAssertMultipleEventSubscription()156 {157 var foo = Mock.Create<IFoo>();158 Mock.Arrange(() => foo.Execute()).Raises(() => foo.EchoEvent += null, true);159 bool echoed1 = false;160 bool echoed2 = false;161 foo.EchoEvent += c => { echoed1 = c; };162 foo.EchoEvent += c => { echoed2 = c; };163 foo.Execute();164 Assert.True(echoed1);165 Assert.True(echoed2);166 }167 [TestMethod, TestCategory("Lite"), TestCategory("Events")]168 public void ShouldRaiseEventWithStandardEventArgs()169 {170 var executor = Mock.Create<IExecutor<int>>();171 string acutal = null;172 string expected = "ping";173 executor.Done += delegate(object sender, FooArgs args)174 {175 acutal = args.Value;176 };177 Mock.Raise(() => executor.Done += null, new FooArgs(expected));178 Assert.Equal(expected, acutal);179 }180 [TestMethod, TestCategory("Lite"), TestCategory("Events")]181 public void ShouldRaiseEventWithCustomEventArgs()182 {183 var foo = Mock.Create<IFoo>();184 string expected = "ping";185 string acutal = string.Empty;186 foo.CustomEvent += delegate(string s)187 {188 acutal = s;189 };190 Mock.Raise(() => foo.CustomEvent += null, expected);191 Assert.Equal(expected, acutal);192 }193 [TestMethod, TestCategory("Lite"), TestCategory("Events"), TestCategory("MockingContext")]194 public void ShouldAssertMockRaiseFromInsideAContainer()195 {196 var foo = Mock.Create<IFoo>();197 var projectEventArgs = new ProjectEventArgs(foo);198 Mock.Raise(() => this.solutionService.ProjectAdded += null, projectEventArgs);199 Assert.True(this.viewModel.IsProjectAddedCalled);200 }201 [TestMethod, TestCategory("Lite"), TestCategory("Events")]202 public void ShouldNotCallDelegateAfterEventDetach()203 {204 var executor = Mock.Create<IExecutor<int>>();205 Mock.Arrange(() => executor.Execute(Arg.IsAny<string>()))206 .Raises(() => executor.Done += null, (string s) => new FooArgs { Value = s });207 FooArgs args = null;208 EventHandler<FooArgs> handler = (sender, e) => args = e;209 executor.Done += (o, e) => { };210 executor.Done += handler;211 executor.Execute("done");212 Assert.Equal(args.Value, "done");213 executor.Done -= handler;214 args = null;215 executor.Execute("done");216 Assert.Null(args);217 }218 [TestMethod, TestCategory("Lite"), TestCategory("Events")]219 public void ShouldRetainArrangementsInRaiseDelegate()220 {221 var activeDocument = Mock.Create<IDocument>(Behavior.Loose);222 var activeView = Mock.Create<IDocumentView>();223 Mock.Arrange(() => activeView.Document).Returns(activeDocument);224 Mock.Raise(() => activeView.Document.IsDirtyChanged += null, EventArgs.Empty);225 }226 public interface IHasEvent227 {228 event Action StuffHappened;229 int Value { get; }230 }231 [TestMethod, TestCategory("Lite"), TestCategory("Events")]232 public void ShouldRetainArrangementsInMockEventHandler()233 {234 var mock = Mock.Create<IHasEvent>();235 Mock.Arrange(() => mock.Value).Returns(5);236 int actualValue = 0;237 mock.StuffHappened += () => actualValue = mock.Value;238 Mock.Raise(() => mock.StuffHappened += null);239 Assert.Equal(5, actualValue);240 }241#if !COREFX242 [TestMethod, TestCategory("Lite"), TestCategory("Events")]243 public void ShouldRetainArrangementsInEventHandlerFromPrivateAccessor()244 {245 var mock = Mock.Create<IHasEvent>();246 Mock.Arrange(() => mock.Value).Returns(5);247 int actualValue = 0;248 var coll = new ObservableCollection<object>();249 coll.CollectionChanged += (o, e) => actualValue = mock.Value;250 new PrivateAccessor(coll).RaiseEvent("CollectionChanged", coll, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));251 Assert.Equal(5, actualValue);252 }253 [TestMethod, TestCategory("Lite"), TestCategory("Events")]254 public void ShouldRetainArrangementsInEventHandlerFromPrivateAccessorForEventWithRaiseMethod()255 {256 var mock = Mock.Create<IHasEvent>();257 Mock.Arrange(() => mock.Value).Returns(5);258 int actualValue = 0;259 var type = EventClassFactory.CreateClassWithEventWithRaiseMethod();260 var obj = Activator.CreateInstance(type);261 Action probe = () => actualValue = mock.Value;262 type.GetField("Probe").SetValue(obj, probe);263 new PrivateAccessor(obj).RaiseEvent("StuffHappened");264 Assert.Equal(5, actualValue);265 }266#endif267 [TestMethod, TestCategory("Lite"), TestCategory("Events")]268 public void ShouldAssertEventHandlerAddingOccurrence()269 {270 var doc = Mock.Create<IDocument>();271 Mock.ArrangeSet<IDocument>(() => doc.IsDirtyChanged += null).IgnoreArguments().OccursOnce();272 Assert.Throws<AssertionException>(() => Mock.Assert(doc));273 doc.IsDirtyChanged += (o, e) => { };274 Mock.Assert(doc);275 }276 [TestMethod, TestCategory("Lite"), TestCategory("Events")]277 public void ShouldRaiseEventWithNullEventArgsArgument()278 {279 var doc = Mock.Create<IDocument>();280 EventArgs args = EventArgs.Empty;281 doc.IsDirtyChanged += (o, e) => args = e;282 Mock.Raise(() => doc.IsDirtyChanged += null, null);283 }284 [TestMethod, TestCategory("Lite"), TestCategory("Events")]285 public void ShouldThrowIncompatibleSignatureExceptionWhenExpectedArgumentsDontMatch()286 {287 var doc = Mock.Create<IDocument>();288 doc.IsDirtyChanged += (o, e) => { };289 Assert.Throws<Exception>(() => Mock.Raise(() => doc.IsDirtyChanged += null));290 Assert.Throws<Exception>(() => Mock.Raise(() => doc.IsDirtyChanged += null, 1, 2));291 }292 public interface IDocumentView293 {294 IDocument Document { get; }295 }296 public interface IDocument297 {298 event EventHandler IsDirtyChanged;299 }300 [TestMethod, TestCategory("Lite"), TestCategory("Events"), TestCategory("NonPublic")]301 public void ShouldRaiseCSharpEventOnNonmock()302 {303#if COREFX304 if (Mock.IsProfilerEnabled)305#endif306 {307 var hasEvent = new HasEvent();308 bool called = false;309 hasEvent.Event += () => called = true;310 Mock.NonPublic.Raise(hasEvent, "Event");311 Assert.True(called);312 }313 }314 [TestMethod, TestCategory("Lite"), TestCategory("Events"), TestCategory("NonPublic")]315 public void ShouldRaiseEventOnMockByName()316 {317#if COREFX318 if (Mock.IsProfilerEnabled)319#endif320 {321 var hasEvent = Mock.Create<HasEvent>();322 bool called = false;323 hasEvent.Event += () => called = true;324 Mock.NonPublic.Raise(hasEvent, "Event");325 Assert.True(called);326 }327 }328 [TestMethod, TestCategory("Lite"), TestCategory("Events"), TestCategory("NonPublic")]329 public void ShouldRaiseStaticEventOnNonmockByName()330 {331#if COREFX332 if (Mock.IsProfilerEnabled)333#endif334 {335 bool called = false;336 HasEvent.StaticEvent += () => called = true;337 Mock.NonPublic.Raise(typeof(HasEvent), "StaticEvent");338 Assert.True(called);339 }340 }341 public class HasEvent342 {343 public virtual event Action Event;344 public static event Action StaticEvent;345 }346 }347 [TestClass]348 public class RecordingWorksWhenTestClassHasMockMixin349 {350 private IDocumentView activeView;351#if XUNIT352 public RecordingWorksWhenTestClassHasMockMixin()353 {354 BeforeEach();355 }356#endif357 [TestInitialize]358 public void BeforeEach()359 {360 var activeDocument = Mock.Create<IDocument>();361 this.activeView = Mock.Create<IDocumentView>();362 Mock.Arrange(() => this.activeView.Document).Returns(activeDocument);363 }364 [TestMethod, TestCategory("Lite"), TestCategory("Events")]365 public void ActiveDocument_WhenIsDirtyChanged_ShouldRaiseCanExecuteChangedEvent()366 {367 Mock.Raise(() => this.activeView.Document.IsDirtyChanged += null, EventArgs.Empty);368 }369 public interface IDocumentView370 {371 IDocument Document { get; }372 }373 public interface IDocument374 {375 event EventHandler IsDirtyChanged;376 }377 }378}379#if XUNIT2380#pragma warning restore xUnit1013 381#endif...
Mock.Raise.cs
Source:Mock.Raise.cs
...11 See the License for the specific language governing permissions and12 limitations under the License.13*/14using System;15using Microsoft.VisualStudio.TestTools.UnitTesting;16using Telerik.JustMock;17namespace JustMock.NonElevatedExamples.BasicUsage.Mock_Raise18{19 /// <summary>20 /// The Raise method is used for raising mocked events. You can use custom or standard events.21 /// See http://www.telerik.com/help/justmock/basic-usage-mock-raise.html for full documentation of the feature.22 /// </summary>23 [TestClass]24 public class Mock_Raise_Tests25 {26 [TestMethod]27 public void ShouldInvokeMethodForACustomEventWhenRaised()28 {29 // ARRANGE...
Unit
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using Telerik.JustMock;7using Telerik.JustMock.Core;8{9 {10 public virtual void Unit()11 {12 Console.WriteLine("Unit");13 }14 }15}16using System;17using System.Collections.Generic;18using System.Linq;19using System.Text;20using System.Threading.Tasks;21using Telerik.JustMock;22using Telerik.JustMock.Core;23{24 {25 public virtual void Unit()26 {27 Console.WriteLine("Unit");28 }29 }30}31using System;32using System.Collections.Generic;33using System.Linq;34using System.Text;35using System.Threading.Tasks;36using Telerik.JustMock;37using Telerik.JustMock.Core;38{39 {40 public virtual void Unit()41 {42 Console.WriteLine("Unit");43 }44 }45}46using System;47using System.Collections.Generic;48using System.Linq;49using System.Text;50using System.Threading.Tasks;51using Telerik.JustMock;52using Telerik.JustMock.Core;53{54 {55 public virtual void Unit()56 {57 Console.WriteLine("Unit");58 }59 }60}61using System;62using System.Collections.Generic;63using System.Linq;64using System.Text;65using System.Threading.Tasks;66using Telerik.JustMock;67using Telerik.JustMock.Core;68{69 {70 public virtual void Unit()71 {72 Console.WriteLine("Unit");73 }74 }75}76using System;77using System.Collections.Generic;78using System.Linq;79using System.Text;80using System.Threading.Tasks;81using Telerik.JustMock;82using Telerik.JustMock.Core;83{84 {
Unit
Using AI Code Generation
1public void TestMethod1()2{3 Telerik.JustMock.Tests.Executor.Unit();4}5public void TestMethod2()6{7 Telerik.JustMock.Tests.Executor.Unit();8}9public void TestMethod3()10{11 Telerik.JustMock.Tests.Executor.Unit();12}13public void TestMethod4()14{15 Telerik.JustMock.Tests.Executor.Unit();16}17public void TestMethod5()18{19 Telerik.JustMock.Tests.Executor.Unit();20}21public void TestMethod6()22{23 Telerik.JustMock.Tests.Executor.Unit();24}25public void TestMethod7()26{27 Telerik.JustMock.Tests.Executor.Unit();28}29public void TestMethod8()30{31 Telerik.JustMock.Tests.Executor.Unit();32}33public void TestMethod9()34{35 Telerik.JustMock.Tests.Executor.Unit();36}37public void TestMethod10()38{39 Telerik.JustMock.Tests.Executor.Unit();40}41public void TestMethod11()42{43 Telerik.JustMock.Tests.Executor.Unit();44}45public void TestMethod12()46{47 Telerik.JustMock.Tests.Executor.Unit();48}
Unit
Using AI Code Generation
1Mock.Arrange(() => Executor.Unit(1)).DoNothing();2Executor.Unit(1);3Mock.Assert(() => Executor.Unit(1));4Mock.Arrange(() => Executor.Unit(2)).DoNothing();5Executor.Unit(2);6Mock.Assert(() => Executor.Unit(2));7Mock.Arrange(() => Executor.Unit(3)).DoNothing();8Executor.Unit(3);9Mock.Assert(() => Executor.Unit(3));10Mock.Arrange(() => Executor.Unit(4)).DoNothing();11Executor.Unit(4);12Mock.Assert(() => Executor.Unit(4));13Mock.Arrange(() => Executor.Unit(5)).DoNothing();14Executor.Unit(5);15Mock.Assert(() => Executor.Unit(5));16Mock.Arrange(() => Executor.Unit(6)).DoNothing();17Executor.Unit(6);18Mock.Assert(() => Executor.Unit(6));19Mock.Arrange(() => Executor.Unit(7)).DoNothing();20Executor.Unit(7);21Mock.Assert(() => Executor.Unit(7));22Mock.Arrange(() => Executor.Unit(8)).DoNothing();23Executor.Unit(8);24Mock.Assert(() => Executor.Unit(8));25Mock.Arrange(() => Executor.Unit(9)).DoNothing();26Executor.Unit(9);27Mock.Assert(() => Executor.Unit(9));28Mock.Arrange(() => Executor.Unit(10)).DoNothing();29Executor.Unit(10);30Mock.Assert(() => Executor.Unit(10));
Unit
Using AI Code Generation
1using Telerik.JustMock.Tests;2using Telerik.JustMock;3using System;4using System.Linq;5using System.Collections.Generic;6using System.Text;7{8 {9 public string Unit(int a, int b)10 {11 return "a";12 }13 }14}15using Telerik.JustMock.Tests;16using Telerik.JustMock;17using System;18using System.Linq;19using System.Collections.Generic;20using System.Text;21{22 {23 public string Unit(int a, int b)24 {25 return "b";26 }27 }28}29using Telerik.JustMock.Tests;30using Telerik.JustMock;31using System;32using System.Linq;33using System.Collections.Generic;34using System.Text;35{36 {37 public string Unit(int a, int b)38 {39 return "c";40 }41 }42}43using Telerik.JustMock.Tests;44using Telerik.JustMock;45using System;46using System.Linq;47using System.Collections.Generic;48using System.Text;49{50 {51 public string Unit(int a, int b)52 {53 return "d";54 }55 }56}57using Telerik.JustMock.Tests;58using Telerik.JustMock;59using System;60using System.Linq;61using System.Collections.Generic;62using System.Text;63{64 {65 public string Unit(int a, int b)66 {67 return "e";68 }69 }70}71using Telerik.JustMock.Tests;72using Telerik.JustMock;73using System;74using System.Linq;75using System.Collections.Generic;76using System.Text;77{78 {79 public string Unit(int a, int b)80 {
Unit
Using AI Code Generation
1using Telerik.JustMock.Tests;2{3 {4 public void MyMethod()5 {6 Executor.Unit();7 }8 }9}10using Telerik.JustMock.Tests;11{12 {13 public void MyMethod()14 {15 Executor.Unit();16 }17 }18}19using Telerik.JustMock.Tests;20{21 {22 public void MyMethod()23 {24 Executor.Unit();25 }26 }27}28using Telerik.JustMock.Tests;29{30 {31 public void MyMethod()32 {33 Executor.Unit();34 }35 }36}37using Telerik.JustMock.Tests;38{39 {40 public void MyMethod()41 {42 Executor.Unit();43 }44 }45}46using Telerik.JustMock.Tests;47{48 {49 public void MyMethod()50 {51 Executor.Unit();52 }53 }54}55using Telerik.JustMock.Tests;56{57 {58 public void MyMethod()59 {60 Executor.Unit();61 }62 }63}
Unit
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Reflection;6using System.IO;7using System.Reflection.Emit;8using System.Threading;9using System.Threading.Tasks;10using Telerik.JustMock;11using Telerik.JustMock.Tests;12{13 {14 public static object Unit(string assemblyName, string className, string methodName, object[] parameters)15 {16 Assembly assembly = Assembly.LoadFrom(assemblyName);17 Type type = assembly.GetType(className);18 MethodInfo method = type.GetMethod(methodName);19 object result = method.Invoke(null, parameters);20 return result;21 }22 }23}24using System;25using System.Collections.Generic;26using System.Linq;27using System.Text;28using System.Reflection;29using System.IO;30using System.Reflection.Emit;31using System.Threading;32using System.Threading.Tasks;33using Telerik.JustMock;34using Telerik.JustMock.Tests;35{36 {37 public static object Unit(string assemblyName, string className, string methodName, object[] parameters)38 {39 Assembly assembly = Assembly.LoadFrom(assemblyName);40 Type type = assembly.GetType(className);41 MethodInfo method = type.GetMethod(methodName);42 object result = method.Invoke(null, parameters);43 return result;44 }45 }46}47using System;48using System.Collections.Generic;49using System.Linq;50using System.Text;51using System.Reflection;52using System.IO;
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!