How to use From method of Telerik.JustMock.Tests.FooGeneric class

Best JustMockLite code snippet using Telerik.JustMock.Tests.FooGeneric.From

MockFixture.cs

Source:MockFixture.cs Github

copy

Full Screen

...70 var bar = Mock.Create<IBar>();71 Assert.NotNull(bar);72 }73 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]74 public void ShouldReturnServiceFromServiceProvider()75 {76 var provider = Mock.Create<IServiceProvider>();77 Mock.Arrange(() => provider.GetService(typeof(IFooService))).Returns(new FooService());78 Assert.True(provider.GetService(typeof(IFooService)) is FooService);79 }80 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]81 public void ShouldAssertDoInstead()82 {83 var foo = Mock.Create<IFoo>();84 bool called = false;85 Mock.Arrange(() => foo.Execute(Arg.IsAny<string>()))86 .DoInstead(() => { called = true; })87 .Returns((string s) => s);88 Assert.Equal(foo.Execute("ping"), "ping");89 Assert.True(called);90 }91 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]92 public void ShouldAssertDoInsteadForOneArgFromMethod()93 {94 int expected = 0;95 var foo = Mock.Create<IFoo>();96 Mock.Arrange(() => foo.Submit(Arg.IsAny<int>()))97 .DoInstead((int arg1) => { expected = arg1; });98 foo.Submit(10);99 Assert.Equal(10, expected);100 }101 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]102 public void ShouldAssertDoInsteadForTwoArgsFromMethod()103 {104 int expected = 0;105 var foo = Mock.Create<IFoo>();106 Mock.Arrange(() => foo.Submit(Arg.IsAny<int>(), Arg.IsAny<int>()))107 .DoInstead((int arg1, int arg2) => { expected = arg1 + arg2; });108 foo.Submit(10, 10);109 Assert.Equal(20, expected);110 }111 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]112 public void ShouldAssertDoInsteadForThreeArgsFromMethod()113 {114 int expected = 0;115 var foo = Mock.Create<IFoo>();116 Mock.Arrange(() => foo.Submit(Arg.IsAny<int>(), Arg.IsAny<int>(), Arg.IsAny<int>()))117 .DoInstead((int arg1, int arg2, int arg3) => { expected = arg1 + arg2 + arg3; });118 foo.Submit(10, 10, 10);119 Assert.Equal(30, expected);120 }121 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]122 public void ShouldAssertDoInsteadForFourArgsFromMethod()123 {124 int expected = 0;125 var foo = Mock.Create<IFoo>();126 Mock.Arrange(() => foo.Submit(Arg.IsAny<int>(), Arg.IsAny<int>(), Arg.IsAny<int>(), Arg.IsAny<int>()))127 .DoInstead((int arg1, int arg2, int arg3, int arg4) => { expected = arg1 + arg2 + arg3 + arg4; });128 foo.Submit(10, 10, 10, 10);129 Assert.Equal(40, expected);130 }131 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]132 public void ShouldAssertDoInsteadForOneArgFromFunc()133 {134 int expected = 0;135 var foo = Mock.Create<IFoo>();136 Mock.Arrange(() => foo.Echo(Arg.IsAny<int>()))137 .DoInstead((int arg1) => { expected = arg1; })138 .Returns(() => expected);139 Assert.Equal(foo.Echo(10), expected);140 }141 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]142 public void ShouldAssertDoInsteadForTwoArgsFromFunc()143 {144 int expected = 0;145 var foo = Mock.Create<IFoo>();146 Mock.Arrange(() => foo.Echo(Arg.IsAny<int>(), Arg.IsAny<int>()))147 .DoInstead((int arg1, int arg2) => { expected = arg1 + arg2; })148 .Returns(() => expected);149 Assert.Equal(foo.Echo(10), expected);150 }151 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]152 public void ShouldAssertDoInsteadForThreeArgsFromFunc()153 {154 int expected = 0;155 var foo = Mock.Create<IFoo>();156 Mock.Arrange(() => foo.Echo(Arg.IsAny<int>(), Arg.IsAny<int>(), Arg.IsAny<int>()))157 .DoInstead((int arg1, int arg2, int arg3) => { expected = arg1 + arg2 + arg3; })158 .Returns(() => expected);159 Assert.Equal(foo.Echo(10), expected);160 }161 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]162 public void ShouldAssertDoInsteadForFourArgsFromFunc()163 {164 int expected = 0;165 var foo = Mock.Create<IFoo>();166 Mock.Arrange(() => foo.Echo(Arg.IsAny<int>(), Arg.IsAny<int>(), Arg.IsAny<int>(), Arg.IsAny<int>()))167 .DoInstead((int arg1, int arg2, int arg3, int arg4) => { expected = arg1 + arg2 + arg3 + arg4; })168 .Returns(() => expected);169 Assert.Equal(foo.Echo(10), expected);170 }171 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]172 public void ShouldThrowIfArgumentsPassedForInterface()173 {174 Assert.Throws<Exception>(() => Mock.Create<IFoo>(25, true));175 }176 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]177 public void ShouldAssertCallOriginal()178 {179 var foo = Mock.Create<FooBase>();180 Mock.Arrange(() => foo.GetString("x")).CallOriginal();181 Mock.Arrange(() => foo.GetString("y")).Returns("z");182 Assert.Equal("x", foo.GetString("x"));183 Assert.Equal("z", foo.GetString("y"));184 }185 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]186 public void ShouldAssertGuidParam()187 {188 var foo = Mock.Create<IFoo>();189 Guid guid = Guid.NewGuid();190 bool called = false;191 Mock.Arrange(() => foo.Execute(guid)).DoInstead(() => called = true);192 foo.Execute(guid);193 Assert.True(called);194 }195 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]196 public void ShouldAssertCallOriginalForVoid()197 {198 var log = Mock.Create<Log>();199 Mock.Arrange(() => log.Info(Arg.IsAny<string>())).CallOriginal();200 Assert.Throws<Exception>(() => log.Info("test"));201 }202 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]203 public void ShouldPassArgumentToOriginal()204 {205 var log = Mock.Create<Log>();206 Mock.Arrange(() => log.Info("x")).CallOriginal();207 Assert.Equal(Assert.Throws<Exception>(() => log.Info("x")).Message, "x");208 }209 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]210 public void MockObjectShouldBeAssignableToMockedInterface()211 {212 var iFoo = Mock.Create<IFoo>();213 Assert.True(iFoo is IFoo);214 }215 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]216 public void ShouldAssertVoidCall()217 {218 var iFoo = Mock.Create<IFoo>();219 Mock.Arrange(() => iFoo.JustCall()).DoNothing();220 iFoo.JustCall();221 }222 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]223 public void ShouldAssertCallsThatAreMethodCalls()224 {225 const int arg = 2;226 var iBar = Mock.Create<IBar>();227 Mock.Arrange(() => iBar.Echo(Arg.IsAny<int>())).Returns(1);228 Assert.Equal(iBar.Echo(arg + 1), 1);229 }230 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]231 public void ShouldAssertGenericThrowsCall()232 {233 var iFoo = Mock.Create<IFoo>();234 Mock.Arrange(() => iFoo.Execute(Arg.IsAny<string>())).Throws<FormatException>();235 Assert.Throws<FormatException>(() => iFoo.Execute("crash"));236 }237 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]238 public void ShouldAssertThrowsHavingArguments()239 {240 var iFoo = Mock.Create<IFoo>();241 Mock.Arrange(() => iFoo.Execute(Arg.IsAny<string>())).Throws<CustomExepction>("test", true);242 Assert.Throws<CustomExepction>(() => iFoo.Execute("crash"));243 }244 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]245 public void ShouldAssertEqualityRefereces()246 {247 var iFoo1 = Mock.Create<IFoo>();248 var iFoo2 = Mock.Create<IFoo>();249 Assert.True(iFoo1.Equals(iFoo1));250 Assert.False(iFoo1.Equals(iFoo2));251 }252 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]253 public void TwoMockedObjectsShouldHavdDifferentHashCode()254 {255 var iFoo1 = Mock.Create<IFoo>();256 var iFoo2 = Mock.Create<IFoo>();257 Assert.NotEqual(iFoo1.GetHashCode(), iFoo2.GetHashCode());258 }259 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]260 public void ToStringShouldNotbeNullOrEmpty()261 {262 var foo = Mock.Create<IFoo>();263 Assert.False(String.IsNullOrEmpty(foo.ToString()));264 }265 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]266 public void ShouldMockClassWithNonDefaultConstructor()267 {268 var nonDefaultClass = Mock.Create<ClassWithNonDefaultConstructor>("ping", 1);269 Assert.NotNull(nonDefaultClass);270 }271 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]272 public void ShouldMockClassWithNonDefaultConstructorWithoutPassingAnything()273 {274 var nonDefaultClass = Mock.Create<ClassWithNonDefaultConstructor>();275 Assert.NotNull(nonDefaultClass);276 }277 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]278 public void ShouldMockClassWithNoDefaultConstructorWithNull()279 {280 var nonDefaultClass = Mock.Create<ClassWithNonDefaultConstructor>(null, 1);281 Assert.NotNull(nonDefaultClass);282 }283 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]284 public void ShoulsMockClassWithMultipleNonDefaultConstructor()285 {286 var nonDefaultClass = Mock.Create<ClassWithNonDefaultConstructor>(null, 1, true);287 Assert.NotNull(nonDefaultClass);288 }289 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]290 public void ShouldAssertGuidNonDefaultCtorWithDefaultIfNotSpecified()291 {292 var nonDefaultGuidClass = Mock.Create<ClassNonDefaultGuidConstructor>();293 Assert.Equal(nonDefaultGuidClass.guidValue, default(Guid));294 }295 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]296 public void ShouldAssertBaseCallWithGuid()297 {298 var foo = Mock.Create<FooBase>();299 Mock.Arrange(() => foo.GetGuid()).CallOriginal();300 Assert.Equal(foo.GetGuid(), default(Guid));301 }302 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]303 public void ShouldAssertImplementedInterface()304 {305 var implemented = Mock.Create<IFooImplemted>();306 Assert.NotNull(implemented);307 }308 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]309 public void ShouldAssertBaseForImplemetedInterface()310 {311 var implemented = Mock.Create<IFooImplemted>();312 Assert.True(implemented is IFoo);313 }314 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]315 public void SHouldAssertCallsFromBaseInImplemented()316 {317 var implemented = Mock.Create<IFooImplemted>();318 Mock.Arrange(() => implemented.Execute("hello")).Returns("world");319 Assert.Equal(implemented.Execute("hello"), "world");320 }321 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]322 public void ShouldMockObject_GetHashCodeMethod()323 {324 var foo = Mock.Create<FooBase>();325 Mock.Arrange(() => foo.GetHashCode()).Returns(1);326 Assert.Equal(1, foo.GetHashCode());327 }328 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]329 public void ShouldMockObject_ToStringMethod()330 {331 var foo = Mock.Create<FooBase>();332 Mock.Arrange(() => foo.ToString()).Returns("foo");333 Assert.Equal("foo", foo.ToString());334 }335 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]336 public void ShouldMockObject_EqualsMethod()337 {338 var foo = Mock.Create<FooBase>();339 Mock.Arrange(() => foo.Equals(Arg.IsAny<object>())).Returns(true);340 Assert.True(foo.Equals(new object()));341 }342 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]343 public void ShouldCallUnderlyingEquals()344 {345 var foo1 = Mock.Create<FooOverridesEquals>("foo");346 var foo2 = Mock.Create<FooOverridesEquals>("foo");347 Assert.True(foo1.Equals(foo2));348 }349 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]350 public void ShouldNotCallBaseByDefault()351 {352 var foo = Mock.Create<FooBase>();353 // this will not throw exception.354 foo.ThrowException();355 }356 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]357 public void ShouldTakeLatestSetup()358 {359 var foo = Mock.Create<IFoo>();360 Mock.Arrange(() => foo.Execute("ping")).Returns("pong");361 Mock.Arrange(() => foo.Execute(Arg.IsAny<string>())).Returns("pong");362 Assert.Equal(foo.Execute("nothing"), "pong");363 }364 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]365 public void ShouldOverrideBehaviorFromBaseClass()366 {367 var foo = Mock.Create<FooBase>();368 Mock.Arrange(() => foo.GetString("pong")).CallOriginal().InSequence();369 Mock.Arrange(() => foo.GetString(Arg.IsAny<string>())).Returns("ping").InSequence();370 Assert.Equal(foo.GetString("pong"), "pong");371 Assert.Equal(foo.GetString("it"), "ping");372 }373 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]374 public void ShouldAssertDateTimeAsRef()375 {376 var foo = Mock.Create<IFoo>();377 DateTime expected = new DateTime(2009, 11, 26);378 Mock.Arrange(() => foo.Execute(out expected)).DoNothing();379 DateTime acutal = DateTime.Now;380 foo.Execute(out acutal);381 Assert.Equal(expected, acutal);382 }383 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]384 public void ShouldAssertOutputParamPassedViaNested()385 {386 var nested = new Nested();387 nested.expected = 10;388 var foo = Mock.Create<IFoo>();389 Mock.Arrange(() => foo.Execute(out nested.expected));390 int actual = 0;391 foo.Execute(out actual);392 Assert.Equal(actual, 10);393 }394 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]395 public void ShouldNotInvokeOriginalCallWhenInitiatedFromCtor()396 {397 var foo = Mock.Create<FooAbstractCall>(false);398 Assert.NotNull(foo);399 }400 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]401 public void ShouldNotInvokeOriginalActionWhenInitiatedFromCtor()402 {403 var foo = Mock.Create<FooAbstractAction>();404 Assert.NotNull(foo);405 }406 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]407 public void ShouldNotInitalizeAsArgMatcherWhenProcessingMemberAccessArgument()408 {409 var foo = Mock.Create<IFoo>();410 Mock.Arrange(() => foo.Execute(false, BadGuid)).OccursOnce();411 foo.Execute(false, Guid.Empty);412 Mock.Assert(() => foo.Execute(Arg.IsAny<bool>(), Guid.Empty));413 }414 public static readonly Guid BadGuid = Guid.Empty;415 public abstract class FooAbstractCall416 {417 public FooAbstractCall(bool flag)418 {419 // invoke base will throw exception here.420 Initailize();421 }422 public abstract bool Initailize();423 }424 public abstract class FooAbstractAction425 {426 public FooAbstractAction()427 {428 // invoke base will throw exception here.429 Initailize();430 }431 public abstract void Initailize();432 }433#if !COREFX434 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]435 public void ShouldCreateMockClassWithInternalConstructor()436 {437 var foo = Mock.Create<FooWithInternalConstruct>();438 Assert.NotNull(foo);439 }440 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]441 public void ShouldAssertArrangeWithInternalConstructor()442 {443 var foo = Mock.Create<FooWithInternalConstruct>();444 bool called = false;445 Mock.Arrange(() => foo.Execute()).DoInstead(() => called = true);446 foo.Execute();447 Assert.True(called);448 }449#endif450 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]451 public void ShouldAssertGenericFuncCalls()452 {453 var genericClass = Mock.Create<FooGeneric<int>>();454 Mock.Arrange(() => genericClass.Get(1, 1)).Returns(10);455 Assert.Equal(genericClass.Get(1, 1), 10);456 }457 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]458 public void ShouldAssertGenericVoidCalls()459 {460 var genericClass = Mock.Create<FooGeneric<int>>();461 bool called = false;462 Mock.Arrange(() => genericClass.Execute(1)).DoInstead(() => called = true);463 genericClass.Execute(1);464 Assert.True(called);465 }466 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]467 public void ShouldAssertGenricMockWithNoGenericClass()468 {469 var genericClass = Mock.Create<FooGeneric>();470 Mock.Arrange(() => genericClass.Get<int, int>(1)).Returns(10);471 Assert.Equal(genericClass.Get<int, int>(1), 10);472 }473 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]474 public void ShouldAssertFuncWithOccurrence()475 {476 var foo = Mock.Create<IFoo>();477 Mock.Arrange(() => foo.Execute("x")).Returns("x");478 foo.Execute("x");479 Mock.Assert(() => foo.Execute("x"), Occurs.Exactly(1));480 }481 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]482 public void ShouldAssertOutputGenericArgument()483 {484 var fooGen = Mock.Create<FooGeneric>();485 int result = 0;486 fooGen.Execute<int, int>(out result);487 Assert.Equal(result, 0);488 }489 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]490 public void ShouldAssertArrangeForGenricOutArgument()491 {492 var fooGen = Mock.Create<FooGeneric>();493 int expected = 10;494 Mock.Arrange(() => fooGen.Execute<int, int>(out expected)).Returns(0);495 int actual = 0;496 fooGen.Execute<int, int>(out actual);497 Assert.Equal(expected, actual);498 }499 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]500 public void ShouldAssertParamArrayMatchArugments()501 {502 string expected = "bar";503 string argument = "foo";504 var target = Mock.Create<IParams>();505 Mock.Arrange(() => target.ExecuteParams(argument, "baz")).Returns(expected);506 string ret = target.ExecuteParams(argument, "baz");507 Assert.Equal(expected, ret);508 }509 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]510 public void ShouldDistinguiseMethodWithDifferentGenericArgument()511 {512 var foo = Mock.Create<FooGeneric>();513 Mock.Arrange(() => foo.Get<int>()).Returns(10);514 Mock.Arrange(() => foo.Get<string>()).Returns(12);515 Assert.Equal(foo.Get<string>(), 12);516 Assert.Equal(foo.Get<int>(), 10);517 }518 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]519 public void ShouldAssertParamArrayWithMatcherAndConcreteValue()520 {521 string expected = "bar";522 string argument = "foo";523 var target = Mock.Create<IParams>();524 Mock.Arrange(() => target.ExecuteByName(Arg.IsAny<int>(), argument)).Returns(expected);525 string ret = target.ExecuteByName(0, argument);526 Assert.Equal(expected, ret);527 }528 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]529 public void ShouldAssertCallWithMultipleMathers()530 {531 var foo = Mock.Create<IFoo>();532 Mock.Arrange(() => foo.Echo(Arg.Matches<int>(x => x == 10), Arg.Matches<int>(x => x == 10))).Returns(20);533 int ret = foo.Echo(10, 10);534 Assert.Equal(20, ret);535 }536 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]537 public void ShouldAssertArgumentMatherArgumentSetup()538 {539 var foo = Mock.Create<IFoo>();540 Mock.Arrange(() => foo.Echo(10, Arg.Matches<int>(x => x > 10 && x < 20), 21)).Returns(20);541 int ret = foo.Echo(10, 11, 21);542 Assert.Equal(20, ret);543 }544 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]545 public void ShouldAssertCallWithDefaultValues()546 {547 var foo = Mock.Create<IFoo>();548 Mock.Arrange(() => foo.Echo(0, 0)).Returns(2);549 int ret = foo.Echo(0, 0);550 Assert.Equal(2, ret);551 }552 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]553 public void ShouldCreateMockFromRealObject()554 {555 var realItem = Mock.Create(() => new RealItem());556 Assert.NotNull(realItem);557 }558 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]559 public void ShouldCreateMockFromRealObjectForNonDefaultConstructor()560 {561 var realItem = Mock.Create(() => new RealItem(10));562 Assert.NotNull(realItem);563 }564 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]565 public void ShouldCreateMockFromRealObjectThatHasOnlyNonDefaultCtor()566 {567 var realItem = Mock.Create(() => new RealItem2(10, string.Empty));568 Assert.NotNull(realItem);569 }570 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]571 public void ShouldCreateMockFromRealCtorWithParams()572 {573 // the following line should not throw any argument exception.574 var realItem = Mock.Create(() => new RealItem("hello", 10, 20),575 Behavior.CallOriginal);576 Assert.Equal("hello", realItem.Text);577 Assert.Equal(2, realItem.Args.Length);578 }579 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]580 public void ShouldAssertMixins()581 {582 var realItem = Mock.Create<RealItem>(x =>583 {584 x.Implements<IDisposable>();585 x.CallConstructor(() => new RealItem(0));586 });587 var iDispose = realItem as IDisposable;588 iDispose.Dispose();589 }590 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]591 public void ShouldAssertMixinsWithClosure()592 {593 int a = 5;594 var realItem = Mock.Create<RealItem>(x =>595 {596 x.Implements<IDisposable>();597 x.CallConstructor(() => new RealItem(a));598 });599 var iDispose = realItem as IDisposable;600 iDispose.Dispose();601 }602 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]603 public void ShouldImplementDependentInterfacesWhenTopIsSpecified()604 {605 var realItem = Mock.Create<RealItem>(x =>606 {607 x.Implements<IFooImplemted>();608 x.CallConstructor(() => new RealItem(0));609 });610 Assert.NotNull(realItem as IFoo);611 }612 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]613 public void ShouldCloneWhenItemImplementsICloneableAndOneOtherInterface()614 {615 var myMock = Mock.Create<IDisposable>(x => x.Implements<ICloneable>());616 var myMockAsClonable = myMock as ICloneable;617 bool isCloned = false;618 Mock.Arrange(() => myMockAsClonable.Clone()).DoInstead(() => isCloned = true);619 myMockAsClonable.Clone();620 Assert.True(isCloned);621 }622 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]623 public void ShouldCallOriginalMethodForCallsOriginal()624 {625 var foo = Mock.Create<FooBase>(Behavior.CallOriginal);626 //// should call the original.627 Assert.Throws<InvalidOperationException>(() => foo.ThrowException());628 }629 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]630 public void ShouldNotCallOriginalMethodIfThereisASetupForCallsOriginal()631 {632 var foo = Mock.Create<FooBase>(Behavior.CallOriginal);633 Guid expected = Guid.NewGuid();634 Mock.Arrange(() => foo.GetGuid()).Returns(expected);635 Assert.Equal(expected, foo.GetGuid());636 }637 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]638 public void ShouldCallOriginalIfThereIsNoSetupForSimilarTypeForCallsOiginal()639 {640 var foo = Mock.Create<FooBase>(Behavior.CallOriginal);641 Mock.Arrange(() => foo.Echo(1)).Returns(2);642 Assert.Equal(2, foo.Echo(1));643 Assert.Equal(2, foo.Echo(2));644 }645 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]646 public void ShouldBeAbleToIgnoreArgumentsIfSpecified()647 {648 var foo = Mock.Create<IFoo>();649 Mock.Arrange(() => foo.Echo(10, 9)).IgnoreArguments().Returns(11);650 Assert.Equal(11, foo.Echo(1, 1));651 }652 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]653 public void ShouldInterceptVirtualsFromBaseClass()654 {655 var foo = Mock.Create<FooChild>();656 Mock.Arrange(() => foo.ThrowException()).Throws<ArgumentException>();657 Assert.Throws<ArgumentException>(() => foo.ThrowException());658 }659 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]660 public void ShouldAssertSetupWithArgAnyMatcherForArray()661 {662 var foo = Mock.Create<IFoo>();663 Mock.Arrange(() => foo.Submit(Arg.IsAny<byte[]>())).MustBeCalled();664 foo.Submit(new byte[10]);665 Mock.Assert(foo);666 }667 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]668 public void ShouldAssertDictionaryArgumentForIsAny()669 {670 var param = Mock.Create<IParams>();671 Mock.Arrange(() =>672 param.ExecuteArrayWithString(Arg.AnyString, Arg.IsAny<Dictionary<string, object>>()))673 .MustBeCalled();674 param.ExecuteArrayWithString("xxx", new Dictionary<string, object>());675 Mock.Assert(param);676 }677 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]678 public void ShouldAssertSetupWithCallHavingParamsAndPassedWithMatcher()679 {680 var foo = Mock.Create<IFoo>();681 Mock.Arrange(() => foo.FindOne(Arg.IsAny<ICriteria>())).Returns(true);682 var criteria = Mock.Create<ICriteria>();683 Assert.True(foo.FindOne(criteria));684 }685 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]686 public void ShouldThrowNotImplementedExceptionForBaseInovocationOnAbstract()687 {688 var node = Mock.Create<ExpressionNode>(Behavior.CallOriginal);689 Assert.Throws<NotImplementedException>(() => { var expected = node.NodeType; });690 }691 [TestMethod, TestCategory("Lite"), TestCategory("Behavior"), TestCategory("CallOriginal")]692 public void CallOriginalClause_AbstractMethod_ThrowsNotImplemented()693 {694 var mock = Mock.Create<IFoo>();695 Mock.Arrange(() => mock.JustCall()).CallOriginal();696 Assert.Throws<NotImplementedException>(() => mock.JustCall());697 }698 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]699 public void ShouldSetupMockWithParamsWhenNoParamIsPassed()700 {701 var fooParam = Mock.Create<FooParam>();702 var expected = "hello";703 Mock.Arrange(() => fooParam.FormatWith(expected)).Returns(expected);704 Assert.Equal(expected, fooParam.FormatWith(expected));705 }706 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]707 public void ShouldBeAbleToPassSingleArgIsAnyForParamsTypeArgument()708 {709 var fooParam = Mock.Create<FooParam>();710 Mock.Arrange(() => fooParam.GetDevicesInLocations(0, false, Arg.IsAny<MesssageBox>())).Returns(10);711 int result = fooParam.GetDevicesInLocations(0, false, new MesssageBox());712 Assert.Equal(10, result);713 }714 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]715 public void ShouldBeAbleToPassMultipleArgIsAnyForParamsTypeArgument()716 {717 var fooParam = Mock.Create<FooParam>();718 Mock.Arrange(() => fooParam719 .GetDevicesInLocations(0, false, Arg.IsAny<MesssageBox>(), Arg.IsAny<MesssageBox>()))720 .Returns(10);721 var box = new MesssageBox();722 int result = fooParam.GetDevicesInLocations(0, false, box, box);723 Assert.Equal(10, result);724 }725 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]726 public void ShouldCreateMockFromInterfaceWithSimilarGenericOverloads()727 {728 var session = Mock.Create<ISession>();729 Assert.NotNull(session);730 }731 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]732 public void ShouldDisposeArrangementEffects()733 {734 var mock = Mock.Create<IBar>();735 using (Mock.Arrange(() => mock.Value).Returns(123))736 {737 Assert.Equal(123, mock.Value);738 }739 Assert.Equal(0, mock.Value);740 }741 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]742 public void ShouldDisposeArrangementExpectations()743 {744 var mock = Mock.Create<IBar>();745 using (Mock.Arrange(() => mock.Value).MustBeCalled())746 {747 Assert.Throws<AssertionException>(() => Mock.Assert(mock));748 }749 Mock.Assert(mock);750 }751 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]752 public void ShouldAssertExpectedWithDynamicQuery()753 {754 var bookRepo = Mock.Create<IBookRepository>();755 var expected = new Book();756 Mock.Arrange(() => bookRepo.GetWhere(book => book.Id > 1))757 .Returns(expected)758 .MustBeCalled();759 var actual = bookRepo.GetWhere(book => book.Id > 1);760 Assert.Equal(expected, actual);761 Mock.Assert(bookRepo);762 }763 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]764 public void ShouldAssertMockExpressionDeleteArgumentForCompoundQuery()765 {766 var bookRepo = Mock.Create<IBookRepository>();767 var expected = new Book();768 string expectedTitle = "Telerik";769 Mock.Arrange(() => bookRepo.GetWhere(book => book.Id > 1 && book.Title == expectedTitle))770 .Returns(expected)771 .MustBeCalled();772 var actual = bookRepo.GetWhere(book => book.Id > 1 && book.Title == expectedTitle);773 Assert.Equal(expected, actual);774 Mock.Assert(bookRepo);775 }776 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]777 public void ShouldAssertMockForDynamicQueryWhenComparedUsingAVariable()778 {779 var repository = Mock.Create<IBookRepository>();780 var expected = new Book { Title = "Adventures" };781 var service = new BookService(repository);782 Mock.Arrange(() => repository.GetWhere(book => book.Id == 1))783 .Returns(expected)784 .MustBeCalled();785 var actual = service.GetSingleBook(1);786 Assert.Equal(actual.Title, expected.Title);787 }788 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]789 public void ShouldAssertWithIntValueUsedForLongValuedArgument()790 {791 int number = 5;792 int expectedResult = 42;793 var myClass = Mock.Create<ClassWithLongMethod>();794 Mock.Arrange(() => myClass.AddOne(number)).Returns(expectedResult);795 // Act796 var result = myClass.AddOne(number);797 // Assert798 Assert.Equal(expectedResult, result);799 }800 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]801 public void ShouldAutoArrangePropertySetInConstructor()802 {803 var expected = "name";804 var item = Mock.Create<Item>(() => new Item(expected));805 Assert.Equal(expected, item.Name);806 }807 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]808 public void ShouldTakeOutValueFromDoInteadWhenDefinedWithCustomDelegate()809 {810 int outArg = 1;811 var mock = Mock.Create<DoInsteadWithCustomDelegate>();812 Mock.Arrange(() => mock.Do(0, ref outArg)).DoInstead(new RefAction<int, int>((int i, ref int arg2) => { arg2 = 2; }));813 mock.Do(0, ref outArg);814 Assert.Equal(2, outArg);815 }816 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]817 public void ShouldCheckMethodOverloadsWhenResolvingInterfaceInheritance()818 {819 var project = Mock.Create<IProject>();820 Assert.NotNull(project);821 }822 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]823 public void PropertySetShouldThrowExceptionWhenNameHasSet_Literal()824 {825 var b_object = Mock.Create<B>();826 Mock.ArrangeSet<B>(() => b_object.b_string_set_get = string.Empty).DoNothing().MustBeCalled();827 b_object.b_string_set_get = string.Empty;828 Mock.Assert(b_object);829 }830 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]831 public void ShouldNotAffectAssertionForInvalidAsserts()832 {833 var foo = Mock.Create<IFoo>();834 Guid goodGuid = Guid.NewGuid();835 Guid badGuid = Guid.NewGuid();836 Mock.Arrange(() => foo.CallMeOnce(true, goodGuid)).OccursOnce();837 foo.CallMeOnce(true, goodGuid);838 Mock.Assert(() => foo.CallMeOnce(true, badGuid), Occurs.Never());839 Mock.Assert(() => foo.CallMeOnce(true, Guid.Empty), Occurs.Never());840 Mock.Assert(() => foo.CallMeOnce(true, goodGuid), Occurs.Once());841 Mock.Assert(() => foo.CallMeOnce(false, badGuid), Args.Ignore(), Occurs.Once());842 Mock.Assert(() => foo.CallMeOnce(Arg.AnyBool, badGuid), Occurs.Never());843 Mock.Assert(() => foo.CallMeOnce(Arg.IsAny<bool>(), badGuid), Occurs.Never());844 }845 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]846 public void ShouldEqualityCheckForMockFromAnInterfaceThatHasEquals()847 {848 IRule mockRule1 = Mock.Create<IRule>();849 List<IRule> ruleList = new List<IRule>();850 Assert.False(ruleList.Contains(mockRule1));851 ruleList.Add(mockRule1);852 Assert.True(ruleList.Contains(mockRule1));853 }854 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]855 public void ShouldAssertMethodWithKeyValuePairTypeArgument()856 {857 var presenter = Mock.Create<InteractiveKioskPresenter>(Behavior.CallOriginal);858 var key = Mock.Create<IKioskPart>();859 var val = Mock.Create<IKioskWellInfo>();860 presenter.ShowControl(new KeyValuePair<IKioskPart, IKioskWellInfo>(key, val));861 }862 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]863 public void ShouldAssertMethodWithStructTypeArgument()864 {865 var presenter = Mock.Create<InteractiveKioskPresenter>(Behavior.CallOriginal);866 Size size = new Size();867 presenter.DrawRect(size);868 }869 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]870 public void ShouldParsePrimitiveParamsArrayCorrectly()871 {872 var foo = Mock.Create<IFoo>();873 Mock.Arrange(() => foo.SubmitWithParams(Arg.AnyInt)).MustBeCalled();874 foo.SubmitWithParams(10);875 Mock.Assert(foo);876 }877 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]878 public void ShouldAssertCorrectMethodWhenDifferentArgumentsPassedForParamSetup()879 {880 var foo = Mock.Create<IFoo>();881 Mock.Arrange(() => foo.SubmitWithParams(10)).OccursOnce();882 foo.SubmitWithParams(10);883 foo.SubmitWithParams(10, 11);884 Mock.Assert(foo);885 }886 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]887 public void ShouldAssertOccursForIndexedPropertyWithDifferentArguments()888 {889 var foo = Mock.Create<Foo>();890 string expected = "string";891 Mock.Arrange(() => foo.Baz["Test"]).Returns(expected);892 Mock.Arrange(() => foo.Baz["TestName"]).Returns(expected);893 Assert.Equal(expected, foo.Baz["Test"]);894 Assert.Equal(expected, foo.Baz["TestName"]);895 Mock.Assert(() => foo.Baz["Test"], Occurs.Once());896 Mock.Assert(() => foo.Baz["TestName"], Occurs.Once());897 }898 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]899 public void ShouldNotSkipBaseInterfaceWhenSomeMembersAreSame()900 {901 var loanString = Mock.Create<ILoanStringField>();902 Assert.NotNull(loanString);903 }904 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]905 public void ShouldAssertParamsArrayAsArrayBasedOnArgument()906 {907 string value1 = "Hello";908 string value2 = "World";909 var session = Mock.Create<IMockable>();910 Mock.Arrange(() => session.Get<string>(Arg.Matches<string[]>(v => v.Contains("Lol") &&911 v.Contains("cakes"))))912 .Returns(new[]913 {914 value1,915 value2,916 });917 var testValues = new[]{918 "Lol",919 "cakes"920 };921 var result = session.Get<string>(testValues);922 Assert.Equal(value1, result[0]);923 Assert.Equal(value2, result[1]);924 }925 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]926 public void ShouldNotInitRescursiveMockingWithProfilerForProperyThatReturnsMock()927 {928 WorkerHelper helper = new WorkerHelper();929 helper.Arrange();930 helper.Worker.Echo("hello");931 }932 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]933 public void ShouldAssertMockWithEnumArgumentWithUnderlyingTypeOtherThanInt()934 {935 var subdivisionTypeCode = SubdivisionTypeCode.City;936 var subdivisionTypeRepository = Mock.Create<ISubdivisionTypeRepository>();937 Mock.Arrange(() => subdivisionTypeRepository.Get(subdivisionTypeCode)).Returns((SubdivisionTypeCode subDivision) =>938 {939 return subDivision.ToString();940 });941 var result = subdivisionTypeRepository.Get(subdivisionTypeCode);942 Assert.Equal(result, subdivisionTypeCode.ToString());943 Mock.AssertAll(subdivisionTypeRepository);944 }945 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]946 public void ShouldAssertMockWithNullableValueTypeArg()947 {948 FooNullable foo = Mock.Create<FooNullable>();949 var now = DateTime.Now;950 Mock.Arrange(() => foo.ValideDate(now)).MustBeCalled();951 foo.ValideDate(now);952 Mock.Assert(foo);953 }954 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]955 public void ShouldAssertMockWithNullForNullableValueTypeArg()956 {957 FooNullable foo = Mock.Create<FooNullable>();958 Mock.Arrange(() => foo.ValideDate(null)).MustBeCalled();959 foo.ValideDate(null);960 Mock.Assert(foo);961 }962 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]963 public void ShouldAssertCallOriginalForAbstractClass()964 {965 Assert.NotNull(Mock.Create<TestTreeItem>(Behavior.CallOriginal));966 }967 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]968 public void ShouldCallBaseWhenCallOriginalSpecifiedForMock()969 {970 var item = Mock.Create<TestTreeItem>(Behavior.CallOriginal);971 var result = ((IComparable)item).CompareTo(10);972 Assert.Equal(1, result);973 }974 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]975 public void ShouldArrangeBothInterfaceMethodAndImplementation()976 {977 var mock = Mock.Create<FrameworkElement>() as ISupportInitialize;978 bool implCalled = false;979 Mock.Arrange(() => mock.Initialize()).DoInstead(() => implCalled = true).MustBeCalled();980 mock.Initialize();981 Assert.True(implCalled);982 Mock.Assert(() => mock.Initialize());983 }984 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]985 public void ShouldArrangeBothBaseAndOverriddenMethod()986 {987 var mock = Mock.Create<Control>() as FrameworkElement;988 bool implCalled = false;989 Mock.Arrange(() => mock.Initialize()).DoInstead(() => implCalled = true);990 mock.Initialize();991 Assert.True(implCalled);992 Mock.Assert(() => mock.Initialize());993 Mock.Assert(() => ((ISupportInitialize)mock).Initialize());994 }995 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]996 public void ShouldArrangeBaseMethodInManyImplementations()997 {998 var fe = Mock.Create<FrameworkElement>();999 var control = Mock.Create<Control>();1000 int calls = 0;1001 Mock.Arrange(() => (null as ISupportInitialize).Initialize()).DoInstead(() => calls++);1002 fe.Initialize();1003 Assert.Equal(1, calls);1004 control.Initialize();1005 Assert.Equal(2, calls);1006 }1007 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]1008 public void ShouldAssertMethodAtAllHierarchyLevels()1009 {1010 var control = Mock.Create<Control>();1011 control.Initialize();1012 Mock.Assert(() => control.Initialize(), Occurs.Once());1013 Mock.Assert(() => (control as FrameworkElement).Initialize(), Occurs.Once());1014 Mock.Assert(() => (control as ISupportInitialize).Initialize(), Occurs.Once());1015 }1016 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]1017 public void ShouldArrangeBaseMethodInManyImplementationsForProperty()1018 {1019 var fe = Mock.Create<FrameworkElement>();1020 var control = Mock.Create<Control>();1021 int calls = 0;1022 Mock.Arrange(() => (null as ISupportInitialize).Property).DoInstead(() => calls++);1023 var property = fe.Property;1024 Assert.Equal(1, calls);1025 property = control.Property;1026 Assert.Equal(2, calls);1027 }1028 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]1029 public void ShouldAssertMethodAtAllHierarchyLevelsForProperty()1030 {1031 var control = Mock.Create<Control>();1032 var property = control.Property;1033 Mock.Assert(() => control.Property, Occurs.Once());1034 Mock.Assert(() => (control as FrameworkElement).Property, Occurs.Once());1035 Mock.Assert(() => (control as ISupportInitialize).Property, Occurs.Once());1036 }1037 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]1038 public void ShouldArrangeInheritableMemberOfExplicitlySpecifiedType()1039 {1040 var ident = Mock.Create<IIdentifiable>();1041 Mock.Arrange<IIdentifiable, int>(new Func<int>(() => ident.Id)).Returns(15);1042 Assert.Equal(15, ident.Id);1043 }1044#if !SILVERLIGHT1045 [TestMethod, TestCategory("Elevated"), TestCategory("Lite"), TestCategory("Mock")]1046 public void ShouldNotCreateProxyIfNotNecessary()1047 {1048 var mock = Mock.Create<Poco>();1049 Mock.Arrange(() => mock.Data).Returns(10);1050 Assert.Equal(10, mock.Data);1051 if (Mock.IsProfilerEnabled)1052 Assert.Same(typeof(Poco), mock.GetType());1053 }1054#elif !LITE_EDITION1055 [TestMethod, TestCategory("Elevated"), TestCategory("Mock")]1056 public void ShouldNotCreateProxyIfNotNecessary()1057 {1058 var mock = Mock.Create<Poco>(Constructor.Mocked);1059 Mock.Arrange(() => mock.Data).Returns(10);1060 Assert.Equal(10, mock.Data);1061 Assert.Same(typeof(Poco), mock.GetType());1062 }1063#endif1064#if LITE_EDITION && !COREFX1065 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]1066 public void MockInternalMembersWithoutExplicitlyGivenVisibilitySentinel()1067 {1068 Assert.Throws<MockException>(() => Mock.Create<InvisibleInternal>());1069 }1070#endif1071 public class Poco // should be inheritable but shouldn't be abstract1072 {1073 public virtual int Data { get { return 0; } }1074 }1075 public interface IIdentifiable1076 {1077 int Id { get; }1078 }1079 public interface ISupportInitialize1080 {1081 void Initialize();1082 string Property { get; }1083 }1084 public abstract class FrameworkElement : ISupportInitialize1085 {1086 public abstract void Initialize();1087 public abstract string Property { get; set; }1088 }1089 public abstract class Control : FrameworkElement1090 {1091 public override void Initialize()1092 {1093 throw new NotImplementedException();1094 }1095 public override string Property1096 {1097 get1098 {1099 throw new NotImplementedException();1100 }1101 set1102 {1103 throw new NotImplementedException();1104 }1105 }1106 }1107 public abstract class TestTreeItem : IComparable1108 {1109 int IComparable.CompareTo(object obj)1110 {1111 return 1;1112 }1113 }1114 public class FooNullable1115 {1116 public virtual void ValideDate(DateTime? date)1117 {1118 }1119 }1120 public enum SubdivisionTypeCode : byte1121 {1122 None = 255,1123 State = 0,1124 County = 1,1125 City = 2,1126 }1127 public interface ISubdivisionTypeRepository1128 {1129 string Get(SubdivisionTypeCode subdivisionTypeCode);1130 }1131 public class WorkerHelper1132 {1133 public IWorker TheWorker { get; private set; }1134 public WorkerHelper()1135 {1136 this.TheWorker = Mock.Create<IWorker>(Behavior.Strict);1137 }1138 public IWorker Worker1139 {1140 get1141 {1142 return this.TheWorker;1143 }1144 }1145 public void Arrange()1146 {1147 Mock.Arrange(() => this.TheWorker.Echo(Arg.AnyString)).DoNothing();1148 }1149 }1150 public interface IWorker1151 {1152 void Echo(string value);1153 }1154 public interface IMockable1155 {1156 T[] Get<T>(params string[] values);1157 }1158 public interface ILoanStringField : ILoanField1159 {1160 string Value { get; set; }1161 }1162 public interface ILoanField1163 {1164 void ClearValue();1165 object Value { get; set; }1166 }1167 public interface IKioskPart1168 {1169 }1170 public interface IKioskWellInfo1171 {1172 }1173 public class InteractiveKioskPresenter1174 {1175 public virtual void ShowControl(KeyValuePair<IKioskPart, IKioskWellInfo> kPart)1176 {1177 }1178 public virtual void DrawRect(Size size)1179 {1180 }1181 }1182 public struct Size1183 {1184 }1185 public interface IRule1186 {1187 bool Equals(object obj);1188 }1189 public class B1190 {1191 public string b_string = null;1192 public virtual string b_string_set_get { get { return b_string; } set { b_string = value; } }1193 }1194 public interface IProject : IProjectItemContainer1195 {1196 IEnumerable<IProjectItem> Items { get; }1197 void AddChild();1198 }1199 public interface IProjectItem : IProjectItemContainer1200 {1201 }1202 public interface IProjectItemContainer : IDocumentItemContainer<IProjectItem>1203 {1204 bool CanAddChild { get; }1205 }1206 public interface IDocumentItemContainer : IDocumentItem1207 {1208 IEnumerable<IDocumentItem> Children { get; }1209 }1210 public interface IDocumentItemContainer<T> : IDocumentItemContainer1211 where T : IDocumentItem1212 {1213 IEnumerable<T> Children { get; }1214 void AddChild(T child);1215 void RemoveChild(T child);1216 }1217 public interface IDocumentItem1218 {1219 }1220 public delegate void RefAction<T1, T2>(T1 arg1, ref T2 arg2);1221 public class DoInsteadWithCustomDelegate1222 {1223 public virtual void Do(int k, ref int j)1224 {1225 }1226 }1227 public class ClassWithLongMethod1228 {1229 public virtual long AddOne(long number)1230 {1231 return number + 1;1232 }1233 }1234 public class BookService1235 {1236 private IBookRepository repository;1237 public BookService(IBookRepository repository)1238 {1239 this.repository = repository;1240 }1241 public Book GetSingleBook(int id)1242 {1243 return repository.GetWhere(book => book.Id == id);1244 }1245 }1246 public interface IBookRepository1247 {1248 Book GetWhere(Expression<Func<Book, bool>> expression);1249 }1250 public class Book1251 {1252 public int Id { get; private set; }1253 public string Title { get; set; }1254 }1255 #region Syntax Integrity1256 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]1257 public void ShouldBeAbleToInvokeMustBeCalledWithIgnoreArguments()1258 {1259 var foo = Mock.Create<Foo>();1260 Mock.Arrange(() => foo.Execute(0)).IgnoreArguments().MustBeCalled();1261 foo.Execute(10);1262 Mock.Assert(foo);1263 }1264 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]1265 public void ShouldBeAbleToUseMuseBeCalledAfterIgnoreFoFunc()1266 {1267 var foo = Mock.Create<Foo>();1268 Mock.Arrange(() => foo.Echo(0)).IgnoreArguments().MustBeCalled();1269 foo.Echo(10);1270 Mock.Assert(foo);1271 }1272 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]1273 public void ShouldBeAbleToDoDoNothingForNonVoidCalls()1274 {1275 var foo = Mock.Create<Foo>();1276 Mock.Arrange(() => foo.Echo(Arg.AnyInt)).DoNothing();1277 foo.Echo(10);1278 }1279 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]1280 public void ShouldBeAbleToSpecifyOccursAfterReturns()1281 {1282 var foo = Mock.Create<Foo>();1283 Mock.Arrange(() => foo.Echo(Arg.AnyInt))1284 .Returns(10)1285 .Occurs(1);1286 foo.Echo(10);1287 Mock.Assert(foo);1288 }1289 internal abstract class FooAbstract1290 {1291 protected internal abstract bool TryCreateToken(string literal);1292 }1293 internal abstract class FooAbstract2 : FooAbstract1294 {1295 }1296 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]1297 public void ShouldAsssertMockHavingInternalAbstractBaseMethod()1298 {1299 var foo = Mock.Create<FooAbstract2>();1300 foo.TryCreateToken(string.Empty);1301 }1302 #endregion1303 public interface ISession1304 {1305 ICriteria CreateCriteria<T>() where T : class;1306 ICriteria CreateCriteria(string entityName);1307 ICriteria CreateCriteria<T>(string alias) where T : class;1308 ICriteria CreateCriteria(System.Type persistentClass);1309 ICriteria CreateCriteria(string entityName, string alias);1310 ICriteria CreateCriteria(System.Type persistentClass, string alias);1311 }1312 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]1313 public void ShouldNotTryToWeaveMethodInSilverlightRuntime()1314 {1315 var foo = Mock.Create<FooSilver>();1316 Assert.NotNull(foo);1317 }1318 public interface ICloneable1319 {1320 object Clone();1321 }1322 public abstract class FooSilver1323 {1324 public void Do()1325 {1326 }1327 }1328#if LITE_EDITION1329 [TestMethod]1330 public void ShouldThrowMockExceptionWhenTryingToMockFinalMethod()1331 {1332 var mock = Mock.Create<Bar>();1333 Assert.Throws<MockException>(() => Mock.Arrange(() => mock.Submit()).DoNothing());1334 }1335 public class Bar1336 {1337 public void Submit()1338 {1339 }1340 }1341#endif1342 #region Test Insfrastructure1343 public class Foo1344 {1345 public virtual void Execute(int arg1)1346 {1347 }1348 public virtual int Echo(int arg1)1349 {1350 return arg1;1351 }1352 public virtual Baz Baz { get; set; }1353 }1354 public class Baz1355 {1356 public virtual string this[string key]1357 {1358 get1359 {1360 return null;1361 }1362 }1363 }1364 public class FooParam1365 {1366 public virtual int GetDevicesInLocations(int arg1, bool bExclude, params MesssageBox[] box)1367 {1368 return default(int);1369 }1370 public virtual string FormatWith(string format, params object[] args)1371 {1372 return string.Empty;1373 }1374 }1375 public class MesssageBox1376 {1377 }1378 public enum ExpressionNodeType1379 {1380 Constant,1381 Binary1382 }1383 public abstract class ExpressionNode1384 {1385 public abstract ExpressionNodeType NodeType { get; }1386 }1387 public class RealItem1388 {1389 public RealItem()1390 {1391 }1392 public RealItem(int num)1393 {1394 }1395 public RealItem(string text, params int[] args)1396 {1397 if (args.Length == 0 || string.IsNullOrEmpty(text))1398 {1399 throw new ArgumentException();1400 }1401 this.text = text;1402 this.args = args;1403 }1404 public string Text1405 {1406 get1407 {1408 return text;1409 }1410 }1411 public int[] Args1412 {1413 get1414 {1415 return args;1416 }1417 }1418 public string text;1419 private int[] args;1420 }1421 public class RealItem21422 {1423 public RealItem2(int num, string str)1424 {1425 }1426 }1427 public class Item1428 {1429 public virtual string Name { get; set; }1430 public Item(string name)1431 {1432 Name = name;1433 }1434 }1435 public class FooGeneric<T>1436 {1437 public virtual T Get<T1, T2>(T1 p1, T2 p2)1438 {1439 return default(T);1440 }1441 public virtual void Execute<T1>(T1 arg)1442 {1443 throw new Exception();1444 }1445 }1446 public class FooGeneric1447 {1448 public virtual TRet Get<T, TRet>(T arg1)1449 {1450 return default(TRet);1451 }1452 public virtual TRet Execute<T1, TRet>(out T1 arg1)1453 {1454 arg1 = default(T1);1455 object[] args = new object[1];1456 args[0] = arg1;1457 return default(TRet);1458 }1459 public virtual int Get<T1>()1460 {1461 throw new NotImplementedException();1462 }1463 }1464 public class FooWithInternalConstruct1465 {1466 internal FooWithInternalConstruct()1467 {1468 }1469 public virtual void Execute()1470 {1471 throw new ArgumentException();1472 }1473 }1474 public class Nested1475 {1476 public int expected;1477 public int expeted1;1478 }1479 class FooService : IFooService { }1480 interface IFooService { }1481 public interface ICriteria1482 {1483 }1484 public interface IFoo1485 {1486 string Execute(string arg);1487 void JustCall();1488 void Execute(Guid guid);1489 void Execute(bool flag, Guid guid);1490 void Execute(out int expected);1491 void Execute(out DateTime date);1492 IFoo GetFoo();1493 int Echo(int arg1);1494 int Echo(int arg1, int arg2);1495 int Echo(int arg1, int arg2, int arg3);1496 int Echo(int arg1, int arg2, int arg3, int arg4);1497 void Submit(int arg1);1498 void Submit(int arg1, int arg2);1499 void Submit(int arg1, int arg2, int arg3);1500 void Submit(int arg1, int arg2, int arg3, int arg4);1501 void Submit(byte[] arg);1502 void SubmitWithParams(params int[] args);1503 void CallMeOnce(bool flag, Guid guid);1504 bool FindOne(params ICriteria[] criteria);1505 }1506 public interface IBar1507 {1508 int Echo(int value);1509 int Value { get; set; }1510 }1511 public interface IFooImplemted : IFoo1512 {1513 }1514 public class CustomExepction : Exception1515 {1516 public CustomExepction(string message, bool throwed)1517 : base(message)1518 {1519 }1520 }1521 public class Log1522 {1523 public virtual void Info(string message)1524 {1525 throw new Exception(message);1526 }1527 }1528 public abstract class FooBase1529 {1530 public virtual string GetString(string inString)1531 {1532 return inString;1533 }1534 public virtual Guid GetGuid()1535 {1536 return default(Guid);1537 }1538 public virtual int Echo(int arg1)1539 {1540 return arg1;1541 }1542 public virtual void ThrowException()1543 {1544 throw new InvalidOperationException("This should throw expection.");1545 }1546 }1547 public class FooChild : FooBase1548 {1549 }1550 public class FooOverridesEquals1551 {1552 public FooOverridesEquals(string name)1553 {1554 this.name = name;1555 }1556 public override bool Equals(object obj)1557 {1558 return (obj is FooOverridesEquals) &&1559 ((FooOverridesEquals)obj).name == this.name;1560 }1561 public override int GetHashCode()1562 {1563 if (!string.IsNullOrEmpty(name))1564 {1565 return name.GetHashCode();1566 }1567 return base.GetHashCode();1568 }1569 private string name;1570 }1571 public interface IParams1572 {1573 string ExecuteByName(int index, params string[] args);1574 string ExecuteParams(params string[] args);1575 string ExecuteArray(string[] args);1576 string ExecuteArrayWithString(string arg1, Dictionary<string, object> dic);1577 }1578 public class ClassNonDefaultGuidConstructor1579 {1580 public ClassNonDefaultGuidConstructor(Guid guidValue)1581 {1582 this.guidValue = guidValue;1583 }1584 public Guid guidValue;1585 }1586 public class ClassWithNonDefaultConstructor1587 {1588 internal ClassWithNonDefaultConstructor()1589 {1590 }1591 public ClassWithNonDefaultConstructor(string strValue, int intValue)1592 {1593 this.strValue = strValue;1594 this.intValue = intValue;1595 }1596 public ClassWithNonDefaultConstructor(string strValue, int intValue, bool boolValue)1597 {1598 this.strValue = strValue;1599 this.intValue = intValue;1600 this.boolValue = boolValue;1601 }1602 public override string ToString()1603 {1604 return string.Format("{0}+{1}+{2}", strValue, intValue, boolValue);1605 }1606 private string strValue;1607 private int intValue;1608 private bool boolValue;1609 }1610 #endregion1611 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]1612 public void ShouldInterpretNullAsDefaultInitializedValueTypeInCtorCall()1613 {1614 var mock = Mock.Create<ValueTypeInCtor>(null, null);1615 Assert.Equal(0, mock.a);1616 }1617 public class ValueTypeInCtor1618 {1619 public readonly int a;1620 public ValueTypeInCtor(ValueTypeInCtor q, int a)1621 {1622 this.a = a;1623 }1624 }1625#if !__IOS__1626 [ComImport]1627#endif1628 [Guid("4256871F-E8D7-40C2-9E1E-61CFA78C3EC1")]1629 public interface IVersioned1630 {1631 [DispId(1)]1632 string Identity { [DispId(1)] get; [DispId(1)] set; }1633 }1634#if !__IOS__1635 [ComImport]1636#endif1637 [Guid("8DAF6396-300A-46E2-AA4C-CCB6103FB955")]1638 public interface IVersioned2 : IVersioned1639 {1640 [DispId(1)]1641 string Identity { [DispId(1)] get; [DispId(1)] set; }1642 }1643 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]1644 public void ShouldCoalesceDifferentMembersWithSameDispIdInVersionedInterfaces()1645 {1646 var mock = Mock.Create<IVersioned2>();1647 mock.Identity = "id";1648 var baseIdentity = ((IVersioned)mock).Identity;1649 Assert.Equal("id", baseIdentity);1650 Assert.Equal("id", mock.Identity);1651 }1652 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]1653 public void ShouldMockInternalAbstract()1654 {1655 var mock = Mock.Create<InternalAbstract>();1656 Assert.NotNull(mock);1657 }1658 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]1659 public void ShouldAcceptTypedEnumAsMethodArgument()1660 {1661 var mock = Mock.Create<IUnmanagedService>();1662 Mock.Arrange(() => mock.IsAllowed(ShortFlags.One)).Returns(true);1663 Assert.True(mock.IsAllowed(ShortFlags.One));1664 Assert.False(mock.IsAllowed(ShortFlags.None));1665 Assert.False(mock.IsAllowed(ShortFlags.Two));1666 }1667 public enum ShortFlags : short1668 {1669 None = 0, One = 1, Two = 1001670 }1671 public interface IUnmanagedService1672 {1673 bool IsAllowed(ShortFlags flags);1674 }1675#if !DOTNET35 && !SILVERLIGHT && !WINDOWS_PHONE1676 [TestMethod, TestCategory("Lite"), TestCategory("Regression")]1677 public void ShouldInterceptDynamicProxyMethodsFromMultipleThreads()1678 {1679 var generator = Mock.Create<IGuidGenerator>();1680 var lotsOfGuids = Enumerable.Range(0, 3000)1681 .AsParallel()1682 .Select(x => generator.Generate())1683 .ToArray();1684 // didn't throw1685 }1686 public interface IGuidGenerator1687 {1688 Guid Generate();1689 }1690#endif1691 public class ClassWithCtor1692 {1693 public ClassWithCtor(string s)1694 {1695 }1696 }1697 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]1698 public void ShouldThrowMeaningfulExceptionWhenConstructorArgumentsAreIncorrect()1699 {1700 var ex = Assert.Throws<Exception>(() => Mock.Create<ClassWithCtor>(5));1701 }1702 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]1703 public void ShouldArrangeMemberFromAdditionalInterfaceOnClassMock()1704 {1705 var mock = Mock.Create<Exception>(cfg => cfg.Implements<IIdentity>());1706 var identity = mock as IIdentity;1707 Mock.Arrange(() => identity.Name).Returns("mock");1708 Assert.Equal("mock", identity.Name);1709 }1710 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]1711 public void ShouldArrangeMemberFromAdditionalInterfaceOnInterfaceMock()1712 {1713 var mock = Mock.Create<IPrincipal>(cfg => cfg.Implements<IIdentity>());1714 var identity = mock as IIdentity;1715 Mock.Arrange(() => identity.Name).Returns("mock");1716 Assert.Equal("mock", identity.Name);1717 }1718#if !PORTABLE1719 [TestMethod, TestCategory("Lite"), TestCategory("Mock")]1720 public void ShouldMockTypesFromReflectionNamespace()1721 {1722 var reflectionTypes = new[]1723 {1724 typeof(MemberInfo),1725 typeof(MethodBase),1726 typeof(MethodInfo),1727 typeof(ConstructorInfo),1728 typeof(FieldInfo),1729 typeof(PropertyInfo),1730 typeof(EventInfo),1731 };1732 foreach (var type in reflectionTypes)1733 {1734 var mock = Mock.Create(type) as MemberInfo;...

Full Screen

Full Screen

MiscFixture.cs

Source:MiscFixture.cs Github

copy

Full Screen

...84 public void ShouldAssertArgumentPassedByExplictConversation()85 {86 const string s = "XYZ";87 var foo = Mock.Create<IFoo>();88 Mock.Arrange(() => foo.Get(SomeClass<string>.From(s))).Returns(10);89 Assert.Throws<AssertionException>(() => Mock.Assert(() => foo.Get(SomeClass<string>.From(s))));90 int ret = foo.Get(SomeClass<string>.From(s));91 Mock.Assert(() => foo.Get(SomeClass<string>.From(s)));92 Assert.Equal(10, ret);93 }94 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]95 public void ShouldCreateMockWithGenericConstraints()96 {97 var target = Mock.Create<ISomething<int>>();98 Assert.NotNull(target);99 }100 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]101 public void ShoudlAssertCallWithGenericConstraint()102 {103 var target = Mock.Create<ISomething<int>>();104 // the following line should not throw any exception.105 target.DoSomething<int>();106 }107 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]108 public void ShouldAssertInterfaceForGenericConstaint()109 {110 var target = Mock.Create<ISomething<IDummy>>();111 // the following line should not throw any exception.112 target.DoSomething<IDummy>();113 }114 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]115 public void ShouldAssertImplicitInterface()116 {117 var bar = Mock.Create<IBar>();118 var barSUT = new Bar(bar);119 barSUT.Do(new Foo());120 Mock.Assert(() => bar.Do(Arg.IsAny<Foo>()));121 }122 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]123 public void ShouldBeAddRemoveConcreteMockItemsFromCollection()124 {125 var foo = Mock.Create<Foo>();126 IList<Foo> list = new List<Foo>();127 list.Add(foo);128 if (list.Contains(foo))129 {130 list.Remove(foo);131 }132 Assert.True(list.Count == 0);133 }134 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]135 public void ShouldBeAbleToCallBaseForGenericMethod()136 {137 var facade = Mock.Create<TestFacade>();138 Mock.Arrange(() => facade.Done<ContentItem>()).CallOriginal();139 Assert.Throws<ArgumentException>(() => facade.Done<ContentItem>());140 }141 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]142 public void ShouldBeAbleToCallOrignalForOutArgMethod()143 {144 var foo = Mock.Create<FooOut>();145 int expected = 0;146 Mock.Arrange(() => foo.EchoOut(out expected)).CallOriginal();147 foo.EchoOut(out expected);148 Assert.Equal(10, expected);149 }150 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]151 public void ShouldAssertCallOrignalForMethodWithGenericParameter()152 {153 var foo = Mock.Create<FooGeneric>();154 Mock.Arrange(() => foo.Echo<int>(10)).CallOriginal();155 foo.Echo<int>(10);156 }157 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]158 public void ShouldPickCorrectGenericVarientInCaseOfCallOriginal()159 {160 var foo = Mock.Create<FooGeneric>();161 Mock.Arrange(() => foo.Echo<int, int>(10)).CallOriginal();162 Assert.Throws<ArgumentException>(() => foo.Echo<int, int>(10));163 }164 [TestMethod, TestCategory("Lite")]165 public void ShouldAssertInvocationFromInsideAMockedEvent()166 {167 var @interface = Mock.Create<IInterface>();168 Mock.Arrange(() => @interface.TheFunc()).Returns(true);169 var target = new EventContainer(@interface);170 Mock.Raise(() => @interface.TheEvent += null, EventArgs.Empty);171 Assert.True(target.Result);172 }173 [TestMethod, TestCategory("Lite")]174 public void ShouldAssertRaiseEventAfterAMethodCallFromDifferentMock()175 {176 var @interface = Mock.Create<IInterface>();177 var @extended = Mock.Create<IInterfaceExtended>();178 var target = new EventContainer(@interface);179 Mock.Arrange(() => @interface.TheFunc()).Returns(true);180 Mock.Raise(() => @interface.TheEvent += null, EventArgs.Empty);181 @extended.TheFunc();182 Mock.Raise(() => @interface.TheEvent += null, EventArgs.Empty);183 Assert.True(target.NumberOfTimesCalled == 2);184 }185 [TestMethod, TestCategory("Lite"),]186 public void ShouldBeToSubscribeEventForStrictMock()187 {188 new EventContainer(Mock.Create<IInterface>(Behavior.Strict));189 }190 [TestMethod, TestCategory("Lite")]191 public void ShouldNotThrowExceptionForDecimalTypeThatHasMultipleImplicitMethods()192 {193 var foo = Mock.Create<TestBase>();194 decimal value = 1;195 Mock.Arrange(() => foo.SetValue(value)).MustBeCalled();196 foo.SetValue(value);197 Mock.Assert(foo);198 }199 public abstract class TestBase200 {201 public virtual decimal Value { get; set; }202 public virtual void SetValue(decimal newValue)203 {204 Value = newValue;205 }206 }207 public class EventContainer208 {209 public bool Result = false;210 private IInterface @interface = null;211 public int NumberOfTimesCalled { get; set; }212 public EventContainer(IInterface i)213 {214 this.@interface = i;215 this.@interface.TheEvent += new EventHandler(i_TheEvent);216 }217 void i_TheEvent(object sender, EventArgs e)218 {219 this.Result = this.@interface.TheFunc();220 this.NumberOfTimesCalled++;221 }222 }223 public interface IInterface224 {225 event EventHandler TheEvent;226 bool TheFunc();227 }228 public interface IInterfaceExtended229 {230 bool TheFunc();231 }232 public class FooOut233 {234 public virtual void EchoOut(out int argOut)235 {236 argOut = 10;237 }238 }239 public class FooGeneric240 {241 public virtual void Echo<TKey>(TKey key)242 {243 }244 public virtual void Echo<TKey, TKey2>(TKey key)245 {246 throw new ArgumentException();247 }248 }249 public class ContentItem : IFacade<ContentItem>250 {251 }252 public interface IFacade<TParaentFacade> { }253 public class TestFacade254 {255 public virtual TParentFacade Done<TParentFacade>() where TParentFacade : class, IFacade<TParentFacade>256 {257 throw new ArgumentException("My custom error");258 }259 }260#if !COREFX261 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]262 public void ShouldNotImplementInternalVirtualMemberUsingProxyWhenNotVisible()263 {264 var context = Mock.Create<Telerik.JustMock.DemoLibSigned.DummyContext>();265 Assert.NotNull(context);266 }267 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]268 public void ShouldCreateMockForFrameWorkClassWithInternalCtor()269 {270 var downloadDateCompleted = Mock.Create<DownloadDataCompletedEventArgs>();271 Assert.NotNull(downloadDateCompleted != null);272 }273 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]274 public void ShouldAssertStreamMocking()275 {276#if NETCORE277 Telerik.JustMock.Setup.AllowedMockableTypes.Add<System.IO.Stream>();278#endif279 var stream = Mock.Create<Stream>();280 Mock.Arrange(() => stream.Seek(0, SeekOrigin.Begin)).Returns(0L);281 var position = stream.Seek(0, SeekOrigin.Begin);282 Assert.Equal(0, position);283 Mock.Arrange(() => stream.Flush()).MustBeCalled();284 Mock.Arrange(() => stream.SetLength(100)).MustBeCalled();285 Assert.Throws<AssertionException>(() => Mock.Assert(stream));286 stream.Flush();287 stream.SetLength(100);288 Mock.Assert(stream);289 }290#endif291 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]292 public void ShouldMockMultipleInterfaceOnASingleMock()293 {294 var foo = Mock.Create<IFooDispose>();295 var iDisposable = foo as IDisposable;296 bool called = false;297 Mock.Arrange(() => iDisposable.Dispose()).DoInstead(() => called = true);298 iDisposable.Dispose();299 Assert.True(called);300 }301 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]302 public void ShouldMockClassWithInterfaceConstraints()303 {304 var container = Mock.Create<FakeContainer<Product>>();305 Mock.Arrange(() => container.Do<Product>()).MustBeCalled();306 container.Do<Product>();307 }308 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]309 public void ShouldMockMethodCallWithObjectArgumentWithMatcher()310 {311 var container = Mock.Create<IContainer>();312 var called = false;313 Mock.Arrange(() => container.Resolve(Arg.IsAny<IDatabase>())).DoInstead(() => called = true);314 var database = Mock.Create<IDatabase>();315 container.Resolve(database);316 Assert.True(called);317 }318 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]319 public void ShouldBeAbleToAssertNestedSetupDirectly()320 {321 var outer = Mock.Create<FooOuter>();322 var inner = Mock.Create<FooInter>();323 Mock.Arrange(() => outer.GetInnerClass()).Returns(inner);324 Mock.Arrange(() => inner.Value).Returns(10).MustBeCalled();325 Assert.Throws<AssertionException>(() => Mock.Assert(() => outer.GetInnerClass().Value));326 }327 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]328 public void ShouldNotCreateNestedMockWhenReturningCallBackForGenericCall()329 {330 Product product1 = new Product();331 Product product2 = new Product();332 Queue<Product> products = new Queue<Product>();333 products.Enqueue(product1);334 products.Enqueue(product2);335 var context = Mock.Create<IDataContext>();336 Mock.Arrange(() => context.Get<Product>()).Returns(() => products.Dequeue());337 Assert.True(context.Get<Product>().Equals(product1));338 Assert.True(context.Get<Product>().Equals(product2));339 }340 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]341 public void ShouldReturnNullWhenSpecifiedByReturn()342 {343 var exmpleMock = Mock.Create<IExampleInterface>();344 Mock.Arrange(() => exmpleMock.GetMeAllFoos()).Returns((IList<IFoo>)null);345 Assert.Null(exmpleMock.GetMeAllFoos());346 }347#if !COREFX348 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]349 public void ShouldMockInternalMemberFromBaseClass()350 {351 var id = Guid.NewGuid();352 var manager = Mock.Create<IContentManager>();353 var facade = Mock.Create<BlogFacade>(Behavior.CallOriginal);354 Mock.Arrange(() => facade.ContentManager).Returns(manager);355 Mock.Arrange(() => manager.GetItem(Arg.IsAny<Type>(), Arg.AnyGuid))356 .Returns(new Product()).MustBeCalled();357 facade.LoadItem(id);358 Mock.Assert(facade.ContentManager);359 }360#endif361 [TestMethod, TestCategory("Lite")]362 public void ShouldAssertSetupWithObjectArrayAsParams()363 {364 var foo = Mock.Create<Foo<Product>>();365 const int expected = 1;366 Mock.Arrange(() => foo.GetByKey(expected)).Returns(() => null).MustBeCalled();367 foo.GetByKey(expected);368 Mock.Assert(foo);369 }370 [TestMethod, TestCategory("Lite")]371 public void ShouldNotInstantiatePropertyWhenSetExplicitly()372 {373 var foo = Mock.Create<NestedFoo>();374 var actual = new FooThatFails(string.Empty);375 Mock.Arrange(() => foo.FooThatFailsOnCtor).Returns(actual);376 Assert.Equal(foo.FooThatFailsOnCtor, actual);377 }378 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]379 public void ShouldBeAbleToCreateMockWithInternalCtor()380 {381 var expected = "hello";382 var foo = Mock.Create<FooInternal>(x =>383 {384 x.CallConstructor(() => new FooInternal("hello"));385 x.SetBehavior(Behavior.CallOriginal);386 });387 Assert.Equal(foo.Name, expected);388 }389 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]390 public void ShouldExecuteEqualsDuringAssertWithMockArgument()391 {392 var foo = Mock.Create<FooAbstract>();393 var fooWork = Mock.Create<FooWork>();394 fooWork.DoWork(foo);395 Mock.Assert(() => fooWork.DoWork(foo));396 }397 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]398 public void ShouldAssertMultipleOccurrencesSeparatelyForAssertAll()399 {400 IFileReader fileReader = Mock.Create<IFileReader>(Behavior.Strict);401 Mock.Arrange(() => fileReader.FileExists(@"C:\Foo\Categories.txt")).Returns(false).OccursOnce();402 Mock.Arrange(() => fileReader.ReadFile(@"C:\Foo\Categories.txt")).IgnoreArguments().OccursNever();403 fileReader.FileExists(@"C:\Foo\Categories.txt");404 Mock.Assert(fileReader);405 }406 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]407 public void ShouldAssertOccurenceWhenCombinedWithNoSetupCalls()408 {409 string userName = "Bob";410 string password = "Password";411 ILoginService service = Mock.Create<ILoginService>();412 Mock.Arrange(() => service.ValidateUser(userName, password)).Returns(5).OccursOnce();413 Mock.Arrange(() => service.ValidateUser("foo", "bar")).OccursNever();414 SecurityHandler handler = new SecurityHandler(service);415 bool loggedIn = handler.LoginUser(userName, password);416 Assert.True(loggedIn);417 Assert.Equal(handler.UserID, 5);418 Mock.Assert(service);419 }420 public class NestedFoo421 {422 public virtual FooThatFails FooThatFailsOnCtor { get; set; }423 }424 public class FooThatFails425 {426 public FooThatFails(string message)427 {428 }429 public FooThatFails()430 {431 throw new ArgumentException("Failed");432 }433 }434 public class SecurityHandler435 {436 private readonly ILoginService _service;437 public int UserID { get; internal set; }438 public SecurityHandler(ILoginService service)439 {440 _service = service;441 _service.DatabaseName = "NorthWind";442 }443 public bool LoginUser(string userName, string password)444 {445 UserID = _service.ValidateUser(userName, password);446 return (UserID != 0);447 }448 }449 public interface ILoginService450 {451 int ValidateUser(string userName, string password);452 string DatabaseName { get; set; }453 event EventHandler UserLoggedOnEvent;454 event EventHandler DatabaseChangedEvent;455 }456 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]457 public void ShouldAssertCallOriginalOnOverloadsViaProxy()458 {459 var dummyExpression = Mock.Create<DummyExpression>(Behavior.CallOriginal);460 dummyExpression.Evaluate(10);461 }462 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]463 public void ShouldAssertSetPropertyOccurenceForAnyValue()464 {465 var foo = Mock.Create<IFoo>();466 Mock.ArrangeSet<IFoo>(() => foo.EffectiveFrom = DateTime.Now).IgnoreArguments();467 foo.EffectiveFrom = DateTime.Now;468 Assert.Throws<AssertionException>(() => Mock.AssertSet(() => foo.EffectiveFrom = Arg.IsAny<DateTime>(), Occurs.Never()));469 }470 [TestMethod, TestCategory("Lite")]471 public void ShouldAssertWithByteArrayArguments()472 {473 ITestInterface ti = Mock.Create<ITestInterface>();474 byte[] newimagebytes = new byte[1] { 4 };475 ti.DoStuff(newimagebytes);476 Mock.Assert(() => ti.DoStuff(newimagebytes), Occurs.AtLeastOnce());477 }478 [TestMethod, TestCategory("Lite"), TestCategory("Misc")]479 public void UsingShouldNotInterfereWithPreOccurrence()480 {481 var fakereader = Mock.Create<IXmlReader>();482 Mock.Arrange(() => fakereader.EOF).Returns(true).OccursOnce();483 Mock.Arrange(() => fakereader.ReadOuterXml()).Returns("aaa").OccursNever();484 using (fakereader)485 {486 if (!fakereader.EOF)487 {488 string s = fakereader.ReadOuterXml();489 }490 }491 Mock.Assert(fakereader);492 }493 [TestMethod, TestCategory("Lite")]494 public void ShouldAssertNewGuIdArgumentForSpecificValue()495 {496 var localPersister = Mock.Create<IProcessDataPersister>();497 Mock.Arrange(() => localPersister.GetTaskWarnings(new Guid("{00000000-0000-0000-0001-000000000003}")))498 .Returns(new List<TaskWarning>() { new TaskWarning(new Guid("{00000000-0000-0000-0001-000000000003}")) { EscalationLevel = 0 } })499 .MustBeCalled();500 var list = localPersister.GetTaskWarnings(new Guid("{00000000-0000-0000-0001-000000000003}"));501 Assert.NotNull(list);502 Mock.Assert(localPersister);503 }504 [TestMethod, TestCategory("Lite"),]505 public void ShouldConfirmMockingClassWithMethodHidingItsVirtualBase()506 {507 var child = Mock.Create<ChildClass>();508 Assert.NotNull(child);509 }510 public class ChildClass : ParentClass, IElement511 {512 public new bool CanWriteProperty(string propertyName)513 {514 throw new NotImplementedException();515 }516 }517 public interface IElement518 {519 bool CanWriteProperty(string propertyName);520 }521 public class ParentClass522 {523 public virtual bool CanWriteProperty(string propertyName)524 {525 return false;526 }527 }528 public class TaskWarning529 {530 private Guid guid;531 public TaskWarning(Guid guid)532 {533 this.guid = guid;534 }535 public int EscalationLevel { get; set; }536 }537 public interface IProcessDataPersister538 {539 List<TaskWarning> GetTaskWarnings(Guid taskId);540 }541 public interface ITestInterface542 {543 void DoStuff(byte[] bytes);544 }545 public class Foo<TEntity>546 {547 public virtual TEntity GetByKey(params object[] keyValues)548 {549 return default(TEntity);550 }551 }552 public class ContentFacade<TItem>553 {554 public virtual IContentManager ContentManager { get; set; }555 internal virtual void LoadItem(Guid guid)556 {557 var product = this.ContentManager.GetItem(typeof(TItem), guid);558 if (product == null)559 {560 throw new ArgumentException("Invalid object");561 }562 }563 }564 public class BlogFacade : ContentFacade<Product>565 {566 }567 public interface IContentManager568 {569 object GetItem(Type itemType, Guid id);570 }571 public interface IXmlReader : IDisposable572 {573 bool EOF { get; }574 string ReadOuterXml();575 }576 public class DummyExpression577 {578 public virtual object Evaluate(int arg1, string myString)579 {580 return null;581 }582 public virtual object Evaluate(int arg1)583 {584 return null;585 }586 }587 public interface IFileReader588 {589 bool FileExists(string pathAndFile);590 IList<string> ReadFile(string pathAndFile);591 }592 public enum FooWorkType593 {594 Go = 0,595 Went596 }597 public class FooWork598 {599 public virtual void DoWork(FooAbstract foo)600 {601 }602 }603 public abstract class FooAbstract : IEquatable<FooAbstract>604 {605 public abstract FooWorkType Type { get; }606 public override int GetHashCode()607 {608 return base.GetHashCode();609 }610 public override bool Equals(object obj)611 {612 return this.Equals(obj as FooAbstract);613 }614 public bool Equals(FooAbstract other)615 {616 if (object.ReferenceEquals(this, other))617 {618 return true;619 }620 return this.Type == other.Type;621 }622 }623 public class FooInternal624 {625 internal FooInternal(string name)626 {627 this.name = name;628 }629 public string Name { get { return name; } }630 private string name;631 }632 public interface IExampleInterface633 {634 IList<IFoo> GetMeAllFoos();635 }636 public interface IDataContext637 {638 T Get<T>();639 }640 public class FooOuter641 {642 public virtual FooInter GetInnerClass()643 {644 return null;645 }646 }647 public class FooInter648 {649 public virtual int Value { get; set; }650 }651 public class Product : IContainer652 {653 #region IContainer Members654 public void Resolve(object obj)655 {656 throw new NotImplementedException();657 }658 #endregion659 }660 public interface IDatabase661 {662 }663 public interface IContainer664 {665 void Resolve(object obj);666 }667 public class FakeContainer<T> where T : class668 {669 public virtual void Do<TSub>() where TSub : IContainer670 {671 throw new NotImplementedException();672 }673 }674 public interface IFooDispose : IDisposable675 {676 void Do();677 }678 public class Foo : IFoo679 {680 #region IFoo Members681 public int Get(SomeClass<string> id)682 {683 throw new NotImplementedException();684 }685 public DateTime EffectiveFrom { get; set; }686 public long Id687 {688 get689 {690 throw new NotImplementedException();691 }692 set693 {694 throw new NotImplementedException();695 }696 }697 public void SetIt(long it)698 {699 throw new NotImplementedException();700 }701 #endregion702 }703 public interface IBar704 {705 void Do(IFoo foo);706 }707 public class Bar708 {709 public Bar(IBar bar)710 {711 this.bar = bar;712 }713 public void Do(IFoo foo)714 {715 bar.Do(foo);716 }717 private IBar bar;718 }719 public interface IDummy720 {721 // dummy interface.722 }723 public interface ISomething<T>724 {725 void DoSomething<U>() where U : T;726 }727 public struct SomeClass<T> // Struct just to avoid having to implement Equals/GetHashCode728 {729 public static implicit operator SomeClass<T>(T t)730 {731 return new SomeClass<T>();732 }733 public static SomeClass<T> From(T t)734 {735 return t;736 }737 }738 public interface IFoo739 {740 int Get(SomeClass<string> id);741 long Id { get; set; }742 DateTime EffectiveFrom { get; set; }743 void SetIt(long it);744 }745 public interface IFooPtr746 {747 IntPtr Get(string input);748 }749 public interface IMyClass750 {751 IEnumerable<string> GetValuesSince(DateTime since);752 }753 }754}...

Full Screen

Full Screen

From

Using AI Code Generation

copy

Full Screen

1var foo = Mock.Create<FooGeneric<int>>();2Mock.Arrange(() => foo.From(1)).Returns(2);3Assert.AreEqual(2, foo.From(1));4var foo = Mock.Create<FooGeneric<int>>();5Mock.Arrange(() => foo.From(1)).Returns(2);6Assert.AreEqual(2, foo.From(1));7var foo = Mock.Create<FooGeneric<int>>();8Mock.Arrange(() => foo.From(1)).Returns(2);9Assert.AreEqual(2, foo.From(1));10var foo = Mock.Create<FooGeneric<int>>();11Mock.Arrange(() => foo.From(1)).Returns(2);12Assert.AreEqual(2, foo.From(1));13var foo = Mock.Create<FooGeneric<int>>();14Mock.Arrange(() => foo.From(1)).Returns(2);15Assert.AreEqual(2, foo.From(1));16var foo = Mock.Create<FooGeneric<int>>();17Mock.Arrange(() => foo.From(1)).Returns(2);18Assert.AreEqual(2, foo.From(1));19var foo = Mock.Create<FooGeneric<int>>();20Mock.Arrange(() => foo.From(1)).Returns(2);21Assert.AreEqual(2, foo.From(1));22var foo = Mock.Create<FooGeneric<int>>();23Mock.Arrange(() => foo.From(1)).Returns(2);24Assert.AreEqual(2, foo.From(1));25var foo = Mock.Create<FooGeneric<int>>();26Mock.Arrange(() => foo.From(1)).Returns(2);

Full Screen

Full Screen

From

Using AI Code Generation

copy

Full Screen

1FooGeneric<int> foo = new FooGeneric<int>();2foo.From(1);3foo.From(2);4foo.From(3);5foo.From(4);6foo.From(5);7foo.From(6);8foo.From(7);9foo.From(8);10foo.From(9);11foo.From(10);12foo.From(11);13FooGeneric<string> fooString = new FooGeneric<string>();14fooString.From("1");15fooString.From("2");16fooString.From("3");17fooString.From("4");18fooString.From("5");19fooString.From("6");20fooString.From("7");21fooString.From("8");22fooString.From("9");23fooString.From("10");24fooString.From("11");25FooGeneric<BarGeneric> fooBar = new FooGeneric<BarGeneric>();26fooBar.From(new BarGeneric());27fooBar.From(new BarGeneric())

Full Screen

Full Screen

From

Using AI Code Generation

copy

Full Screen

1var mock = Mock.Create<FooGeneric>();2var mock2 = Mock.Create<FooGeneric>();3var mock3 = Mock.Create<FooGeneric>();4var mock4 = Mock.Create<FooGeneric>();5Mock.Arrange(() => FooGeneric.From(It.IsAny<int>())).Returns(mock3);6Mock.Arrange(() => FooGeneric.From(It.IsAny<int>(), It.IsAny<int>())).Returns(mock4);7Mock.Arrange(() => mock3.From(It.IsAny<int>())).Returns(mock);8Mock.Arrange(() => mock3.From(It.IsAny<int>(), It.IsAny<int>())).Returns(mock2);9var result = FooGeneric.From(1).From(2, 3);10Assert.AreEqual(mock2, result);11var mock = Mock.Create<FooGeneric>();12var mock2 = Mock.Create<FooGeneric>();13var mock3 = Mock.Create<FooGeneric>();14var mock4 = Mock.Create<FooGeneric>();15Mock.Arrange(() => FooGeneric.From(It.IsAny<int>())).Returns(mock3);16Mock.Arrange(() => FooGeneric.From(It.IsAny<int>(), It.IsAny<int>())).Returns(mock4);17Mock.Arrange(() => mock3.From(It.IsAny<int>())).Returns(mock);18Mock.Arrange(() => mock3.From(It.IsAny<int>(), It.IsAny<int>())).Returns(mock2);19var result = FooGeneric.From(1).From(2, 3);20Assert.AreEqual(mock2, result);21var mock = Mock.Create<FooGeneric>();22var mock2 = Mock.Create<FooGeneric>();23var mock3 = Mock.Create<FooGeneric>();24var mock4 = Mock.Create<FooGeneric>();25Mock.Arrange(() => FooGeneric.From(It.IsAny<int>())).Returns(mock3);26Mock.Arrange(() => FooGeneric.From(It.IsAny<int>(), It.IsAny<int>())).Returns(mock4);27Mock.Arrange(() => mock3.From(It.IsAny<int>())).Returns(mock);28Mock.Arrange(() => mock3.From(It.IsAny<int>(), It.IsAny<int>())).Returns(mock2);29var result = FooGeneric.From(1).From(2, 3);30Assert.AreEqual(mock2, result);

Full Screen

Full Screen

From

Using AI Code Generation

copy

Full Screen

1FooGeneric<int> foo = new FooGeneric<int>();2foo.From(1, 2, 3);3foo.From(1, 2, 3);4FooGeneric<string> foo = new FooGeneric<string>();5foo.From("a", "b", "c");6foo.From("a", "b", "c");7FooGeneric<DateTime> foo = new FooGeneric<DateTime>();8foo.From(new DateTime(2010, 01, 01), new DateTime(2010, 01, 02), new DateTime(2010, 01, 03));9foo.From(new DateTime(2010, 01, 01), new DateTime(2010, 01, 02), new DateTime(2010, 01, 03));10FooGeneric<int> foo = new FooGeneric<int>();11foo.From(1, 2, 3);12foo.From(1, 2, 3);13FooGeneric<string> foo = new FooGeneric<string>();14foo.From("a", "b", "c");15foo.From("a", "b", "c");16FooGeneric<DateTime> foo = new FooGeneric<DateTime>();17foo.From(new DateTime(2010, 01, 01), new DateTime(2010, 01, 02), new DateTime(2010, 01, 03));18foo.From(new DateTime(2010, 01, 01), new DateTime(2010, 01, 02), new DateTime(2010, 01, 03));19FooGeneric<int> foo = new FooGeneric<int>();20foo.From(1, 2, 3);21foo.From(1, 2, 3);22FooGeneric<string> foo = new FooGeneric<string>();23foo.From("a", "b", "c");24foo.From("a

Full Screen

Full Screen

From

Using AI Code Generation

copy

Full Screen

1var fooGeneric = Mock.Create<FooGeneric>();2Mock.Arrange(() => fooGeneric.From(Arg.AnyString)).Returns("From");3var fooGeneric = Mock.Create<FooGeneric>();4Mock.Arrange(() => fooGeneric.From(Arg.AnyString)).Returns("From");5var foo = Mock.Create<Foo>();6Mock.Arrange(() => foo.GetFoo()).Returns("Foo").InSequence();7Mock.Arrange(() => foo.GetFoo()).Returns("Bar").InSequence();8var foo = Mock.Create<Foo>();9Mock.Arrange(() => foo.GetFoo()).Returns("Foo").InSequence();10Mock.Arrange(() => foo.GetFoo()).Returns("Bar").InSequence();11var foo = Mock.Create<Foo>();12Mock.Arrange(() => foo.GetFoo()).Returns("Foo").InSequence();13Mock.Arrange(() => foo.GetFoo()).Returns("Bar").InSequence();

Full Screen

Full Screen

From

Using AI Code Generation

copy

Full Screen

1using Telerik.JustMock.Tests;2{3 public void Bar()4 {5 var mock = Mock.Create<FooGeneric>();6 Mock.Arrange(() => mock.From(1)).Returns(1);7 }8}9using Telerik.JustMock.Tests;10{11 public void Bar()12 {13 var mock = Mock.Create<FooGeneric>();14 Mock.Arrange(() => mock.From(1)).Returns(1);15 }16}

Full Screen

Full Screen

From

Using AI Code Generation

copy

Full Screen

1using Telerik.JustMock.Tests;2{3 public static void Main()4 {5 var mock = Mock.Create<FooGeneric<int>>();6 var val = mock.From(5);7 }8}9{10 {11 public T From(T value)12 {13 return default(T);14 }15 }16}

Full Screen

Full Screen

From

Using AI Code Generation

copy

Full Screen

1var from = new FooGeneric<int>();2var result = from.From(new FooGeneric<int>());3var from = new FooGeneric<int>();4var result = from.From(new FooGeneric<int>());5var from = new FooGeneric<int>();6var result = from.From(new FooGeneric<int>());7var from = new FooGeneric<int>();8var result = from.From(new FooGeneric<int>());9var from = new FooGeneric<int>();10var result = from.From(new FooGeneric<int>());11var from = new FooGeneric<int>();12var result = from.From(new FooGeneric<int>());13var from = new FooGeneric<int>();14var result = from.From(new FooGeneric<int>());15var from = new FooGeneric<int>();16var result = from.From(new FooGeneric<int>());

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run JustMockLite automation tests on LambdaTest cloud grid

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

Most used method in FooGeneric

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful