This commit is contained in:
Stefan Dragnev 2013-12-23 10:02:11 +02:00
Коммит e3e9c76d4e
707 изменённых файлов: 98712 добавлений и 0 удалений

63
.gitattributes поставляемый Normal file
Просмотреть файл

@ -0,0 +1,63 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain

149
.gitignore поставляемый Normal file
Просмотреть файл

@ -0,0 +1,149 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.sln.docstates
# Build results
[Dd]ebug/
[Rr]elease/
[Dd]ebugFree/
[Rr]eleaseFree/
x64/
[Bb]in/
[Oo]bj/
*.jmconfig
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
*_i.c
*_p.c
*.ilk
*.meta
*.obj
*.pch
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.log
*.scc
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
*.cachefile
# Visual Studio profiler
*.psess
*.vsp
*.vspx
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
*.ncrunch*
.*crunch*.local.xml
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.Publish.xml
*.pubxml
# NuGet Packages Directory
## TODO: If you have NuGet Package Restore enabled, uncomment the next line
#packages/
# Windows Azure Build Output
csx
*.build.csdef
# Windows Store app package directory
AppPackages/
# Others
*.Cache
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.[Pp]ublish.xml
*.pfx
*.publishsettings
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file to a newer
# Visual Studio version. Backup files are not needed, because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
App_Data/*.mdf
App_Data/*.ldf
# =========================
# Windows detritus
# =========================
# Windows image file caches
Thumbs.db
ehthumbs.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Mac crap
.DS_Store

31
CommonAssemblyInfo.cs Normal file
Просмотреть файл

@ -0,0 +1,31 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System.Reflection;
#if LITE_EDITION
[assembly: AssemblyProduct("Telerik JustMock")]
#else
[assembly: AssemblyProduct("Telerik JustMock Commercial")]
#endif
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCompany("Telerik AD")]
[assembly: AssemblyCopyright("Copyright © 2010-2013 Telerik AD")]
[assembly: AssemblyVersion("2013.3.1021")]
[assembly: AssemblyFileVersion("2013.3.1021")]

Просмотреть файл

@ -0,0 +1,98 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
namespace JustMock.NonElevatedExamples.AdvancedUsage.ConcreteMocking
{
/// <summary>
/// Concrete mocking is one of the advanced features supported in Telerik JustMock. Up to this point we have been talking
/// mostly about mocking interfaces. This feature allows you to mock the creation of an object. To some extent this is available
/// in the free edition and there are more things you can do in the commercial edition of the product.
/// See http://www.telerik.com/help/justmock/advanced-usage-concrete-mocking.html for full documentation of the feature.
/// </summary>
[TestClass]
public class ConcreteMocking_Tests
{
[TestMethod]
[ExpectedException(typeof(NotImplementedException))]
public void ShouldCallOriginalForVirtualMemberWithMockedConstructor()
{
// ARRANGE
// Creating a mocked instance of the "FooVirtual" class.
// Telerik JustMock also gives you the ability to explicitly specify whether a constructor should be mocked or not.
// By default the constructor is not mocked.
var foo = Mock.Create<FooVirtual>(Constructor.Mocked);
// Arranging: When foo.GetList() is called, it should call the original method implementation.
Mock.Arrange(() => foo.GetList()).CallOriginal();
// ACT
foo.GetList();
}
[TestMethod]
public void VoidMethod_OnExcute_ShouldCallGetList()
{
// ARRANGE
// Creating a mocked instance of the "FooVirtual" class.
// Telerik JustMock also gives you the ability to explicitly specify whether a constructor should be mocked or not.
// By default the constructor is not mocked.
var foo = Mock.Create<FooVirtual>(Constructor.Mocked);
// Arranging: When foo.VoidMethod() is called, it should call foo.GetList() instead.
Mock.Arrange(() => foo.VoidMethod()).DoInstead(() => foo.GetList());
// Arranging: That foo.GetList() must be called during the test method and it should do nothing.
Mock.Arrange(() => foo.GetList()).DoNothing().MustBeCalled();
// ACT
foo.VoidMethod();
// ASSERT
Mock.Assert(foo);
}
}
#region SUT
public class FooVirtual
{
public FooVirtual()
{
throw new NotImplementedException("Constructor");
}
public virtual string Name
{
get;
set;
}
public virtual void VoidMethod()
{
throw new NotImplementedException();
}
public virtual IList<int> GetList()
{
throw new NotImplementedException();
}
}
#endregion
}

Просмотреть файл

@ -0,0 +1,139 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
namespace JustMock.NonElevatedExamples.AdvancedUsage.MockingDelegates
{
/// <summary>
/// With Telerik JustMock you can mock delegates and additionally apply all mock capabilities on them. For example, you can
/// assert against their invocation, arrange certain expectations and then pass them in the system under test.
/// See http://www.telerik.com/help/justmock/advanced-usage-mocking-delegates.html for full documentation of the feature.
/// </summary>
[TestClass]
public class MockingDelegates_Tests
{
[TestMethod]
public void ShouldArrangeReturnExpectation()
{
// ARRANGE
// Creating a mock instance of the Func<int, int> delegate.
var delegateMock = Mock.Create<Func<int, int>>();
// Arranging: When the mock is called with 10 as an integer argument, it should return 20.
Mock.Arrange(() => delegateMock(10)).Returns(20);
// ACT
var mySUT = new Foo();
// Assigning the mock to the dependent property.
mySUT.FuncDelegate = delegateMock;
var actual = mySUT.GetInteger(10);
// ASSERT
Assert.AreEqual(20, actual);
}
[TestMethod]
public void ShouldArrangeOccurrenceExpectation()
{
// ARRANGE
// Creating a mock instance of the Func<int, int> delegate.
var delegateMock = Mock.Create<Func<int, int>>();
// Arranging: That the mock should be called with any integer values during the test execution.
Mock.Arrange(() => delegateMock(Arg.AnyInt)).MustBeCalled();
// ACT
var mySUT = new Foo();
mySUT.FuncDelegate = delegateMock;
// Assigning the mock to the dependent property.
var actual = mySUT.GetInteger(123);
// ASSERT - asserting the mock.
Mock.Assert(delegateMock);
}
[TestMethod]
public void ShouldPassPrearrangedDelegateMockAsArgument()
{
// ARRANGE
// Creating a mock instance of the Func<string> delegate.
var delegateMock = Mock.Create<Func<string>>();
// Arranging: When the mock is called, it should return "Success".
Mock.Arrange(() => delegateMock()).Returns("Success");
// ACT
var testInstance = new DataRepository();
// Passing the mock into our system under test.
var actual = testInstance.GetCurrentUserId(delegateMock);
// ASSERT
Assert.AreEqual("Success", actual);
}
[TestMethod]
public void ShouldPassDelegateMockAsArgumentAndAssertItsOccurrence()
{
bool isCalled = false;
// ARRANGE
// Creating a mock instance of the Action<int> delegate.
var delegateMock = Mock.Create<Action<int>>();
// Arranging: When the mock is called with any integer value as an argument, it should assign true to isCalled instead.
Mock.Arrange(() => delegateMock(Arg.AnyInt)).DoInstead(() => isCalled = true);
// ACT
var testInstance = new DataRepository();
// Passing the mock into our system under test.
testInstance.ApproveCredentials(delegateMock);
// ASSERT
Assert.IsTrue(isCalled);
}
}
#region SUT
public class DataRepository
{
public string GetCurrentUserId(Func<string> callback)
{
return callback();
}
public void ApproveCredentials(Action<int> callback)
{
// Some logic here...
callback(1);
}
}
public class Foo
{
public Func<int, int> FuncDelegate { get; set; }
public int GetInteger(int toThisInt)
{
return FuncDelegate(toThisInt);
}
}
#endregion
}

Просмотреть файл

@ -0,0 +1,87 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
namespace JustMock.NonElevatedExamples.AdvancedUsage.PrivateAccessorNamespace
{
/// <summary>
/// The Telerik JustMock PrivateAccessor allows you to call non-public members of the tested code right in your unit tests.
/// See http://www.telerik.com/help/justmock/advanced-usage-private-accessor.html for full documentation of the feature.
/// </summary>
[TestClass]
public class PrivateAccessor_Tests
{
[TestMethod]
public void PrivateAccessor_ShouldCallPrivateMethod()
{
// ACT
// Wrapping the instance holding the private method.
var inst = new PrivateAccessor(new ClassWithNonPublicMembers());
// Calling the non-public method by giving its exact name.
var actual = inst.CallMethod("MePrivate");
// ASSERT
Assert.AreEqual(1000, actual);
}
[TestMethod]
public void PrivateAccessor_ShouldCallPrivateStaticMethod()
{
// ACT
// Wrapping the instance holding the private method by type.
var inst = PrivateAccessor.ForType(typeof(ClassWithNonPublicMembers));
// Calling the non-public static method by giving its exact name.
var actual = inst.CallMethod("MeStaticPrivate");
// ASSERT
Assert.AreEqual(2000, actual);
}
[TestMethod]
public void PrivateAccessor_ShouldGetSetProperty()
{
// ACT
// Wrapping the instance holding the private property.
var inst = new PrivateAccessor(new ClassWithNonPublicMembers());
// Setting the value of the private property.
inst.SetProperty("Prop", 555);
// ASSERT - Asserting with getting the value of the private property.
Assert.AreEqual(555, inst.GetProperty("Prop"));
}
}
#region SUT
public class ClassWithNonPublicMembers
{
private int Prop { get; set; }
private int MePrivate()
{
return 1000;
}
private static int MeStaticPrivate()
{
return 2000;
}
}
#endregion
}

Просмотреть файл

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
</configuration>

Просмотреть файл

@ -0,0 +1,332 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
namespace JustMock.NonElevatedExamples.BasicUsage.AssertingOccurrence
{
/// <summary>
/// See http://www.telerik.com/help/justmock/basic-usage-asserting-occurrence.html for full documentation of the feature.
/// Occurrence is used in conjunction with Mock.Assert and Mock.AssertSet to determine how many times a call has occurred.
/// There are 6 types of occurrence that we can use:
/// Occurs.Never() - Specifies that a particular call is never made on a mock.
/// Occurs.Once() - Specifies that a call has occurred only once on a mock.
/// Occurs.AtLeastOnce() - Specifies that a call has occurred at least once on a mock.
/// Occurs.AtLeast(numberOfTimes) - Specifies the number of times at least a call should occur on a mock.
/// Occurs.AtMost(numberOfTimes) - Specifies the number of times at most a call should occur on a mock.
/// Occurs.Exactly(numberOfTimes) - Specifies exactly the number of times a call should occur on a mock.
/// Furthermore, you can set occurrence directly in the arrangement of a method.
/// You can use one of 5 different constructs of Occur:
/// Occurs(numberOfTimes) - Specifies exactly the number of times a call should occur on a mock.
/// OccursOnce() - Specifies that a call should occur only once on a mock.
/// OccursNever() - Specifies that a particular call should never be made on a mock.
/// OccursAtLeast(numberOfTimes) - Specifies that a call should occur at least once on a mock.
/// OccursAtMost(numberOfTimes) - Specifies the number of times at most a call should occur on a mock.
/// </summary>
[TestClass]
public class AssertingOccurrence_Tests
{
[TestMethod]
public void ShouldOccursNever()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// ASSERT - Asserting that foo.Submit() has never occurred during the test method.
Mock.Assert(() => foo.Submit(), Occurs.Never());
}
[TestMethod]
public void ShouldOccursOnce()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// ACT
foo.Submit();
// ASSERT - Asserting that foo.Submit() occurs exactly once during the test method.
Mock.Assert(() => foo.Submit(), Occurs.Once());
}
[TestMethod]
public void ShouldOccursAtLeastOnce()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// ACT
foo.Submit();
// ASSERT - Asserting that foo.Submit() occurs at least once (could be more than once) during the test method.
Mock.Assert(() => foo.Submit(), Occurs.AtLeastOnce());
// ACT - Calling foo.Submit() more times.
foo.Submit();
foo.Submit();
// ASSERT - This should pass again.
Mock.Assert(() => foo.Submit(), Occurs.AtLeastOnce());
}
[TestMethod]
public void ShouldOccursAtLeastCertainNumberOfTimes()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// ACT
foo.Submit();
foo.Submit();
foo.Submit();
// ASSERT - Asserting that foo.Submit() occurs at least three times during the test method.
Mock.Assert(() => foo.Submit(), Occurs.AtLeast(3));
// ACT - Calling foo.Submit() more times.
foo.Submit();
// ASSERT - This should pass again.
Mock.Assert(() => foo.Submit(), Occurs.AtLeast(3));
}
[TestMethod]
[ExpectedException(typeof(AssertFailedException))]
public void ShouldOccursCertainNumberOfTimesAtMost()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// ACT
foo.Submit();
foo.Submit();
// ASSERT - Asserting that foo.Submit() occurs maximum twice during the test method.
Mock.Assert(() => foo.Submit(), Occurs.AtMost(2));
// ACT - Calling foo.Submit() once again - 3 times in total.
foo.Submit();
// Assert - This throws an exception.
Mock.Assert(() => foo.Submit(), Occurs.AtMost(2));
}
[TestMethod]
[ExpectedException(typeof(AssertFailedException))]
public void ShouldOccursExactly()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// ACT
foo.Submit();
foo.Submit();
foo.Submit();
// ASSERT - Asserting that foo.Submit() occurs exactly 3 times during the test method.
Mock.Assert(() => foo.Submit(), Occurs.Exactly(3));
// ACT - Calling foo.Submit once again - 4 times in total.
foo.Submit();
// Assert - This fails because foo.Submit was called more times than specified.
Mock.Assert(() => foo.Submit(), Occurs.Exactly(3));
}
[TestMethod]
[ExpectedException(typeof(AssertFailedException))]
public void ShouldFailOnAssertAllWhenExpectionIsNotMet()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: That foo.Submit() should occur exactly twice during the test method.
Mock.Arrange(() => foo.Submit()).Occurs(2);
// ACT - No actions.
// ASSERT - This will throw an exception as the expectations are not met.
Mock.Assert(foo);
}
[TestMethod]
public void ShouldArrangeOccursOnce()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: That foo.Submit() should occur exactly once during the test method.
Mock.Arrange(() => foo.Submit()).OccursOnce();
// ACT
foo.Submit();
// ASSERT
Mock.Assert(foo);
}
[TestMethod]
public void ShouldArrangeOccursNever()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: That foo.Submit() should never occur during the test method.
Mock.Arrange(() => foo.Submit()).OccursNever();
// ACT - No actions.
// ASSERT
Mock.Assert(foo);
}
[TestMethod]
public void ShouldArrangeOccursAtLeast()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: That foo.Submit() should occur at least twice during the test method.
Mock.Arrange(() => foo.Submit()).OccursAtLeast(2);
// ACT - Calling foo.Submit() 3 times.
foo.Submit();
foo.Submit();
foo.Submit();
// ASSERT - This passes as foo.Submit() is called at least twice.
Mock.Assert(foo);
}
[TestMethod]
[ExpectedException(typeof(AssertFailedException))]
public void ShouldFailWhenInvokedMoreThanRequried()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: That foo.Submit() should occur maximum twice during the test method.
Mock.Arrange(() => foo.Submit()).OccursAtMost(2);
// ACT
foo.Submit();
foo.Submit();
foo.Submit(); // This throws an exception because foo.Submit is being called more times than specified.
}
[TestMethod]
public void ShouldBeAbleToAssertOccursUsingMatcherForSimilarCallAtOneShot()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: Different expectations depending on the argument of foo.Echo().
Mock.Arrange(() => foo.Echo(1)).Returns((int arg) => arg);
Mock.Arrange(() => foo.Echo(2)).Returns((int arg) => arg);
Mock.Arrange(() => foo.Echo(3)).Returns((int arg) => arg);
// ACT
foo.Echo(1);
foo.Echo(2);
foo.Echo(3);
// ASSERT - This will pass as foo.Echo() has been called exactly 3 times no matter the argument.
Mock.Assert(() => foo.Echo(Arg.AnyInt), Occurs.Exactly(3));
}
[TestMethod]
public void ShouldVerifyCallsOrder()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: That foo.Submit() should be called before foo.Echo().
Mock.Arrange(() => foo.Submit()).InOrder();
Mock.Arrange(() => foo.Echo(Arg.AnyInt)).InOrder();
// ACT
foo.Submit();
foo.Echo(5);
// ASSERT
Mock.Assert(foo);
}
[TestMethod]
public void ShouldAssertInOrderForDifferentInstancesInTestMethodScope()
{
string userName = "Bob";
string password = "Password";
int userID = 5;
var cart = new List<string> { "Foo", "Bar" };
// ARRANGE
// Creating mocked instances of the "IUserValidationService" and "IShoppingCartService" interfaces.
var userServiceMock = Mock.Create<IUserValidationService>();
var shoppingCartServiceMock = Mock.Create<IShoppingCartService>();
// Arranging: When userServiceMock.ValidateUser(userName, password) is called it should return userID.
// Also this method should occur exactly once in a given order during the test execution.
Mock.Arrange(() => userServiceMock.ValidateUser(userName, password)).Returns(userID).InOrder().OccursOnce();
// Arranging: When shoppingCartServiceMock.LoadCart(userID) is called it should return cart.
// Also this method should occur exactly once in a given order during the test execution.
Mock.Arrange(() => shoppingCartServiceMock.LoadCart(userID)).Returns(cart).InOrder().OccursOnce();
// ACT
userServiceMock.ValidateUser(userName, password);
shoppingCartServiceMock.LoadCart(userID);
// ASSERT - Asserting occurrence and calls order.
Mock.Assert(userServiceMock);
Mock.Assert(shoppingCartServiceMock);
}
}
#region SUT
public interface IFoo
{
void Submit();
int Echo(int intArg);
}
public interface IUserValidationService
{
int ValidateUser(string userName, string password);
}
public interface IShoppingCartService
{
IList<string> LoadCart(int userID);
}
#endregion
}

Просмотреть файл

@ -0,0 +1,117 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
using Telerik.JustMock.Container;
namespace JustMock.NonElevatedExamples.BasicUsage.Automocking
{
/// <summary>
/// Automocking allows the developer to create an instance of a class (the system under test) without having
/// to explicitly create each individual dependency as a unique mock. The mocked dependencies are still available
/// to the developer if methods or properties need to be arranged as part of the test.
/// See http://www.telerik.com/help/justmock/basic-usage-automocking.html for full documentation of the feature.
/// </summary>
[TestClass]
public class Automocking_Tests
{
[TestMethod]
public void ShouldMockDependenciesWithContainer()
{
// ARRANGE
// Creating a MockingContainer of ClassUnderTest.
// To instantiate the system uder test (the container) you should use the Instance property
// For example: container.Instance.
var container = new MockingContainer<ClassUnderTest>();
string expectedString = "Test";
// Arranging: When the GetString() method from the ISecondDependecy interface
// is called from the container, it should return expectedString.
container.Arrange<ISecondDependency>(
secondDep => secondDep.GetString()).Returns(expectedString);
// ACT - Calling SringMethod() from the mocked instance of ClassUnderTest
var actualString = container.Instance.StringMethod();
// ASSERT
Assert.AreEqual(expectedString, actualString);
}
[TestMethod]
public void ShouldAssertAllContainerArrangments()
{
// ARRANGE
// Creating a MockingContainer of ClassUnderTest.
// To instantiate the system uder test (the container) you should use the Instance property
// For example: container.Instance.
var container = new MockingContainer<ClassUnderTest>();
// Arranging: That the GetString() method from the ISecondDependecy interface
// must be called from the container instance durring the test method.
container.Arrange<ISecondDependency>(
secondDep => secondDep.GetString()).MustBeCalled();
// ACT - Calling SringMethod() from the mocked instance of ClassUnderTest
var actualString = container.Instance.StringMethod();
// ASSERT - Asserting all expectations for the container.
container.AssertAll();
}
}
#region SUT
public class ClassUnderTest
{
private IFirstDependency firstDep;
private ISecondDependency secondDep;
public ClassUnderTest(IFirstDependency first, ISecondDependency second)
{
this.firstDep = first;
this.secondDep = second;
}
public IList<object> CollectionMethod()
{
var firstCollection = firstDep.GetList();
return firstCollection;
}
public string StringMethod()
{
var secondString = secondDep.GetString();
return secondString;
}
}
public interface IFirstDependency
{
IList<object> GetList();
}
public interface ISecondDependency
{
string GetString();
}
#endregion
}

Просмотреть файл

@ -0,0 +1,87 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
namespace JustMock.NonElevatedExamples.BasicUsage.CreateMocksByExample
{
/// <summary>
/// The built-in feature for creating mocks by example saves time when it comes to tiresome set up of arrangements.
/// This functionality allows you to create mocks of a certain class (the system under test)
/// and in the same time to arrange their behavior.
/// For simple tests with few arrangements, this provides only marginal benefit.
/// The real benefit comes with complex tests with multiple arrangements
/// See http://www.telerik.com/help/justmock/basic-usage-create-mocks-by-example.html for full documentation of the feature.
/// </summary>
[TestClass]
public class CreateMocksByExample_Tests
{
[TestMethod]
public void ShouldUseMatchers()
{
// Create a mock and arrange the Equals method, when called with any arguments,
// to forward the call to Object.Equals with the given arguments.
Mock.CreateLike<IEqualityComparer>(
cmp => cmp.Equals(Arg.AnyObject, Arg.AnyObject) == Object.Equals(Param._1, Param._2));
}
[TestMethod]
public void SampleTest()
{
// Create a mock and arrange:
// - the Driver property, should return "MSSQL" when called,
// - the Open() method, when called with any string argument should return true.
var conn = Mock.CreateLike<IConnection>(
me => me.Driver == "MSSQL" && me.Open(Arg.AnyString) == true);
// ASSERT
Assert.AreEqual("MSSQL", conn.Driver);
Assert.IsTrue(conn.Open(@".\SQLEXPRESS"));
}
[TestMethod]
public void ShouldUseCreateLikeAlongWithStandartArrangements()
{
// Create a mock and arrange:
// - the Driver property, should return "MSSQL" when called.
var conn = Mock.CreateLike<IConnection>(me => me.Driver == "MSSQL");
// Arranging: The Open() method must be called with any string argument and it should return true.
Mock.Arrange(() => conn.Open(Arg.AnyString)).Returns(true).MustBeCalled();
// ASSERT
Assert.AreEqual("MSSQL", conn.Driver);
Assert.IsTrue(conn.Open(@".\SQLEXPRESS"));
Mock.Assert(conn);
}
}
#region SUT
public interface IEqualityComparer
{
bool Equals(object a, object b);
}
public interface IConnection
{
string Driver { get; }
bool Open(string parameters);
}
#endregion
}

Просмотреть файл

@ -0,0 +1,67 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
using Telerik.JustMock.Helpers;
namespace JustMock.NonElevatedExamples.BasicUsage.FluentMocking
{
/// <summary>
/// Fluent Assertions allow you to easily follow the Arrange Act Assert pattern in a straigtforward way.
/// Note that JustMock dynamically checks for any assertion mechanism provided by the underlying test framework
/// if such one is available (MSTest, XUnit, NUnit, MbUnit, Silverlight) and uses it, rather than using its own
/// MockAssertionException when a mock assertion fails. This functionality extends the JustMock tooling support
/// for different test runners.
/// See http://www.telerik.com/help/justmock/basic-usage-fluent-mocking.html for full documentation of the feature.
///
/// Note: To write in a fluent way, you will need to have the Telerik.JustMock.Helpers namespace included.
/// </summary>
[TestClass]
public class FluentMocking_Tests
{
[TestMethod]
public void ShouldBeAbleToAssertSpecificFuntionForASetup()
{
var expected = @"c:\JustMock";
// ARRANGE
// Creating a mocked instance of the "IFileReader" interface.
var fileReader = Mock.Create<IFileReader>();
// Arranging: When fileReader.Path_GET is called, it should return expected.
fileReader.Arrange(x => x.Path).Returns(expected).OccursOnce();
// ACT
var actual = fileReader.Path;
// ASSERT
Assert.AreEqual(expected, actual);
fileReader.Assert(x => x.Path);
}
}
#region SUT
public interface IFileReader
{
string Path { get; set; }
void Initialize();
}
#endregion
}

Просмотреть файл

@ -0,0 +1,164 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
namespace JustMock.NonElevatedExamples.BasicUsage.Generics
{
/// <summary>
/// Telerik JustMock allows you to mock generic classes/interfaces/methods in the same way
/// as you do it for non-generic ones.
/// See http://www.telerik.com/help/justmock/basic-usage-generics.html for full documentation of the feature.
/// </summary>
[TestClass]
public class Generics_Tests
{
[TestMethod]
public void ShouldDistinguishVirtualCallsDependingOnArgumentTypes()
{
int expextedCallWithInt = 0;
int expextedCallWithString = 1;
// ARRANGE
// Creating a mock instance of the "FooGeneric" class.
var foo = Mock.Create<FooGeneric>();
// Arranging: When foo.Get<int>() generic is called, it should return expextedCallWithInt.
Mock.Arrange(() => foo.Get<int>()).Returns(expextedCallWithInt);
// Arranging: When foo.Get<string>() generic is called, it should return expextedCallWithString.
Mock.Arrange(() => foo.Get<string>()).Returns(expextedCallWithString);
// ACT
var actualCallWithInt = foo.Get<int>();
var actualCallWithString = foo.Get<string>();
// ASSERT
Assert.AreEqual(expextedCallWithInt, actualCallWithInt);
Assert.AreEqual(expextedCallWithString, actualCallWithString);
}
[TestMethod]
public void ShouldMockGenericClass()
{
int expectedValue = 1;
// ARRANGE
// Creating a mock instance of the "FooGeneric<T>" class.
var foo = Mock.Create<FooGeneric<int>>();
// Arranging: When foo.Get() is called with any integer as an argument, it should return expectedValue.
Mock.Arrange(() => foo.Get(Arg.IsAny<int>())).Returns(expectedValue);
// ACT
int actualValue = foo.Get(0);
// ASSERT
Assert.AreEqual(expectedValue, actualValue);
}
[TestMethod]
public void ShouldMockGenericMethod()
{
var expectedValue = 10;
// ARRANGE
// Creating a mock instance of the "FooGeneric<T>" class.
var genericClass = Mock.Create<FooGeneric<int>>();
// Arranging: When genericClass.Get() is called with 1, 1 as arguments, it should return expectedValue.
Mock.Arrange(() => genericClass.Get(1, 1)).Returns(expectedValue);
// ACT
var actual = genericClass.Get(1, 1);
// ASSERT
Assert.AreEqual(expectedValue, actual);
}
[TestMethod]
public void ShouldMockMethodInGenericClass()
{
bool isCalled = false;
// ARRANGE
// Creating a mock instance of the "FooGeneric<T>" class.
var genericClass = Mock.Create<FooGeneric<int>>();
// Arranging: When genericClass.Execute() is called with 1 as an argument, it should notify for call.
Mock.Arrange(() => genericClass.Execute(1)).DoInstead(() => isCalled = true);
// ACT
genericClass.Execute(1);
// ASSERT
Assert.IsTrue(isCalled);
}
[TestMethod]
public void ShouldMockVirtualGenericMethodInNonGenericClass()
{
var expectedValue = 10;
// ARRANGE
// Creating a mock instance of the "FooGeneric" class.
var genericClass = Mock.Create<FooGeneric>();
// Arranging: When genericClass.Get<int, int>() is called with 1 as an argument, it should return expectedValue.
Mock.Arrange(() => genericClass.Get<int, int>(1)).Returns(expectedValue);
// ACT
var actual = genericClass.Get<int, int>(1);
// ASSERT
Assert.AreEqual(expectedValue, actual);
}
}
#region SUT
public class FooGeneric
{
public virtual TRet Get<T, TRet>(T arg1)
{
return default(TRet);
}
public virtual int Get<T>()
{
throw new NotImplementedException();
}
}
public class FooGeneric<T>
{
public virtual T Get(T arg)
{
throw new NotImplementedException();
}
public virtual T Get(T arg, T arg2)
{
throw new NotImplementedException();
}
public virtual void Execute<T1>(T1 arg)
{
throw new Exception();
}
}
#endregion
}

Просмотреть файл

@ -0,0 +1,209 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
namespace JustMock.NonElevatedExamples.BasicUsage.Matchers
{
/// <summary>
/// See http://www.telerik.com/help/justmock/basic-usage-matchers.html for full documentation of the feature.
/// Matchers let you ignore passing actual values as arguments used in mocks.
/// Instead, they give you the possibility to pass just an expression that satisfies the
/// argument type or the expected value range. There are several types of matchers supported in Telerik JustMock:
/// - Defined Matchers:
/// Arg.AnyBool
/// Arg.AnyDouble
/// Arg.AnyFloat
/// Arg.AnyGuid
/// Arg.AnyInt
/// Arg.AnyLong
/// Arg.AnyObject
/// Arg.AnyShort
/// Arg.AnyString
/// Arg.NullOrEmpty
/// - Arg.IsAny<[Type]>();
/// - Arg.IsInRange([FromValue : int], [ToValue : int], [RangeKind])
/// - Arg.Matches<T>(Expression<Predicate<T>> expression)
/// </summary>
[TestClass]
public class Matchers_Tests
{
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void UsingMatchersAndSpecializations()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging when foo.Echo() is called with any integer as an argument it should return 10.
Mock.Arrange(() => foo.Echo(Arg.AnyInt)).Returns(10);
// Arranging when foo.Echo() is called with integer, bigger than 10 as an argument it should throw ArgumentException.
Mock.Arrange(() => foo.Echo(Arg.Matches<int>(x => x > 10))).Throws(new ArgumentException());
// ACT
int actual = foo.Echo(1);
// ASSERT
Assert.AreEqual(10, actual);
// ACT - This will throw ArgumentException.
foo.Echo(11);
}
[TestMethod]
public void ShouldUseMatchersInArrange()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging when foo.Echo() is called with arguments: integer equals to 10 and integer equals to 20,
// it should return 30.
Mock.Arrange(() => foo.Echo(Arg.Matches<int>(x => x == 10), Arg.Matches<int>(x => x == 20))).Returns(30);
// ACT
var actual = foo.Echo(10, 20);
// ASSERT
Assert.AreEqual(30, actual);
}
[TestMethod]
public void IgnoringAllArgumentsForASpecificExpectation()
{
// Arrange
var foo = Mock.Create<IFoo>();
Mock.Arrange(() => foo.Echo(0, 0)).IgnoreArguments().Returns(10);
// Act
int actual = foo.Echo(10, 200);
// Assert
Assert.AreEqual(10, actual);
}
[TestMethod]
public void ShouldUseMatchersInAssert()
{
// ARRANGE
// Creating a mocked instance of the "IPaymentService" interface.
var paymentService = Mock.Create<IPaymentService>();
// ACT
paymentService.ProcessPayment(DateTime.Now, 54.44M);
// ASSERT - Asserting that paymentService.ProcessPayment() is called with arguments:
// - any DateTime
// - decimal equals 54.44M.
Mock.Assert(() => paymentService.ProcessPayment(
Arg.IsAny<DateTime>(),
Arg.Matches<decimal>(paymentAmount => paymentAmount == 54.44M)));
}
[TestMethod]
public void ShouldIgnoreArgumentsWuthMatcherInAssert()
{
// ARRANGE
// Creating a mocked instance of the "IPaymentService" interface.
var paymentService = Mock.Create<IPaymentService>();
// ACT
paymentService.ProcessPayment(DateTime.Now, 54.44M);
// ASSERT - Asserting that paymentService.ProcessPayment() is called no matter the arguments.
Mock.Assert(() => paymentService.ProcessPayment(new DateTime(), 0), Args.Ignore());
}
[TestMethod]
public void MatchingCertainRefParameters()
{
int myRefArg = 5;
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging when foo.Bar() is called with ref argument that equals 5, it should return 10.
Mock.Arrange(() => foo.Bar(ref Arg.Ref(5).Value)).Returns(10);
// ACT
int actual = foo.Bar(ref myRefArg);
// ASSERT
Assert.AreEqual(10, actual);
Assert.AreEqual(5, myRefArg); // Asserting that the ref arguments has not been changed.
}
[TestMethod]
public void MatchingRefParametersOfAnyType()
{
int myRefArg = 5;
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging when foo.Bar() is called with any integer ref argument, it should return 10.
Mock.Arrange(() => foo.Bar(ref Arg.Ref(Arg.AnyInt).Value)).Returns(10);
// ACT
int actual = foo.Bar(ref myRefArg);
// ASSERT
Assert.AreEqual(10, actual);
Assert.AreEqual(5, myRefArg); // Asserting that the ref arguments has not been changed.
}
[TestMethod]
public void MatchingRefParametersWithSpecialization()
{
int myRefArg = 11;
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging when foo.Bar() is called with integer ref argument that is bigger than 10, it should return 10.
Mock.Arrange(() => foo.Bar(ref Arg.Ref(Arg.Matches<int>(x=> x > 10)).Value)).Returns(10);
// ACT
int actual = foo.Bar(ref myRefArg);
// ASSERT
Assert.AreEqual(10, actual);
Assert.AreEqual(11, myRefArg); // Asserting that the ref arguments has not been changed.
}
}
#region SUT
public interface IPaymentService
{
void ProcessPayment(DateTime dateTi, decimal deci);
}
public interface IFoo
{
int Echo(int intArg1);
int Echo(int intArg1, int intArg2);
int Bar(ref int intArg1);
}
#endregion
}

Просмотреть файл

@ -0,0 +1,83 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
namespace JustMock.NonElevatedExamples.BasicUsage.Mock_CallOriginal
{
/// <summary>
/// The CallOriginal method marks a mocked method/property call that should execute the original method/property implementation.
/// See http://www.telerik.com/help/justmock/basic-usage-mock-call-original.html for full documentation of the feature.
/// </summary>
[TestClass]
public class Mock_CallOriginal_Tests
{
[TestMethod]
public void ReturnSum_CallOriginal_ReturnsExpectedSum()
{
// ARRANGE
// Creating a mock instance of the "Log" class.
var log = Mock.Create<Log>();
// Arranging when log.ReturnSum() is called with any integers as arguments it should execute its original implementation.
Mock.Arrange(() => log.ReturnSum(Arg.AnyInt, Arg.AnyInt)).CallOriginal();
// ACT - Calling log.ReturnSum with 1 and 2 as arguments.
var actual = log.ReturnSum(1, 2);
// We should expect 3 as a return value
int expected = 3;
// ASSERT - We are asserting that the expected and the actual values are equal.
Assert.AreEqual(expected, actual);
}
[TestMethod]
[ExpectedException(typeof(Exception))]
public void Info_CallOriginal_ThrowException()
{
// ARRANGE
// Creating a mock instance of the "Log" class.
var log = Mock.Create<Log>();
// Arranging when log.Info() is called with any string as an argument it should execute its original implementation.
Mock.Arrange(() => log.Info(Arg.IsAny<string>())).CallOriginal();
// ACT
log.Info("test");
// ASSERT - We are asserting with the [ExpectedException(typeof(Exception))] test attribute.
}
}
#region SUT
public class Log
{
public virtual int ReturnSum(int firstInt, int secondInt)
{
return firstInt + secondInt;
}
public virtual void Info(string message)
{
throw new Exception(message);
}
}
#endregion
}

Просмотреть файл

@ -0,0 +1,132 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
namespace JustMock.NonElevatedExamples.BasicUsage.Mock_DoInstead
{
/// <summary>
/// The DoInstead method is used to replace the actual implementation of a method with a mocked one.
/// See http://www.telerik.com/help/justmock/basic-usage-mock-do-instead.html for full documentation of the feature.
/// </summary>
[TestClass]
public class Mock_DoInstead_Tests
{
[TestMethod]
public void Execute_OnExecuteWithAnyStringArg_ShouldNotifyAndReturnThatArg()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
bool called = false;
// Arranging: When foo.Execute() is called with any string as an argument it should change "called" to true and also return that argument.
Mock.Arrange(() => foo.Execute(Arg.IsAny<string>()))
.DoInstead(() => { called = true; })
.Returns((string s) => s);
// ACT
var actual = foo.Execute("bar");
// ASSERT
Assert.AreEqual("bar", actual);
Assert.IsTrue(called);
}
[TestMethod]
public void Submit_OnExecuteWitAnyIntArgs_ShouldAssignTheirSumToVariable()
{
// Arrange
int expected = 0;
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: When foo.Submit() is called with any integers as an arguments it should assign their sum to the "expected" variable.
Mock.Arrange(() => foo.Submit(Arg.IsAny<int>(), Arg.IsAny<int>(), Arg.IsAny<int>(), Arg.IsAny<int>()))
.DoInstead((int arg1, int arg2, int arg3, int arg4) => { expected = arg1 + arg2 + arg3 + arg4; });
// Act
foo.Submit(10, 10, 10, 10);
// Assert
Assert.AreEqual(40, expected);
}
[TestMethod]
public void Bar_OnSetTo1_ShouldNotify()
{
// Arrange
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
bool isSetTo1 = false;
// Arranging: When foo.Bar is set to 1 it should change "isSetTo1" to true.
Mock.ArrangeSet(() => { foo.Bar = 1; }).DoInstead(() => isSetTo1 = true);
// Act
foo.Bar = 1;
// Assert
Assert.IsTrue(isSetTo1);
}
[TestMethod]
public void AddTo_OnCertainCall_ShouldSumTheArgsAndAssignInsidedTheRefArg()
{
// Arrange
int refArg = 1;
// Creating a mocked instance of the "DoInsteadWithCustomDelegate" class.
var mock = Mock.Create<DoInsteadWithCustomDelegate>();
// Arranging: When mock.AddTo is called with 10 and "refArg" it should assign their sum to the second argument (refArg).
Mock.Arrange(() => mock.AddTo(10, ref refArg)).DoInstead(new RefAction<int, int>((int arg1, ref int arg2) =>
{
arg2 += arg1;
}));
// Act
mock.AddTo(10, ref refArg);
// Assert
Assert.AreEqual(11, refArg);
}
}
#region SUT
public interface IFoo
{
int Bar { get; set; }
string Execute(string str);
int Submit(int arg1, int arg2, int arg3, int arg4);
}
public delegate void RefAction<T1, T2>(T1 arg1, ref T2 arg2);
public class DoInsteadWithCustomDelegate
{
public virtual void AddTo(int arg1, ref int arg2)
{
}
}
#endregion
}

Просмотреть файл

@ -0,0 +1,74 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
namespace JustMock.NonElevatedExamples.BasicUsage.Mock_DoNothing
{
/// <summary>
/// The DoNothing method is used to arrange that a call to a method or property should be ignored.
/// See http://www.telerik.com/help/justmock/basic-usage-mock-do-nothing.html for full documentation of the feature.
/// </summary>
[TestClass]
public class Mock_DoNothing_Tests
{
[TestMethod]
public void VoidCall_OnExecute_ShouldDoNothingAndMustBeCalled()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: foo.VoidCall() should do nothing and it must be called during the test method.
Mock.Arrange(() => foo.VoidCall()).DoNothing().MustBeCalled();
// ACT
foo.VoidCall();
// ASSERT - Asserting all arrangements on "foo".
Mock.Assert(foo);
}
[TestMethod]
public void Bar_OnSetWithArgument1_ShouldDoNothingAndMustBeCalled()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: foo.Bar should do nothing when set to 1, but must be called.
Mock.ArrangeSet(() => foo.Bar = 1).DoNothing().MustBeCalled();
// ACT
foo.Bar = 1;
// ASSERT - Asserting all arrangements on "foo".
Mock.Assert(foo);
}
}
#region SUT
public interface IFoo
{
int Bar { get; set; }
void VoidCall();
}
#endregion
}

Просмотреть файл

@ -0,0 +1,94 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
namespace JustMock.NonElevatedExamples.BasicUsage.Mock_MustBeCalled
{
/// <summary>
/// <FEATURE HELP>
/// The MustBeCalled method is used to assert that a call to a given method or property is made during the execution of a test.
/// See http://www.telerik.com/help/justmock/basic-usage-mock-must-be-called.html for full documentation of the feature.
/// </summary>
[TestClass]
public class Mock_MustBeCalled_Tests
{
[TestMethod]
public void Value_OnSetTo1_ShouldBeCalled()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: foo.Value should be set to 1 during the test.
Mock.ArrangeSet(() => { foo.Value = 1; }).MustBeCalled();
// ACT
foo.Value = 1;
// ASSERT - Asserting all arrangements on "foo".
Mock.Assert(foo);
}
[TestMethod]
[ExpectedException(typeof(AssertFailedException))]
public void Value_NotSet_ShouldNotBeCalled()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: foo.Value should be set to 1 during the test.
Mock.ArrangeSet(() => { foo.Value = 1; }).MustBeCalled();
// ACT
// ASSERT - Asserting all arrangements on "foo".
Mock.Assert(foo);
}
[TestMethod]
public void Execute_OnArrangedExecuteTestCall_ShouldBeCalled()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: foo.Test() should be called during the test.
Mock.Arrange(() => foo.Test()).MustBeCalled();
// Arranging: When foo.ExecuteTest() is called, it should call foo.Test() instead.
Mock.Arrange(() => foo.ExecuteTest()).DoInstead(() => foo.Test());
// ACT
foo.ExecuteTest();
// ASSERT - Asserting all arrangements on "foo".
Mock.Assert(foo);
}
}
#region SUT
public interface IFoo
{
int Value { get; set; }
void ExecuteTest();
void Test();
}
#endregion
}

Просмотреть файл

@ -0,0 +1,137 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
namespace JustMock.NonElevatedExamples.BasicUsage.Mock_Raise
{
/// <summary>
/// The Raise method is used for raising mocked events. You can use custom or standard events.
/// See http://www.telerik.com/help/justmock/basic-usage-mock-raise.html for full documentation of the feature.
/// </summary>
[TestClass]
public class Mock_Raise_Tests
{
[TestMethod]
public void ShouldInvokeMethodForACustomEventWhenRaised()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
string expected = "ping";
string actual = string.Empty;
foo.CustomEvent += delegate(string exp)
{
actual = exp;
};
// ACT
Mock.Raise(() => foo.CustomEvent += null, expected);
// ASSERT
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void ShouldRaiseEventWithStandardEventArgs()
{
// ARRANGE
// Creating a mocked instance of the "IExecutor" interface.
var executor = Mock.Create<IExecutor<int>>();
string acutal = null;
string expected = "ping";
executor.Done += delegate(object sender, FooArgs args)
{
acutal = args.Value;
};
// ACT - Raising the event with the expected args.
Mock.Raise(() => executor.Done += null, new FooArgs(expected));
// ASSERT
Assert.AreEqual(expected, acutal);
}
[TestMethod]
public void Submit_OnIsChangedRaised_ShouldBeCalled()
{
// ARRANGE
// Creating the necessary mocked instances.
var activeDocument = Mock.Create<IDocument>();
var activeView = Mock.Create<IDocumentView>();
// Attaching the Submit method to the IsChanged event.
activeDocument.IsChanged += new EventHandler(activeDocument.Submit);
// Arranging: activeDocument.Submit should be called during the test method with any arguments.
Mock.Arrange(() => activeDocument.Submit(Arg.IsAny<object>(), Arg.IsAny<EventArgs>())).MustBeCalled();
// Arranging: activeView.Document should return activeDocument when called.
Mock.Arrange(() => activeView.Document).Returns(activeDocument);
// ACT
Mock.Raise(() => activeView.Document.IsChanged += null, EventArgs.Empty);
// ASSERT - Asserting all arrangements on "foo".
Mock.Assert(activeDocument);
}
}
#region SUT
public interface IFoo
{
event CustomEvent CustomEvent;
}
public delegate void CustomEvent(string value);
public interface IExecutor<T>
{
event EventHandler<FooArgs> Done;
}
public class FooArgs : EventArgs
{
public FooArgs()
{
}
public FooArgs(string value)
{
this.Value = value;
}
public string Value { get; set; }
}
public interface IDocumentView
{
IDocument Document { get; }
}
public interface IDocument
{
event EventHandler IsChanged;
void Submit(object sender, EventArgs e);
}
#endregion
}

Просмотреть файл

@ -0,0 +1,113 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
namespace JustMock.NonElevatedExamples.BasicUsage.Mock_Raises
{
/// <summary>
/// The Raises method is used to fire an event once a method is called.
/// See http://www.telerik.com/help/justmock/basic-usage-mock-raises.html for full documentation of the feature.
/// </summary>
[TestClass]
public class Mock_Raises_Tests
{
[TestMethod]
public void ShouldRaiseCustomEventOnMethodCall()
{
var expected = "ping";
string actual = string.Empty;
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: When foo.RaiseMethod() is called, it should raise foo.CustomEvent with expected args.
Mock.Arrange(() => foo.RaiseMethod()).Raises(() => foo.CustomEvent += null, expected);
foo.CustomEvent += (s) => { actual = s; };
// ACT
foo.RaiseMethod();
// ASSERT
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void ShouldRaiseCustomEventForFuncCalls()
{
bool isRaised = false;
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: When foo.Echo() is called with expected arguments, it should raise foo.EchoEvent with arg: true.
Mock.Arrange(() => foo.Echo("string")).Raises(() => foo.EchoEvent += null, true);
foo.EchoEvent += (c) => { isRaised = c; };
// ACT
var actual = foo.Echo("string");
// ASSERT
Assert.IsTrue(isRaised);
}
[TestMethod]
public void ShouldAssertMultipleEventSubscription()
{
bool isRaisedForFirstSubscr = false;
bool isRaisedForSecondSubscr = false;
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: When foo.Execute() is called, it should raise foo.EchoEvent with arg: true.
Mock.Arrange(() => foo.Execute()).Raises(() => foo.EchoEvent += null, true);
// Subscribing for the event
foo.EchoEvent += c => { isRaisedForFirstSubscr = c; };
foo.EchoEvent += c => { isRaisedForSecondSubscr = c; };
// ACT
foo.Execute();
// ASSERT
Assert.IsTrue(isRaisedForFirstSubscr);
Assert.IsTrue(isRaisedForSecondSubscr);
}
}
#region SUT
public delegate void CustomEvent(string value);
public delegate void EchoEvent(bool echoed);
public interface IFoo
{
event CustomEvent CustomEvent;
event EchoEvent EchoEvent;
void RaiseMethod();
string Echo(string arg);
void Execute();
}
#endregion
}

Просмотреть файл

@ -0,0 +1,135 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
using Telerik.JustMock.Helpers;
namespace JustMock.NonElevatedExamples.BasicUsage.Mock_Returns
{
/// <summary>
/// The Returns method is used with non void calls to ignore the actual call and return a custom value.
/// See http://www.telerik.com/help/justmock/basic-usage-mock-returns.html for full documentation of the feature.
/// </summary>
[TestClass]
public class Mock_Returns_Tests
{
[TestMethod]
public void ShouldAssertPropertyGetCall()
{
var expected = 10;
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: When foo.Bar is called, it should return the expected value.
Mock.Arrange(() => foo.Bar).Returns(expected);
// ACT
var actual = foo.Bar;
// ASSERT
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void ShouldAssertMethodCallWithMatcher1()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: When foo.Echo() is called with any integer as an argument, it should return 1 + that argument.
Mock.Arrange(() => foo.Echo(Arg.IsAny<int>())).Returns((int i) => ++i);
// ACT
var actual = foo.Echo(10);
// ASSERT
Assert.AreEqual(11, actual);
}
[TestMethod]
public void ShouldAssertMethodCallWithMatcher2()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: When foo.Echo() is called with an integer argument exactly matching 10,
// it should return that argument.
Mock.Arrange(() => foo.Echo(Arg.Matches<int>(x => x == 10))).Returns((int i) => i);
// ACT
var actual = foo.Echo(10);
// ASSERT
Assert.AreEqual(10, actual);
}
[TestMethod]
public void ShouldReturnWhateverSecondArgIs()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: When foo.Execute() is called with any integer arguments, it should return the second argument.
Mock.Arrange(() => foo.Execute(Arg.IsAny<int>(), Arg.IsAny<int>())).Returns((int id, int i) => i);
// ACT
var actual = foo.Execute(100, 10);
// ASSERT
Assert.AreEqual(actual, 10);
}
[TestMethod]
public void ShouldReturnInSequence()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
int[] values = new int[3] { 1, 2, 3 };
// Arranging: When foo.Bar_GET is called number of times, it should return the array values in sequence.
Mock.Arrange(() => foo.Bar).ReturnsMany(values);
// ACT
var first = foo.Bar;
var second = foo.Bar;
var third = foo.Bar;
// ASSERT
Assert.AreEqual(first, 1);
Assert.AreEqual(second, 2);
Assert.AreEqual(third, 3);
}
}
#region SUT
public interface IFoo
{
int Bar { get; set; }
int Echo(int myInt);
int Execute(int myInt1, int myInt2);
}
#endregion
}

Просмотреть файл

@ -0,0 +1,69 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
namespace JustMock.NonElevatedExamples.BasicUsage.Mock_Throws
{
/// <summary>
/// The Throws method is used to throw an exception when a given call is made.
/// See http://www.telerik.com/help/justmock/basic-usage-mock-throws.html for full documentation of the feature.
/// </summary>
[TestClass]
public class Mock_Throws_Tests
{
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowExceptionOnMethodCall()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: When foo.Execute() is called with any string as an argument, it should throw an ArgumentException.
Mock.Arrange(() => foo.Execute(Arg.AnyString)).Throws<ArgumentException>();
// ACT
foo.Execute(string.Empty);
}
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void ShouldThrowExceptionWithArgumentsOnMethodCall()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: When foo.Execute() is called with an empty string as an argument,
// it should throw an ArgumentException with args: "Argument shouldn't be empty.".
Mock.Arrange(() => foo.Execute(string.Empty)).Throws<ArgumentException>("Argument shouldn't be empty.");
// ACT
foo.Execute(string.Empty);
}
}
#region SUT
public interface IFoo
{
string Execute(string myStr);
}
#endregion
}

Просмотреть файл

@ -0,0 +1,159 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
namespace JustMock.NonElevatedExamples.BasicUsage.MockingProperties
{
/// <summary>
/// Mocking properties is similar to mocking methods, but there are a few cases that need special attention
/// like mocking indexers and particular set operations.
/// See http://www.telerik.com/help/justmock/basic-usage-mock-properties.html for full documentation of the feature.
/// </summary>
[TestClass]
public class MockingProperties_Tests
{
[TestMethod]
public void ShouldFakePropertyGet()
{
var expectedValue = 25;
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: When foo.Value_GET is called, it should return expectedValue.
Mock.Arrange(() => foo.Value).Returns(expectedValue);
// ACT
var actual = foo.Value;
// ASSERT
Assert.AreEqual(expectedValue, actual);
}
[TestMethod]
public void ShouldAssertPropertySet()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: That foo.Value must be set to 1 during the test method.
Mock.ArrangeSet(() => foo.Value = 1).MustBeCalled();
// ACT
foo.Value = 1;
// ASSERT - Asserting the expected foo.Value_SET.
Mock.AssertSet(() => foo.Value = 1);
}
[TestMethod]
[ExpectedException(typeof(StrictMockException))]
public void ShouldThrowExceptionOnTheThirdPropertySetCall()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface with Behavior.Strict.
var foo = Mock.Create<IFoo>(Behavior.Strict);
// Arranging: That foo.Value should be set to an integer bigger than 3.
Mock.ArrangeSet(() => foo.Value = Arg.Matches<int>(x => x > 3));
// ACT - These lines will not trigger the Strict behavior, because they satisfy the expectations.
foo.Value = 4;
foo.Value = 5;
// This throws MockException because matching criteria is not met.
foo.Value = 3;
}
[TestMethod]
public void MockIndexers()
{
// ARRANGE
// Creating a mocked instance of the "IIndexedFoo" interface.
var indexedFoo = Mock.Create<IIndexedFoo>();
// Arranging: That the [0] element of indexedFoo should return "ping".
Mock.Arrange(() => indexedFoo[0]).Returns("ping");
// Arranging: That the [1] element of indexedFoo should return "pong".
Mock.Arrange(() => indexedFoo[1]).Returns("pong");
// ACT
string actualFirst = indexedFoo[0];
string actualSecond = indexedFoo[1];
// ASSERT
Assert.AreEqual("ping", actualFirst);
Assert.AreEqual("pong", actualSecond);
}
[TestMethod]
[ExpectedException(typeof(StrictMockException))]
public void ShouldThrowExceptionForNotArrangedPropertySet()
{
// ARRANGE
// Creating a mocked instance of the "IIndexedFoo" interface with Behavior.Strict.
var foo = Mock.Create<IIndexedFoo>(Behavior.Strict);
// Arranging: That the [0] element of foo should be set to "foo".
Mock.ArrangeSet(() => { foo[0] = "foo"; });
// ACT - This meets the expectations.
foo[0] = "foo";
// This throws StrictMockException because matching criteria is not met.
foo[0] = "bar";
}
[TestMethod]
[ExpectedException(typeof(StrictMockException))]
public void ShouldAssertIndexedSetWithMatcher()
{
// ARRANGE
// Creating a mocked instance of the "IIndexedFoo" interface with Behavior.Strict.
var foo = Mock.Create<IIndexedFoo>(Behavior.Strict);
// Arranging: That the [0] element of foo should match a string "ping".
Mock.ArrangeSet(() => { foo[0] = Arg.Matches<string>(x => x.Equals("ping")); });
// Arranging: That the [1] element of foo should be any string.
Mock.ArrangeSet(() => { foo[1] = Arg.IsAny<string>(); });
// ACT - These lines will not trigger the Strict behavior, because they satisfy the expectations.
foo[0] = "ping";
foo[1] = "pong";
// This line does not satisfy the matching criteria and throws a MockException.
foo[0] = "bar";
}
}
#region SUT
public interface IIndexedFoo
{
string this[int key] { get; set; }
}
public interface IFoo
{
int Value { get; set; }
}
#endregion
}

Просмотреть файл

@ -0,0 +1,147 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
namespace JustMock.NonElevatedExamples.BasicUsage.RecursiveMocking
{
/// <summary>
/// Recursive mocks enable you to mock members that are obtained as a result of "chained" calls on a mock.
/// For example, recursive mocking is useful in the cases when you test code like this: foo.Bar.Baz.Do("x").
/// See http://www.telerik.com/help/justmock/basic-usage-recursive-mocking.html for full documentation of the feature.
/// </summary>
[TestClass]
public class RecursiveMocking_Tests
{
[TestMethod]
public void ShouldAssertNestedVeriables()
{
string pingArg = "ping";
var expected = "test";
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: When foo.Bar.Do() is called, it should return the expected string.
// This will automatically create mock of foo.Bar and a NullReferenceException will be avoided.
Mock.Arrange(() => foo.Bar.Do(pingArg)).Returns(expected);
// ACT
var actualFooBarDo = foo.Bar.Do(pingArg);
// ASSERT
Assert.AreEqual(expected, actualFooBarDo);
}
[TestMethod]
public void ShouldInstantiateFooBar()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// ASSERT - Not arranged members in a RecursiveLoose mocks should not be null.
Assert.IsNotNull(foo.Bar);
}
[TestMethod]
public void ShouldAssertNestedPropertyGet()
{
var expected = 10;
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: When foo.Bar.Value is called, it should return expected value.
// This will automatically create mock of foo.Bar and a NullReferenceException will be avoided.
Mock.Arrange(() => foo.Bar.Value).Returns(expected);
// ACT
var actual = foo.Bar.Value;
// ASSERT
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void ShouldAssertNestedPropertySet()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: Setting foo.Bar.Value to 5, should do nothing.
// This will automatically create mock of foo.Bar and a NullReferenceException will be avoided.
Mock.ArrangeSet(() => { foo.Bar.Value = 5; }).DoNothing().MustBeCalled();
// ACT
foo.Bar.Value = 5;
// ASSERT
Mock.Assert(foo);
}
[TestMethod]
public void NestedPropertyAndMethodCalls()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: When foo.Bar.Do() is called with "x" as an argument, it return "xit".
// This will automatically create mock of foo.Bar and a NullReferenceException will be avoided.
Mock.Arrange(() => foo.Bar.Do("x")).Returns("xit");
// Arranging: When foo.Bar.Baz.Do() is called with "y" as an argument, it return "yit".
// This will automatically create mock of foo.Bar and foo.Bar.Baz and a
// NullReferenceException will be avoided.
Mock.Arrange(() => foo.Bar.Baz.Do("y")).Returns("yit");
// ACT
var actualFooBarDo = foo.Bar.Do("x");
var actualFooBarBazDo = foo.Bar.Baz.Do("y");
// ASSERT
Assert.AreEqual("xit", actualFooBarDo);
Assert.AreEqual("yit", actualFooBarBazDo);
}
}
#region SUT
public interface IFoo
{
IBar Bar { get; set; }
string Do(string command);
}
public interface IBar
{
int Value { get; set; }
string Do(string command);
IBaz Baz { get; set; }
}
public interface IBaz
{
string Do(string command);
}
#endregion
}

Просмотреть файл

@ -0,0 +1,132 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
using Telerik.JustMock.Helpers;
namespace JustMock.NonElevatedExamples.BasicUsage.SequentialMocking
{
/// <summary>
/// Sequential mocking allows you to return different values on the same or different consecutive calls to
/// one and the same type. In other words, you can set up expectations for successive calls of the same type.
/// See http://www.telerik.com/help/justmock/basic-usage-sequential-mocking.html for full documentation of the feature.
/// </summary>
[TestClass]
public class SequentialMocking_Tests
{
[TestMethod]
public void ShouldArrangeAndAssertInASequence()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: Sequence calls to foo.GetIntValue() should return different values.
Mock.Arrange(() => foo.GetIntValue()).Returns(0).InSequence();
Mock.Arrange(() => foo.GetIntValue()).Returns(1).InSequence();
Mock.Arrange(() => foo.GetIntValue()).Returns(2).InSequence();
// ACT
int actualFirstCall = foo.GetIntValue();
int actualSecondCall = foo.GetIntValue();
int actualThirdCall = foo.GetIntValue();
// ASSERT
Assert.AreEqual(0, actualFirstCall);
Assert.AreEqual(1, actualSecondCall);
Assert.AreEqual(2, actualThirdCall);
}
[TestMethod]
public void ShouldAssertSequentlyWithAMatchers()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var iFoo = Mock.Create<IFoo>();
// Arranging:
// When iFoo.Execute() is called with "foo" as an argument, it should return "hello".
// Next iFoo.Execute() calls with any string as an argument should return "bye".
Mock.Arrange(() => iFoo.Execute("foo")).Returns("hello").InSequence();
Mock.Arrange(() => iFoo.Execute(Arg.IsAny<string>())).Returns("bye").InSequence();
// ACT
string actualFirstCall = iFoo.Execute("foo");
string actualSecondCall = iFoo.Execute("bar");
// This will also return "bye" as this is the last arrange in the sequence.
string actualThirdCall = iFoo.Execute("foobar");
// ASSERT
Assert.AreEqual("hello", actualFirstCall);
Assert.AreEqual("bye", actualSecondCall);
Assert.AreEqual("bye", actualThirdCall);
}
[TestMethod]
public void ShouldAssertMultipleCallsWithDifferentMatchers()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: First call to foo.Echo() with any integer bigger than 10 as an argument should return 10,
// every next call to foo.Echo() with any integer bigger than 20 as an argument should return 20.
Mock.Arrange(() => foo.Echo(Arg.Matches<int>(x => x > 10))).Returns(10).InSequence();
Mock.Arrange(() => foo.Echo(Arg.Matches<int>(x => x > 20))).Returns(20).InSequence();
// ACT
int actualFirstCall = foo.Echo(11);
int actualSecondCall = foo.Echo(21);
// ASSERT
Assert.AreEqual(10, actualFirstCall);
Assert.AreEqual(20, actualSecondCall);
}
[TestMethod]
public void ShouldArrangeInSequencedReturns()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface.
var foo = Mock.Create<IFoo>();
// Arranging: First call to foo.Echo() with any integer as an argument should return 10,
// every next call to foo.Echo() (using the same matcher) should return 11.
Mock.Arrange(() => foo.Echo(Arg.AnyInt)).Returns(10).Returns(11);
// ACT
var ctualFirstCall = foo.Echo(1);
var actualSecondCall = foo.Echo(2);
// ASSERT
Assert.AreEqual(10, ctualFirstCall);
Assert.AreEqual(11, actualSecondCall);
}
}
#region SUT
public interface IFoo
{
string Execute(string arg);
int Echo(int arg1);
int GetIntValue();
}
#endregion
}

Просмотреть файл

@ -0,0 +1,66 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
namespace JustMock.NonElevatedExamples.BasicUsage.StrictMocking
{
/// <summary>
/// You may have a case where you want to enable only arranged calls and to reject others.
/// In such cases you need to set the mock Behavior to Strict.
/// See http://www.telerik.com/help/justmock/basic-usage-strict-mocking.html for full documentation of the feature.
/// </summary>
[TestClass]
public class StrictMocking_Tests
{
[ExpectedException(typeof(StrictMockException))]
[TestMethod]
public void ArbitraryCallsShouldGenerateException()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface with Behavior.Strict.
// This means, every non-arranged call from this instance will throw MockException.
var foo = Mock.Create<IFoo>(Behavior.Strict);
//ACT - As foo.VoidCall() is not arranged, it should throw an exception.
foo.VoidCall();
}
[TestMethod]
[ExpectedException(typeof(StrictMockException))]
public void ArbitraryCallsShouldGenerateExpectedException()
{
// ARRANGE
// Creating a mocked instance of the "IFoo" interface with Behavior.Strict.
// This means, every non-arranged call from this instance will throw MockException.
var foo = Mock.Create<IFoo>(Behavior.Strict);
//ACT - As foo.VoidCall() is not arranged, it should throw an exception.
foo.GetGuid();
}
}
#region SUT
public interface IFoo
{
void VoidCall();
Guid GetGuid();
}
#endregion
}

Просмотреть файл

@ -0,0 +1,97 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>
</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{6B7BC32C-34EC-495E-B596-8BBD5B6A0B4B}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>JustMock.NonElevatedExamples</RootNamespace>
<AssemblyName>JustMock.NonElevatedExamples</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<TargetFrameworkProfile />
<SccProjectName>SAK</SccProjectName>
<SccLocalPath>SAK</SccLocalPath>
<SccAuxPath>SAK</SccAuxPath>
<SccProvider>SAK</SccProvider>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
<Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data.Entity" />
<Reference Include="Telerik.JustMock, Version=2013.2.724.0, Culture=neutral, PublicKeyToken=721b6c5bc0326b3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\..\..\Program Files (x86)\Telerik\JustMock\Libraries\Telerik.JustMock.dll</HintPath>
</Reference>
<Reference Include="Telerik.JustMock.Container, Version=2013.2.724.0, Culture=neutral, PublicKeyToken=721b6c5bc0326b3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\..\..\Program Files (x86)\Telerik\JustMock\Libraries\Telerik.JustMock.Container.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<CodeAnalysisDependentAssemblyPaths Condition=" '$(VS100COMNTOOLS)' != '' " Include="$(VS100COMNTOOLS)..\IDE\PrivateAssemblies">
<Visible>False</Visible>
</CodeAnalysisDependentAssemblyPaths>
</ItemGroup>
<ItemGroup>
<Compile Include="AdvancedUsage\ConcreteMocking.cs" />
<Compile Include="AdvancedUsage\MockingDelegates.cs" />
<Compile Include="AdvancedUsage\PrivateAccessor.cs" />
<Compile Include="BasicUsage\AssertingOccurrence.cs" />
<Compile Include="BasicUsage\Automocking.cs" />
<Compile Include="BasicUsage\CreateMocksByExample.cs" />
<Compile Include="BasicUsage\FluentMocking.cs" />
<Compile Include="BasicUsage\Generics.cs" />
<Compile Include="BasicUsage\Matchers.cs" />
<Compile Include="BasicUsage\Mock.CallOriginal.cs" />
<Compile Include="BasicUsage\Mock.DoInstead.cs" />
<Compile Include="BasicUsage\Mock.DoNothing.cs" />
<Compile Include="BasicUsage\Mock.MustBeCalled.cs" />
<Compile Include="BasicUsage\Mock.Raise.cs" />
<Compile Include="BasicUsage\Mock.Raises.cs" />
<Compile Include="BasicUsage\Mock.Returns.cs" />
<Compile Include="BasicUsage\Mock.Throws.cs" />
<Compile Include="BasicUsage\MockingProperties.cs" />
<Compile Include="BasicUsage\RecursiveMocking.cs" />
<Compile Include="BasicUsage\SequentialMocking.cs" />
<Compile Include="BasicUsage\StrictMocking.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Просмотреть файл

@ -0,0 +1,52 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("JustMock.NonElevatedExamples")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Telerik AD")]
[assembly: AssemblyProduct("JustMock.NonElevatedExamples")]
[assembly: AssemblyCopyright("Copyright @ Telerik 2002-2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9c2e4a6a-4ec8-42e2-970c-03248c037518")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("123.4.5.0")]
[assembly: AssemblyFileVersion("123.4.5.0")]

Просмотреть файл

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<TestSettings name="Local" id="2ca3d07c-27ce-4719-ae6f-a54cdab12086" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010">
<Description>These are default test settings for a local test run.</Description>
<Deployment enabled="false" />
<Execution>
<TestTypeSpecific />
<AgentRule name="Execution Agents">
</AgentRule>
</Execution>
</TestSettings>

Просмотреть файл

@ -0,0 +1,34 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{CA6553F0-B856-455F-9821-F60B6E344C9C}"
ProjectSection(SolutionItems) = preProject
Local.testsettings = Local.testsettings
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JustMock.NonElevatedExamples", "JustMock.NonElevatedExamples\JustMock.NonElevatedExamples.csproj", "{6B7BC32C-34EC-495E-B596-8BBD5B6A0B4B}"
EndProject
Global
GlobalSection(TeamFoundationVersionControl) = preSolution
SccNumberOfProjects = 2
SccEnterpriseProvider = {4CA58AB2-18FA-4F8D-95D4-32DDF27D184C}
SccTeamFoundationServer = http://tfs:8082/defaultcollection
SccLocalPath0 = .
SccProjectUniqueName0 = JustMock.NonElevatedExamples\\JustMock.NonElevatedExamples.csproj
SccProjectName0 = JustMock.NonElevatedExamples
SccLocalPath1 = JustMock.NonElevatedExamples
EndGlobalSection
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{6B7BC32C-34EC-495E-B596-8BBD5B6A0B4B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6B7BC32C-34EC-495E-B596-8BBD5B6A0B4B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6B7BC32C-34EC-495E-B596-8BBD5B6A0B4B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6B7BC32C-34EC-495E-B596-8BBD5B6A0B4B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

Просмотреть файл

@ -0,0 +1,91 @@
' limitations under the License.
' See the License for the specific language governing permissions and
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' distributed under the License is distributed on an "AS IS" BASIS,
' Unless required by applicable law or agreed to in writing, software
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' You may obtain a copy of the License at
' you may not use this file except in compliance with the License.
' Licensed under the Apache License, Version 2.0 (the "License");
'
' Copyright © 2010-2014 Telerik AD
' JustMock Lite
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Namespace JustMock.NonElevatedExamples.AdvancedUsage.ConcreteMocking
''' <summary>
''' Concrete mocking is one of the advanced features supported in Telerik JustMock. Up to this point we have been talking
''' mostly about mocking interfaces. This feature allows you to mock the creation of an object. To some extent this is available
''' in the free edition and there are more things you can do in the commercial edition of the product.
''' See http://www.telerik.com/help/justmock/advanced-usage-concrete-mocking.html for full documentation of the feature.
''' </summary>
<TestClass> _
Public Class ConcreteMocking_Tests
<TestMethod> _
<ExpectedException(GetType(NotImplementedException))> _
Public Sub ShouldCallOriginalForVirtualMemberWithMockedConstructor()
' ARRANGE
' Creating a mocked instance of the "FooVirtual" class.
' Telerik JustMock also gives you the ability to explicitly specify whether a constructor should be mocked or not.
' By default the constructor is not mocked.
Dim foo = Mock.Create(Of FooVirtual)(Constructor.Mocked)
' Arranging: When foo.GetList() is called, it should call the original method implementation.
Mock.Arrange(Function() foo.GetList()).CallOriginal()
' ACT
foo.GetList()
End Sub
<TestMethod> _
Public Sub VoidMethod_OnExcute_ShouldCallGetList()
' ARRANGE
' Creating a mocked instance of the "FooVirtual" class.
' Telerik JustMock also gives you the ability to explicitly specify whether a constructor should be mocked or not.
' By default the constructor is not mocked.
Dim foo = Mock.Create(Of FooVirtual)(Constructor.Mocked)
' Arranging: When foo.SubMethod() is called, it should call foo.GetList() instead.
Mock.Arrange(Sub() foo.SubMethod()).DoInstead(Function() foo.GetList())
' Arranging: That foo.GetList() must be called during the test method and it should do nothing.
Mock.Arrange(Function() foo.GetList()).DoNothing().MustBeCalled()
' ACT
foo.SubMethod()
' ASSERT
Mock.Assert(foo)
End Sub
End Class
#Region "SUT"
Public Class FooVirtual
Public Sub New()
Throw New NotImplementedException("Constructor")
End Sub
Public Overridable Property Name() As String
Get
Return m_Name
End Get
Set(value As String)
m_Name = Value
End Set
End Property
Private m_Name As String
Public Overridable Sub SubMethod()
Throw New NotImplementedException()
End Sub
Public Overridable Function GetList() As IList(Of Integer)
Throw New NotImplementedException()
End Function
End Class
#End Region
End Namespace

Просмотреть файл

@ -0,0 +1,135 @@
' JustMock Lite
' Copyright © 2010-2014 Telerik AD
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.
Namespace JustMock.NonElevatedExamples.AdvancedUsage.MockingDelegates
''' <summary>
''' With Telerik JustMock you can mock delegates and additionally apply all mock capabilities on them. For example, you can
''' assert against their invocation, arrange certain expectations and then pass them in the system under test.
''' See http://www.telerik.com/help/justmock/advanced-usage-mocking-delegates.html for full documentation of the feature.
''' </summary>
<TestClass>
Public Class MockingDelegates_Tests
<TestMethod>
Public Sub ShouldArrangeReturnExpectation()
' ARRANGE
' Creating a mock instance of the Func<int, int> delegate.
Dim delegateMock = Mock.Create(Of Func(Of Integer, Integer))()
' Arranging: When the mock is called with 10 as an integer argument, it should return 20.
Mock.Arrange(Function() delegateMock(10)).Returns(20)
' ACT
Dim mySUT = New Foo()
' Assigning the mock to the dependent property.
mySUT.FuncDelegate = delegateMock
Dim actual = mySUT.GetInteger(10)
' ASSERT
Assert.AreEqual(20, actual)
End Sub
<TestMethod>
Public Sub ShouldArrangeOccurrenceExpectation()
' ARRANGE
' Creating a mock instance of the Func<int, int> delegate.
Dim delegateMock = Mock.Create(Of Func(Of Integer, Integer))()
' Arranging: That the mock should be called with any integer values during the test execution.
Mock.Arrange(Function() delegateMock(Arg.AnyInt)).MustBeCalled()
' ACT
Dim mySUT = New Foo()
mySUT.FuncDelegate = delegateMock
' Assigning the mock to the dependent property.
Dim actual = mySUT.GetInteger(123)
' ASSERT - asserting the mock.
Mock.Assert(delegateMock)
End Sub
<TestMethod>
Public Sub ShouldPassPrearrangedDelegateMockAsArgument()
' ARRANGE
' Creating a mock instance of the Func<string> delegate.
Dim delegateMock = Mock.Create(Of Func(Of String))()
' Arranging: When the mock is called, it should return "Success".
Mock.Arrange(Function() delegateMock()).Returns("Success")
' ACT
Dim testInstance = New DataRepository()
' Passing the mock into our system under test.
Dim actual = testInstance.GetCurrentUserId(delegateMock)
' ASSERT
Assert.AreEqual("Success", actual)
End Sub
<TestMethod>
Public Sub ShouldPassDelegateMockAsArgumentAndAssertItsOccurrence()
Dim isCalled As Boolean = False
' ARRANGE
' Creating a mock instance of the Action<int> delegate.
Dim delegateMock = Mock.Create(Of Action(Of Integer))()
' Arranging: When the mock is called with any integer value as an argument, it should assign true to isCalled instead.
Mock.Arrange(Sub() delegateMock(Arg.AnyInt)).DoInstead(Function() InlineAssignHelper(isCalled, True))
' ACT
Dim testInstance = New DataRepository()
' Passing the mock into our system under test.
testInstance.ApproveCredentials(delegateMock)
' ASSERT
Assert.IsTrue(isCalled)
End Sub
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
target = value
Return value
End Function
End Class
#Region "SUT"
Public Class DataRepository
Public Function GetCurrentUserId(callback As Func(Of String)) As String
Return callback()
End Function
Public Sub ApproveCredentials(callback As Action(Of Integer))
' Some logic here...
callback(1)
End Sub
End Class
Public Class Foo
Public Property FuncDelegate() As Func(Of Integer, Integer)
Get
Return m_FuncDelegate
End Get
Set(value As Func(Of Integer, Integer))
m_FuncDelegate = Value
End Set
End Property
Private m_FuncDelegate As Func(Of Integer, Integer)
Public Function GetInteger(toThisInt As Integer) As Integer
Return FuncDelegate(toThisInt)
End Function
End Class
#End Region
End Namespace

Просмотреть файл

@ -0,0 +1,85 @@
' limitations under the License.
' See the License for the specific language governing permissions and
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' distributed under the License is distributed on an "AS IS" BASIS,
' Unless required by applicable law or agreed to in writing, software
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' You may obtain a copy of the License at
' you may not use this file except in compliance with the License.
' Licensed under the Apache License, Version 2.0 (the "License");
'
' Copyright © 2010-2014 Telerik AD
' JustMock Lite
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Namespace JustMock.NonElevatedExamples.AdvancedUsage.PrivateAccessorNamespace
''' <summary>
''' The Telerik JustMock PrivateAccessor allows you to call non-public members of the tested code right in your unit tests.
''' See http://www.telerik.com/help/justmock/advanced-usage-private-accessor.html for full documentation of the feature.
''' </summary>
<TestClass> _
Public Class PrivateAccessor_Tests
<TestMethod> _
Public Sub PrivateAccessor_ShouldCallPrivateMethod()
' ACT
' Wrapping the instance holding the private method.
Dim inst = New PrivateAccessor(New ClassWithNonPublicMembers())
' Calling the non-public method by giving its exact name.
Dim actual = inst.CallMethod("MePrivate")
' ASSERT
Assert.AreEqual(1000, actual)
End Sub
<TestMethod> _
Public Sub PrivateAccessor_ShouldCallPrivateStaticMethod()
' ACT
' Wrapping the instance holding the private method by type.
Dim inst = PrivateAccessor.ForType(GetType(ClassWithNonPublicMembers))
' Calling the non-public static method by giving its exact name.
Dim actual = inst.CallMethod("MeStaticPrivate")
' ASSERT
Assert.AreEqual(2000, actual)
End Sub
<TestMethod> _
Public Sub PrivateAccessor_ShouldGetSetProperty()
' ACT
' Wrapping the instance holding the private property.
Dim inst = New PrivateAccessor(New ClassWithNonPublicMembers())
' Setting the value of the private property.
inst.SetProperty("Prop", 555)
' ASSERT - Asserting with getting the value of the private property.
Assert.AreEqual(555, inst.GetProperty("Prop"))
End Sub
End Class
#Region "SUT"
Public Class ClassWithNonPublicMembers
Private Property Prop() As Integer
Get
Return m_Prop
End Get
Set(value As Integer)
m_Prop = Value
End Set
End Property
Private m_Prop As Integer
Private Function MePrivate() As Integer
Return 1000
End Function
Private Shared Function MeStaticPrivate() As Integer
Return 2000
End Function
End Class
#End Region
End Namespace

Просмотреть файл

@ -0,0 +1,314 @@
' limitations under the License.
' See the License for the specific language governing permissions and
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' distributed under the License is distributed on an "AS IS" BASIS,
' Unless required by applicable law or agreed to in writing, software
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' You may obtain a copy of the License at
' you may not use this file except in compliance with the License.
' Licensed under the Apache License, Version 2.0 (the "License");
'
' Copyright © 2010-2014 Telerik AD
' JustMock Lite
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Namespace JustMock.NonElevatedExamples.BasicUsage.AssertingOccurrence
''' <summary>
''' See http://www.telerik.com/help/justmock/basic-usage-asserting-occurrence.html for full documentation of the feature.
''' Occurrence is used in conjunction with Mock.Assert and Mock.AssertSet to determine how many times a call has occurred.
''' There are 6 types of occurrence that we can use:
''' Occurs.Never() - Specifies that a particular call is never made on a mock.
''' Occurs.Once() - Specifies that a call has occurred only once on a mock.
''' Occurs.AtLeastOnce() - Specifies that a call has occurred at least once on a mock.
''' Occurs.AtLeast(numberOfTimes) - Specifies the number of times at least a call should occur on a mock.
''' Occurs.AtMost(numberOfTimes) - Specifies the number of times at most a call should occur on a mock.
''' Occurs.Exactly(numberOfTimes) - Specifies exactly the number of times a call should occur on a mock.
''' Furthermore, you can set occurrence directly in the arrangement of a method.
''' You can use one of 5 different constructs of Occur:
''' Occurs(numberOfTimes) - Specifies exactly the number of times a call should occur on a mock.
''' OccursOnce() - Specifies that a call should occur only once on a mock.
''' OccursNever() - Specifies that a particular call should never be made on a mock.
''' OccursAtLeast(numberOfTimes) - Specifies that a call should occur at least once on a mock.
''' OccursAtMost(numberOfTimes) - Specifies the number of times at most a call should occur on a mock.
''' </summary>
<TestClass> _
Public Class AssertingOccurrence_Tests
<TestMethod> _
Public Sub ShouldOccursNever()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' ASSERT - Asserting that foo.Submit() has never occurred during the test method.
Mock.Assert(Sub() foo.Submit(), Occurs.Never())
End Sub
<TestMethod> _
Public Sub ShouldOccursOnce()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' ACT
foo.Submit()
' ASSERT - Asserting that foo.Submit() occurs exactly once during the test method.
Mock.Assert(Sub() foo.Submit(), Occurs.Once())
End Sub
<TestMethod> _
Public Sub ShouldOccursAtLeastOnce()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' ACT
foo.Submit()
' ASSERT - Asserting that foo.Submit() occurs at least once (could be more than once) during the test method.
Mock.Assert(Sub() foo.Submit(), Occurs.AtLeastOnce())
' ACT - Calling foo.Submit() more times.
foo.Submit()
foo.Submit()
' ASSERT - This should pass again.
Mock.Assert(Sub() foo.Submit(), Occurs.AtLeastOnce())
End Sub
<TestMethod> _
Public Sub ShouldOccursAtLeastCertainNumberOfTimes()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' ACT
foo.Submit()
foo.Submit()
foo.Submit()
' ASSERT - Asserting that foo.Submit() occurs at least three times during the test method.
Mock.Assert(Sub() foo.Submit(), Occurs.AtLeast(3))
' ACT - Calling foo.Submit() more times.
foo.Submit()
' ASSERT - This should pass again.
Mock.Assert(Sub() foo.Submit(), Occurs.AtLeast(3))
End Sub
<TestMethod> _
<ExpectedException(GetType(AssertFailedException))> _
Public Sub ShouldOccursCertainNumberOfTimesAtMost()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' ACT
foo.Submit()
foo.Submit()
' ASSERT - Asserting that foo.Submit() occurs maximum twice during the test method.
Mock.Assert(Sub() foo.Submit(), Occurs.AtMost(2))
' ACT - Calling foo.Submit() once again - 3 times in total.
foo.Submit()
' Assert - This throws an exception.
Mock.Assert(Sub() foo.Submit(), Occurs.AtMost(2))
End Sub
<TestMethod> _
<ExpectedException(GetType(AssertFailedException))> _
Public Sub ShouldOccursExactly()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' ACT
foo.Submit()
foo.Submit()
foo.Submit()
' ASSERT - Asserting that foo.Submit() occurs exactly 3 times during the test method.
Mock.Assert(Sub() foo.Submit(), Occurs.Exactly(3))
' ACT - Calling foo.Submit once again - 4 times in total.
foo.Submit()
' Assert - This fails because foo.Submit was called more times than specified.
Mock.Assert(Sub() foo.Submit(), Occurs.Exactly(3))
End Sub
<TestMethod> _
<ExpectedException(GetType(AssertFailedException))> _
Public Sub ShouldFailOnAssertAllWhenExpectionIsNotMet()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: That foo.Submit() should occur exactly twice during the test method.
Mock.Arrange(Sub() foo.Submit()).Occurs(2)
' ACT - No actions.
' ASSERT - This will throw an exception as the expectations are not met.
Mock.Assert(foo)
End Sub
<TestMethod> _
Public Sub ShouldArrangeOccursOnce()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: That foo.Submit() should occur exactly once during the test method.
Mock.Arrange(Sub() foo.Submit()).OccursOnce()
' ACT
foo.Submit()
' ASSERT
Mock.Assert(foo)
End Sub
<TestMethod> _
Public Sub ShouldArrangeOccursNever()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: That foo.Submit() should never occur during the test method.
Mock.Arrange(Sub() foo.Submit()).OccursNever()
' ACT - No actions.
' ASSERT
Mock.Assert(foo)
End Sub
<TestMethod> _
Public Sub ShouldArrangeOccursAtLeast()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: That foo.Submit() should occur at least twice during the test method.
Mock.Arrange(Sub() foo.Submit()).OccursAtLeast(2)
' ACT - Calling foo.Submit() 3 times.
foo.Submit()
foo.Submit()
foo.Submit()
' ASSERT - This passes as foo.Submit() is called at least twice.
Mock.Assert(foo)
End Sub
<TestMethod> _
<ExpectedException(GetType(AssertFailedException))> _
Public Sub ShouldFailWhenInvokedMoreThanRequried()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: That foo.Submit() should occur maximum twice during the test method.
Mock.Arrange(Sub() foo.Submit()).OccursAtMost(2)
' ACT
foo.Submit()
foo.Submit()
foo.Submit() ' This throws an exception because foo.Submit is being called more times than specified.
End Sub
<TestMethod> _
Public Sub ShouldBeAbleToAssertOccursUsingMatcherForSimilarCallAtOneShot()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: Different expectations depending on the argument of foo.Echo().
Mock.Arrange(Function() foo.Echo(1)).Returns(Function(arg__1 As Integer) arg__1)
Mock.Arrange(Function() foo.Echo(2)).Returns(Function(arg__1 As Integer) arg__1)
Mock.Arrange(Function() foo.Echo(3)).Returns(Function(arg__1 As Integer) arg__1)
' ACT
foo.Echo(1)
foo.Echo(2)
foo.Echo(3)
' ASSERT - This will pass as foo.Echo() has been called exactly 3 times no matter the argument.
Mock.Assert(Function() foo.Echo(Arg.AnyInt), Occurs.Exactly(3))
End Sub
<TestMethod> _
Public Sub ShouldVerifyCallsOrder()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: That foo.Submit() should be called before foo.Echo().
Mock.Arrange(Sub() foo.Submit()).InOrder()
Mock.Arrange(Function() foo.Echo(Arg.AnyInt)).InOrder()
' ACT
foo.Submit()
foo.Echo(5)
' ASSERT
Mock.Assert(foo)
End Sub
<TestMethod> _
Public Sub ShouldAssertInOrderForDifferentInstancesInTestMethodScope()
Dim userName As String = "Bob"
Dim password As String = "Password"
Dim userID As Integer = 5
Dim cart = New List(Of String)() From { _
"Foo", _
"Bar" _
}
' ARRANGE
' Creating mocked instances of the "IUserValidationService" and "IShoppingCartService" interfaces.
Dim userServiceMock = Mock.Create(Of IUserValidationService)()
Dim shoppingCartServiceMock = Mock.Create(Of IShoppingCartService)()
' Arranging: When userServiceMock.ValidateUser(userName, password) is called it should return userID.
' Also this method should occur exactly once in a given order during the test execution.
Mock.Arrange(Function() userServiceMock.ValidateUser(userName, password)).Returns(userID).InOrder().OccursOnce()
' Arranging: When shoppingCartServiceMock.LoadCart(userID) is called it should return cart.
' Also this method should occur exactly once in a given order during the test execution.
Mock.Arrange(Function() shoppingCartServiceMock.LoadCart(userID)).Returns(cart).InOrder().OccursOnce()
' ACT
userServiceMock.ValidateUser(userName, password)
shoppingCartServiceMock.LoadCart(userID)
' ASSERT - Asserting occurrence and calls order.
Mock.Assert(userServiceMock)
Mock.Assert(shoppingCartServiceMock)
End Sub
End Class
#Region "SUT"
Public Interface IFoo
Sub Submit()
Function Echo(intArg As Integer) As Integer
End Interface
Public Interface IUserValidationService
Function ValidateUser(userName As String, password As String) As Integer
End Interface
Public Interface IShoppingCartService
Function LoadCart(userID As Integer) As IList(Of String)
End Interface
#End Region
End Namespace

Просмотреть файл

@ -0,0 +1,101 @@
' JustMock Lite
' Copyright © 2010-2014 Telerik AD
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Imports Telerik.JustMock.Container
Namespace JustMock.NonElevatedExamples.BasicUsage.Automocking
''' <summary>
''' Automocking allows the developer to create an instance of a class (the system under test) without having
''' to explicitly create each individual dependency as a unique mock. The mocked dependencies are still available
''' to the developer if methods or properties need to be arranged as part of the test.
''' See http://www.telerik.com/help/justmock/basic-usage-automocking.html for full documentation of the feature.
''' </summary>
<TestClass> _
Public Class Automocking_Tests
<TestMethod> _
Public Sub ShouldMockDependenciesWithContainer()
' ARRANGE
' Creating a MockingContainer of ClassUnderTest.
' To instantiate the system uder test (the container) you should use the Instance property
' For example: container.Instance.
Dim container = New MockingContainer(Of ClassUnderTest)()
Dim expectedString As String = "Test"
' Arranging: When the GetString() method from the ISecondDependecy interface
' is called from the container, it should return expectedString.
container.Arrange(Of ISecondDependency)(Function(secondDep) secondDep.GetString()).Returns(expectedString)
' ACT - Calling SringMethod() from the mocked instance of ClassUnderTest
Dim actualString = container.Instance.StringMethod()
' ASSERT
Assert.AreEqual(expectedString, actualString)
End Sub
<TestMethod> _
Public Sub ShouldAssertAllContainerArrangments()
' ARRANGE
' Creating a MockingContainer of ClassUnderTest.
' To instantiate the system uder test (the container) you should use the Instance property
' For example: container.Instance.
Dim container = New MockingContainer(Of ClassUnderTest)()
' Arranging: That the GetString() method from the ISecondDependecy interface
' must be called from the container instance durring the test method.
container.Arrange(Of ISecondDependency)(Function(secondDep) secondDep.GetString()).MustBeCalled()
' ACT - Calling SringMethod() from the mocked instance of ClassUnderTest
Dim actualString = container.Instance.StringMethod()
' ASSERT - Asserting all expectations for the container.
container.AssertAll()
End Sub
End Class
#Region "SUT"
Public Class ClassUnderTest
Private firstDep As IFirstDependency
Private secondDep As ISecondDependency
Public Sub New(first As IFirstDependency, second As ISecondDependency)
Me.firstDep = first
Me.secondDep = second
End Sub
Public Function CollectionMethod() As IList(Of Object)
Dim firstCollection = firstDep.GetList()
Return firstCollection
End Function
Public Function StringMethod() As String
Dim secondString = secondDep.GetString()
Return secondString
End Function
End Class
Public Interface IFirstDependency
Function GetList() As IList(Of Object)
End Interface
Public Interface ISecondDependency
Function GetString() As String
End Interface
#End Region
End Namespace

Просмотреть файл

@ -0,0 +1,75 @@
' limitations under the License.
' See the License for the specific language governing permissions and
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' distributed under the License is distributed on an "AS IS" BASIS,
' Unless required by applicable law or agreed to in writing, software
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' You may obtain a copy of the License at
' you may not use this file except in compliance with the License.
' Licensed under the Apache License, Version 2.0 (the "License");
'
' Copyright © 2010-2014 Telerik AD
' JustMock Lite
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Namespace JustMock.NonElevatedExamples.BasicUsage.CreateMocksByExample
''' <summary>
''' The built-in feature for creating mocks by example saves time when it comes to tiresome set up of arrangements.
''' This functionality allows you to create mocks of a certain class (the system under test)
''' and in the same time to arrange their behavior.
''' For simple tests with few arrangements, this provides only marginal benefit.
''' The real benefit comes with complex tests with multiple arrangements
''' See http://www.telerik.com/help/justmock/basic-usage-create-mocks-by-example.html for full documentation of the feature.
''' </summary>
<TestClass> _
Public Class CreateMocksByExample_Tests
<TestMethod> _
Public Sub ShouldUseMatchers()
' Create a mock and arrange the Equals method, when called with any arguments,
' to forward the call to Object.Equals with the given arguments.
Mock.CreateLike(Of IEqualityComparer)(Function(cmp) cmp.Equals(Arg.AnyObject, Arg.AnyObject) = [Object].Equals(Param._1, Param._2))
End Sub
<TestMethod> _
Public Sub SampleTest()
' Create a mock and arrange:
' - the Driver property, should return "MSSQL" when called,
' - the Open() method, when called with any string argument should return true.
Dim conn = Mock.CreateLike(Of IConnection)(Function([me]) [me].Driver Is "MSSQL" AndAlso [me].Open(Arg.AnyString) = True)
' ASSERT
Assert.AreEqual("MSSQL", conn.Driver)
Assert.IsTrue(conn.Open(".\SQLEXPRESS"))
End Sub
<TestMethod> _
Public Sub ShouldUseCreateLikeAlongWithStandartArrangements()
' Create a mock and arrange:
' - the Driver property, should return "MSSQL" when called.
Dim conn = Mock.CreateLike(Of IConnection)(Function([me]) [me].Driver Is "MSSQL")
' Arranging: The Open() method must be called with any string argument and it should return true.
Mock.Arrange(Function() conn.Open(Arg.AnyString)).Returns(True).MustBeCalled()
' ASSERT
Assert.AreEqual("MSSQL", conn.Driver)
Assert.IsTrue(conn.Open(".\SQLEXPRESS"))
Mock.Assert(conn)
End Sub
End Class
#Region "SUT"
Public Interface IEqualityComparer
Function Equals(a As Object, b As Object) As Boolean
End Interface
Public Interface IConnection
ReadOnly Property Driver() As String
Function Open(parameters As String) As Boolean
End Interface
#End Region
End Namespace

Просмотреть файл

@ -0,0 +1,61 @@
' JustMock Lite
' Copyright © 2010-2014 Telerik AD
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Imports Telerik.JustMock.Helpers
Namespace JustMock.NonElevatedExamples.BasicUsage.FluentMocking
''' <summary>
''' Fluent Assertions allow you to easily follow the Arrange Act Assert pattern in a straigtforward way.
''' Note that JustMock dynamically checks for any assertion mechanism provided by the underlying test framework
''' if such one is available (MSTest, XUnit, NUnit, MbUnit, Silverlight) and uses it, rather than using its own
''' MockAssertionException when a mock assertion fails. This functionality extends the JustMock tooling support
''' for different test runners.
''' See http://www.telerik.com/help/justmock/basic-usage-fluent-mocking.html for full documentation of the feature.
'''
''' Note: To write in a fluent way, you will need to have the Telerik.JustMock.Helpers namespace included.
''' </summary>
<TestClass> _
Public Class FluentMocking_Tests
<TestMethod> _
Public Sub ShouldBeAbleToAssertSpecificFuntionForASetup()
Dim expected = "c:\JustMock"
' ARRANGE
' Creating a mocked instance of the "IFileReader" interface.
Dim fileReader = Mock.Create(Of IFileReader)()
' Arranging: When fileReader.Path_GET is called, it should return expected.
fileReader.Arrange(Function(x) x.Path).Returns(expected).OccursOnce()
' ACT
Dim actual = fileReader.Path
' ASSERT
Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(expected, actual)
fileReader.Assert(Function(x) x.Path)
End Sub
End Class
#Region "SUT"
Public Interface IFileReader
Property Path() As String
Sub Initialize()
End Interface
#End Region
End Namespace

Просмотреть файл

@ -0,0 +1,152 @@
' limitations under the License.
' See the License for the specific language governing permissions and
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' distributed under the License is distributed on an "AS IS" BASIS,
' Unless required by applicable law or agreed to in writing, software
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' You may obtain a copy of the License at
' you may not use this file except in compliance with the License.
' Licensed under the Apache License, Version 2.0 (the "License");
'
' Copyright © 2010-2014 Telerik AD
' JustMock Lite
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Namespace JustMock.NonElevatedExamples.BasicUsage.Generics
''' <summary>
''' Telerik JustMock allows you to mock generic classes/interfaces/methods in the same way
''' as you do it for non-generic ones.
''' See http://www.telerik.com/help/justmock/basic-usage-generics.html for full documentation of the feature.
''' </summary>
<TestClass> _
Public Class Generics_Tests
<TestMethod> _
Public Sub ShouldDistinguishVirtualCallsDependingOnArgumentTypes()
Dim expextedCallWithInt As Integer = 0
Dim expextedCallWithString As Integer = 1
' ARRANGE
' Creating a mock instance of the "FooGeneric" class.
Dim foo = Mock.Create(Of FooGeneric)()
' Arranging: When foo.Get<int>() generic is called, it should return expextedCallWithInt.
Mock.Arrange(Function() foo.[Get](Of Integer)()).Returns(expextedCallWithInt)
' Arranging: When foo.Get<string>() generic is called, it should return expextedCallWithString.
Mock.Arrange(Function() foo.[Get](Of String)()).Returns(expextedCallWithString)
' ACT
Dim actualCallWithInt = foo.[Get](Of Integer)()
Dim actualCallWithString = foo.[Get](Of String)()
' ASSERT
Assert.AreEqual(expextedCallWithInt, actualCallWithInt)
Assert.AreEqual(expextedCallWithString, actualCallWithString)
End Sub
<TestMethod> _
Public Sub ShouldMockGenericClass()
Dim expectedValue As Integer = 1
' ARRANGE
' Creating a mock instance of the "FooGeneric<T>" class.
Dim foo = Mock.Create(Of FooGeneric(Of Integer))()
' Arranging: When foo.Get() is called with any integer as an argument, it should return expectedValue.
Mock.Arrange(Function() foo.[Get](Arg.IsAny(Of Integer)())).Returns(expectedValue)
' ACT
Dim actualValue As Integer = foo.[Get](0)
' ASSERT
Assert.AreEqual(expectedValue, actualValue)
End Sub
<TestMethod> _
Public Sub ShouldMockGenericMethod()
Dim expectedValue = 10
' ARRANGE
' Creating a mock instance of the "FooGeneric<T>" class.
Dim genericClass = Mock.Create(Of FooGeneric(Of Integer))()
' Arranging: When genericClass.Get() is called with 1, 1 as arguments, it should return expectedValue.
Mock.Arrange(Function() genericClass.[Get](1, 1)).Returns(expectedValue)
' ACT
Dim actual = genericClass.[Get](1, 1)
' ASSERT
Assert.AreEqual(expectedValue, actual)
End Sub
<TestMethod> _
Public Sub ShouldMockMethodInGenericClass()
Dim isCalled As Boolean = False
' ARRANGE
' Creating a mock instance of the "FooGeneric<T>" class.
Dim genericClass = Mock.Create(Of FooGeneric(Of Integer))()
' Arranging: When genericClass.Execute() is called with 1 as an argument, it should notify for call.
Mock.Arrange(Sub() genericClass.Execute(1)).DoInstead(Function() InlineAssignHelper(isCalled, True))
' ACT
genericClass.Execute(1)
' ASSERT
Assert.IsTrue(isCalled)
End Sub
<TestMethod> _
Public Sub ShouldMockVirtualGenericMethodInNonGenericClass()
Dim expectedValue = 10
' ARRANGE
' Creating a mock instance of the "FooGeneric" class.
Dim genericClass = Mock.Create(Of FooGeneric)()
' Arranging: When genericClass.Get<int, int>() is called with 1 as an argument, it should return expectedValue.
Mock.Arrange(Function() genericClass.[Get](Of Integer, Integer)(1)).Returns(expectedValue)
' ACT
Dim actual = genericClass.[Get](Of Integer, Integer)(1)
' ASSERT
Assert.AreEqual(expectedValue, actual)
End Sub
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
target = value
Return value
End Function
End Class
#Region "SUT"
Public Class FooGeneric
Public Overridable Function [Get](Of T, TRet)(arg1 As T) As TRet
Return Nothing
End Function
Public Overridable Function [Get](Of T)() As Integer
Throw New NotImplementedException()
End Function
End Class
Public Class FooGeneric(Of T)
Public Overridable Function [Get](arg As T) As T
Throw New NotImplementedException()
End Function
Public Overridable Function [Get](arg As T, arg2 As T) As T
Throw New NotImplementedException()
End Function
Public Overridable Sub Execute(Of T1)(arg As T1)
Throw New Exception()
End Sub
End Class
#End Region
End Namespace

Просмотреть файл

@ -0,0 +1,196 @@
' JustMock Lite
' Copyright © 2010-2014 Telerik AD
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Namespace JustMock.NonElevatedExamples.BasicUsage.Matchers
''' <summary>
''' See http://www.telerik.com/help/justmock/basic-usage-matchers.html for full documentation of the feature.
''' Matchers let you ignore passing actual values as arguments used in mocks.
''' Instead, they give you the possibility to pass just an expression that satisfies the
''' argument type or the expected value range. There are several types of matchers supported in Telerik JustMock:
''' - Defined Matchers:
''' Arg.AnyBool
''' Arg.AnyDouble
''' Arg.AnyFloat
''' Arg.AnyGuid
''' Arg.AnyInt
''' Arg.AnyLong
''' Arg.AnyObject
''' Arg.AnyShort
''' Arg.AnyString
''' Arg.NullOrEmpty
''' - Arg.IsAny<[Type]>();
''' - Arg.IsInRange([FromValue : int], [ToValue : int], [RangeKind])
''' - Arg.Matches<T>(Expression<Predicate<T>> expression)
''' </summary>
<TestClass> _
Public Class Matchers_Tests
<TestMethod> _
<ExpectedException(GetType(ArgumentException))> _
Public Sub UsingMatchersAndSpecializations()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging when foo.Echo() is called with any integer as an argument it should return 10.
Mock.Arrange(Function() foo.Echo(Arg.AnyInt)).Returns(10)
' Arranging when foo.Echo() is called with integer, bigger than 10 as an argument it should throw ArgumentException.
Mock.Arrange(Function() foo.Echo(Arg.Matches(Of Integer)(Function(x) x > 10))).Throws(New ArgumentException())
' ACT
Dim actual As Integer = foo.Echo(1)
' ASSERT
Assert.AreEqual(10, actual)
' ACT - This will throw ArgumentException.
foo.Echo(11)
End Sub
<TestMethod> _
Public Sub ShouldUseMatchersInArrange()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging when foo.Echo() is called with arguments: integer equals to 10 and integer equals to 20,
' it should return 30.
Mock.Arrange(Function() foo.Echo(Arg.Matches(Of Integer)(Function(x) x = 10), Arg.Matches(Of Integer)(Function(x) x = 20))).Returns(30)
' ACT
Dim actual = foo.Echo(10, 20)
' ASSERT
Assert.AreEqual(30, actual)
End Sub
<TestMethod>
Public Sub IgnoringAllArgumentsForASpecificExpectation()
' Arrange
Dim foo = Mock.Create(Of IFoo)()
Mock.Arrange(Function() foo.Echo(0, 0)).IgnoreArguments().Returns(10)
' Act
Dim actual As Integer = foo.Echo(10, 200)
' Assert
Assert.AreEqual(10, actual)
End Sub
<TestMethod> _
Public Sub ShouldUseMatchersInAssert()
' ARRANGE
' Creating a mocked instance of the "IPaymentService" interface.
Dim paymentService = Mock.Create(Of IPaymentService)()
' ACT
paymentService.ProcessPayment(DateTime.Now, 54.44D)
' ASSERT - Asserting that paymentService.ProcessPayment() is called with arguments:
' - any DateTime
' - decimal equals 54.44M.
Mock.Assert(Sub() paymentService.ProcessPayment(Arg.IsAny(Of DateTime)(), Arg.Matches(Of Decimal)(Function(paymentAmount) paymentAmount = 54.44D)))
End Sub
<TestMethod> _
Public Sub ShouldIgnoreArgumentsWuthMatcherInAssert()
' ARRANGE
' Creating a mocked instance of the "IPaymentService" interface.
Dim paymentService = Mock.Create(Of IPaymentService)()
' ACT
paymentService.ProcessPayment(DateTime.Now, 54.44D)
' ASSERT - Asserting that paymentService.ProcessPayment() is called no matter the arguments.
Mock.Assert(Sub() paymentService.ProcessPayment(New DateTime(), 0), Args.Ignore())
End Sub
<TestMethod> _
Public Sub MatchingCertainRefParameters()
Dim myRefArg As Integer = 5
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging when foo.Bar() is called with ref argument that equals 5, it should return 10.
Mock.Arrange(Function() foo.Bar(5)).Returns(10)
' ACT
Dim actual As Integer = foo.Bar(myRefArg)
' ASSERT
Assert.AreEqual(10, actual)
Assert.AreEqual(5, myRefArg)
' Asserting that the ref arguments has not been changed.
End Sub
<TestMethod> _
Public Sub MatchingRefParametersOfAnyType()
Dim myRefArg As Integer = 5
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging when foo.Bar() is called with any integer ref argument, it should return 10.
Mock.Arrange(Function() foo.Bar(Arg.AnyInt)).Returns(10)
' ACT
Dim actual As Integer = foo.Bar(myRefArg)
' ASSERT
Assert.AreEqual(10, actual)
Assert.AreEqual(5, myRefArg)
' Asserting that the ref arguments has not been changed.
End Sub
<TestMethod> _
Public Sub MatchingRefParametersWithSpecialization()
Dim myRefArg As Integer = 11
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging when foo.Bar() is called with integer ref argument that is bigger than 10, it should return 10.
Mock.Arrange(Function() foo.Bar(Arg.Matches(Of Integer)(Function(x) x > 10))).Returns(10)
' ACT
Dim actual As Integer = foo.Bar(myRefArg)
' ASSERT
Assert.AreEqual(10, actual)
Assert.AreEqual(11, myRefArg)
' Asserting that the ref arguments has not been changed.
End Sub
End Class
#Region "SUT"
Public Interface IPaymentService
Sub ProcessPayment(dateTi As DateTime, deci As Decimal)
End Interface
Public Interface IFoo
Function Echo(intArg1 As Integer) As Integer
Function Echo(intArg1 As Integer, intArg2 As Integer) As Integer
Function Bar(ByRef intArg1 As Integer) As Integer
End Interface
#End Region
End Namespace

Просмотреть файл

@ -0,0 +1,74 @@
' limitations under the License.
' See the License for the specific language governing permissions and
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' distributed under the License is distributed on an "AS IS" BASIS,
' Unless required by applicable law or agreed to in writing, software
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' You may obtain a copy of the License at
' you may not use this file except in compliance with the License.
' Licensed under the Apache License, Version 2.0 (the "License");
'
' Copyright © 2010-2014 Telerik AD
' JustMock Lite
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Namespace JustMock.NonElevatedExamples.BasicUsage.Mock_CallOriginal
''' <summary>
''' The CallOriginal method marks a mocked method/property call that should execute the original method/property implementation.
''' See http://www.telerik.com/help/justmock/basic-usage-mock-call-original.html for full documentation of the feature.
''' </summary>
<TestClass> _
Public Class Mock_CallOriginal_Tests
<TestMethod> _
Public Sub ReturnSum_CallOriginal_ReturnsExpectedSum()
' ARRANGE
' Creating a mock instance of the "Log" class.
Dim log = Mock.Create(Of Log)()
' Arranging when log.ReturnSum() is called with any integers as arguments it should execute its original implementation.
Mock.Arrange(Function() log.ReturnSum(Arg.AnyInt, Arg.AnyInt)).CallOriginal()
' ACT - Calling log.ReturnSum with 1 and 2 as arguments.
Dim actual = log.ReturnSum(1, 2)
' We should expect 3 as a return value
Dim expected As Integer = 3
' ASSERT - We are asserting that the expected and the actual values are equal.
Assert.AreEqual(expected, actual)
End Sub
<TestMethod> _
<ExpectedException(GetType(Exception))> _
Public Sub Info_CallOriginal_ThrowException()
' ARRANGE
' Creating a mock instance of the "Log" class.
Dim log = Mock.Create(Of Log)()
' Arranging when log.Info() is called with any string as an argument it should execute its original implementation.
Mock.Arrange(Sub() log.Info(Arg.IsAny(Of String)())).CallOriginal()
' ACT
log.Info("test")
' ASSERT - We are asserting with the [ExpectedException(typeof(Exception))] test attribute.
End Sub
End Class
#Region "SUT"
Public Class Log
Public Overridable Function ReturnSum(firstInt As Integer, secondInt As Integer) As Integer
Return firstInt + secondInt
End Function
Public Overridable Sub Info(message As String)
Throw New Exception(message)
End Sub
End Class
#End Region
End Namespace

Просмотреть файл

@ -0,0 +1,124 @@
' JustMock Lite
' Copyright © 2010-2014 Telerik AD
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Namespace JustMock.NonElevatedExamples.BasicUsage.Mock_DoInstead
''' <summary>
''' The DoInstead method is used to replace the actual implementation of a method with a mocked one.
''' See http://www.telerik.com/help/justmock/basic-usage-mock-do-instead.html for full documentation of the feature.
''' </summary>
<TestClass> _
Public Class Mock_DoInstead_Tests
<TestMethod> _
Public Sub Execute_OnExecuteWithAnyStringArg_ShouldNotifyAndReturnThatArg()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
Dim called As Boolean = False
' Arranging: When foo.Execute() is called with any string as an argument it should change "called" to true and also return that argument.
Mock.Arrange(Function() foo.Execute(Arg.IsAny(Of String)())).DoInstead(Function()
called = True
End Function).Returns(Function(s As String) s)
' ACT
Dim actual = foo.Execute("bar")
' ASSERT
Assert.AreEqual("bar", actual)
Assert.IsTrue(called)
End Sub
<TestMethod> _
Public Sub Submit_OnExecuteWitAnyIntArgs_ShouldAssignTheirSumToVariable()
' Arrange
Dim expected As Integer = 0
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: When foo.Submit() is called with any integers as an arguments it should assign their sum to the "expected" variable.
Mock.Arrange(Function() foo.Submit(Arg.IsAny(Of Integer)(), Arg.IsAny(Of Integer)(), Arg.IsAny(Of Integer)(), Arg.IsAny(Of Integer)())).DoInstead(Function(arg1 As Integer, arg2 As Integer, arg3 As Integer, arg4 As Integer)
expected = arg1 + arg2 + arg3 + arg4
End Function)
' Act
foo.Submit(10, 10, 10, 10)
' Assert
Assert.AreEqual(40, expected)
End Sub
<TestMethod> _
Public Sub Bar_OnSetTo1_ShouldNotify()
' Arrange
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
Dim isSetTo1 As Boolean = False
' Arranging: When foo.Bar is set to 1 it should change "isSetTo1" to true.
Mock.ArrangeSet(Sub() foo.Bar = 1).DoInstead(Sub() isSetTo1 = True)
' Act
foo.Bar = 1
' Assert
Assert.IsTrue(isSetTo1)
End Sub
<TestMethod> _
Public Sub AddTo_OnCertainCall_ShouldSumTheArgsAndAssignInsidedTheRefArg()
' Arrange
Dim refArg As Integer = 1
' Creating a mocked instance of the "DoInsteadWithCustomDelegate" class.
Dim myMock = Mock.Create(Of DoInsteadWithCustomDelegate)()
' Arranging: When myMock.AddTo is called with 10 and "refArg" it should assign their sum to the second argument (refArg).
Mock.Arrange(Sub() myMock.AddTo(10, refArg)) _
.DoInstead(New RefAction(Of Integer, Integer)(Function(arg1 As Integer, ByRef arg2 As Integer)
arg2 += arg1
End Function))
' Act
myMock.AddTo(10, refArg)
' Assert
Assert.AreEqual(11, refArg)
End Sub
End Class
#Region "SUT"
Public Interface IFoo
Property Bar() As Integer
Function Execute(str As String) As String
Function Submit(arg1 As Integer, arg2 As Integer, arg3 As Integer, arg4 As Integer) As Integer
End Interface
Public Delegate Sub RefAction(Of T1, T2)(arg1 As T1, ByRef arg2 As T2)
Public Class DoInsteadWithCustomDelegate
Public Overridable Sub AddTo(arg1 As Integer, ByRef arg2 As Integer)
End Sub
End Class
#End Region
End Namespace

Просмотреть файл

@ -0,0 +1,67 @@
' limitations under the License.
' See the License for the specific language governing permissions and
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' distributed under the License is distributed on an "AS IS" BASIS,
' Unless required by applicable law or agreed to in writing, software
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' You may obtain a copy of the License at
' you may not use this file except in compliance with the License.
' Licensed under the Apache License, Version 2.0 (the "License");
'
' Copyright © 2010-2014 Telerik AD
' JustMock Lite
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Namespace JustMock.NonElevatedExamples.BasicUsage.Mock_DoNothing
''' <summary>
''' The DoNothing method is used to arrange that a call to a method or property should be ignored.
''' See http://www.telerik.com/help/justmock/basic-usage-mock-do-nothing.html for full documentation of the feature.
''' </summary>
<TestClass> _
Public Class Mock_DoNothing_Tests
<TestMethod> _
Public Sub VoidCall_OnExecute_ShouldDoNothingAndMustBeCalled()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: foo.VoidCall() should do nothing and it must be called during the test method.
Mock.Arrange(Sub() foo.VoidCall()).DoNothing().MustBeCalled()
' ACT
foo.VoidCall()
' ASSERT - Asserting all arrangements on "foo".
Mock.Assert(foo)
End Sub
<TestMethod> _
Public Sub Bar_OnSetWithArgument1_ShouldDoNothingAndMustBeCalled()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: foo.Bar should do nothing when set to 1, but must be called.
Mock.ArrangeSet(Sub() foo.Bar = 1).DoNothing().MustBeCalled()
' ACT
foo.Bar = 1
' ASSERT - Asserting all arrangements on "foo".
Mock.Assert(foo)
End Sub
End Class
#Region "SUT"
Public Interface IFoo
Property Bar() As Integer
Sub VoidCall()
End Interface
#End Region
End Namespace

Просмотреть файл

@ -0,0 +1,86 @@
' JustMock Lite
' Copyright © 2010-2014 Telerik AD
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Namespace JustMock.NonElevatedExamples.BasicUsage.Mock_MustBeCalled
''' <summary>
''' <FEATURE HELP>
''' The MustBeCalled method is used to assert that a call to a given method or property is made during the execution of a test.
''' See http://www.telerik.com/help/justmock/basic-usage-mock-must-be-called.html for full documentation of the feature.
''' </summary>
<TestClass> _
Public Class Mock_MustBeCalled_Tests
<TestMethod> _
Public Sub Value_OnSetTo1_ShouldBeCalled()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: foo.Value should be set to 1 during the test.
Mock.ArrangeSet(Sub() foo.Value = 1).MustBeCalled()
' ACT
foo.Value = 1
' ASSERT - Asserting all arrangements on "foo".
Mock.Assert(foo)
End Sub
<TestMethod> _
<ExpectedException(GetType(AssertFailedException))> _
Public Sub Value_NotSet_ShouldNotBeCalled()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: foo.Value should be set to 1 during the test.
Mock.ArrangeSet(Sub() foo.Value = 1).MustBeCalled()
' ACT
' ASSERT - Asserting all arrangements on "foo".
Mock.Assert(foo)
End Sub
<TestMethod> _
Public Sub Execute_OnArrangedExecuteTestCall_ShouldBeCalled()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: foo.Test() should be called during the test.
Mock.Arrange(Sub() foo.Test()).MustBeCalled()
' Arranging: When foo.ExecuteTest() is called, it should call foo.Test() instead.
Mock.Arrange(Sub() foo.ExecuteTest()).DoInstead(Sub() foo.Test())
' ACT
foo.ExecuteTest()
' ASSERT - Asserting all arrangements on "foo".
Mock.Assert(foo)
End Sub
End Class
#Region "SUT"
Public Interface IFoo
Property Value() As Integer
Sub ExecuteTest()
Sub Test()
End Interface
#End Region
End Namespace

Просмотреть файл

@ -0,0 +1,126 @@
' limitations under the License.
' See the License for the specific language governing permissions and
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' distributed under the License is distributed on an "AS IS" BASIS,
' Unless required by applicable law or agreed to in writing, software
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' You may obtain a copy of the License at
' you may not use this file except in compliance with the License.
' Licensed under the Apache License, Version 2.0 (the "License");
'
' Copyright © 2010-2014 Telerik AD
' JustMock Lite
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Namespace JustMock.NonElevatedExamples.BasicUsage.Mock_Raise
''' <summary>
''' The Raise method is used for raising mocked events. You can use custom or standard events.
''' See http://www.telerik.com/help/justmock/basic-usage-mock-raise.html for full documentation of the feature.
''' </summary>
<TestClass> _
Public Class Mock_Raise_Tests
<TestMethod> _
Public Sub ShouldInvokeMethodForACustomEventWhenRaised()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
Dim expected As String = "ping"
Dim actual As String = String.Empty
AddHandler foo.CustomEvent, Sub(exp As String) actual = exp
' ACT
Mock.Raise(Sub() AddHandler foo.CustomEvent, Nothing, expected)
' ASSERT
Assert.AreEqual(expected, actual)
End Sub
<TestMethod> _
Public Sub ShouldRaiseEventWithStandardEventArgs()
' ARRANGE
' Creating a mocked instance of the "IExecutor" interface.
Dim executor = Mock.Create(Of IExecutor(Of Integer))()
Dim acutal As String = Nothing
Dim expected As String = "ping"
AddHandler executor.Done, Sub(sender As Object, args As FooArgs) acutal = args.Value
' ACT - Raising the event with the expected args.
Mock.Raise(Sub() AddHandler executor.Done, Nothing, New FooArgs(expected))
' ASSERT
Assert.AreEqual(expected, acutal)
End Sub
<TestMethod> _
Public Sub Submit_OnIsChangedRaised_ShouldBeCalled()
' ARRANGE
' Creating the necessary mocked instances.
Dim activeDocument = Mock.Create(Of IDocument)()
Dim activeView = Mock.Create(Of IDocumentView)()
' Attaching the Submit method to the IsChanged event.
AddHandler activeDocument.IsChanged, New EventHandler(AddressOf activeDocument.Submit)
' Arranging: activeDocument.Submit should be called during the test method with any arguments.
Mock.Arrange(Sub() activeDocument.Submit(Arg.IsAny(Of Object)(), Arg.IsAny(Of EventArgs)())).MustBeCalled()
' Arranging: activeView.Document should return activeDocument when called.
Mock.Arrange(Function() activeView.Document).Returns(activeDocument)
' ACT
Mock.Raise(Sub() AddHandler activeView.Document.IsChanged, Nothing, EventArgs.Empty)
' ASSERT - Asserting all arrangements on "foo".
Mock.Assert(activeDocument)
End Sub
End Class
#Region "SUT"
Public Interface IFoo
Event CustomEvent As CustomEvent
End Interface
Public Delegate Sub CustomEvent(value As String)
Public Interface IExecutor(Of T)
Event Done As EventHandler(Of FooArgs)
End Interface
Public Class FooArgs
Inherits EventArgs
Public Sub New()
End Sub
Public Sub New(value As String)
Me.Value = value
End Sub
Public Property Value() As String
Get
Return m_Value
End Get
Set(value As String)
m_Value = Value
End Set
End Property
Private m_Value As String
End Class
Public Interface IDocumentView
ReadOnly Property Document() As IDocument
End Interface
Public Interface IDocument
Event IsChanged As EventHandler
Sub Submit(sender As Object, e As EventArgs)
End Interface
#End Region
End Namespace

Просмотреть файл

@ -0,0 +1,113 @@
' JustMock Lite
' Copyright © 2010-2014 Telerik AD
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Namespace JustMock.NonElevatedExamples.BasicUsage.Mock_Raises
''' <summary>
''' The Raises method is used to fire an event once a method is called.
''' See http://www.telerik.com/help/justmock/basic-usage-mock-raises.html for full documentation of the feature.
''' </summary>
<TestClass> _
Public Class Mock_Raises_Tests
<TestMethod> _
Public Sub ShouldRaiseCustomEventOnMethodCall()
Dim expected = "ping"
Dim actual As String = String.Empty
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: When foo.RaiseMethod() is called, it should raise foo.CustomEvent with expected args.
Mock.Arrange(Sub() foo.RaiseMethod()).Raises(Sub() AddHandler foo.CustomEvent, Nothing, expected)
AddHandler foo.CustomEvent, Function(s)
actual = s
End Function
' ACT
foo.RaiseMethod()
' ASSERT
Assert.AreEqual(expected, actual)
End Sub
<TestMethod> _
Public Sub ShouldRaiseCustomEventForFuncCalls()
Dim isRaised As Boolean = False
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: When foo.Echo() is called with expected arguments, it should raise foo.EchoEvent with arg: true.
Mock.Arrange(Function() foo.Echo("string")).Raises(Sub() AddHandler foo.EchoEvent, Nothing, True)
AddHandler foo.EchoEvent, Function(c)
isRaised = c
End Function
' ACT
Dim actual = foo.Echo("string")
' ASSERT
Assert.IsTrue(isRaised)
End Sub
<TestMethod> _
Public Sub ShouldAssertMultipleEventSubscription()
Dim isRaisedForFirstSubscr As Boolean = False
Dim isRaisedForSecondSubscr As Boolean = False
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: When foo.Execute() is called, it should raise foo.EchoEvent with arg: true.
Mock.Arrange(Sub() foo.Execute()).Raises(Sub() AddHandler foo.EchoEvent, Nothing, True)
' Subscribing for the event
AddHandler foo.EchoEvent, Function(c)
isRaisedForFirstSubscr = c
End Function
AddHandler foo.EchoEvent, Function(c)
isRaisedForSecondSubscr = c
End Function
' ACT
foo.Execute()
' ASSERT
Assert.IsTrue(isRaisedForFirstSubscr)
Assert.IsTrue(isRaisedForSecondSubscr)
End Sub
End Class
#Region "SUT"
Public Delegate Sub CustomEvent(value As String)
Public Delegate Sub EchoEvent(echoed As Boolean)
Public Interface IFoo
Event CustomEvent As CustomEvent
Event EchoEvent As EchoEvent
Sub RaiseMethod()
Function Echo(arg As String) As String
Sub Execute()
End Interface
#End Region
End Namespace

Просмотреть файл

@ -0,0 +1,126 @@
' limitations under the License.
' See the License for the specific language governing permissions and
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' distributed under the License is distributed on an "AS IS" BASIS,
' Unless required by applicable law or agreed to in writing, software
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' You may obtain a copy of the License at
' you may not use this file except in compliance with the License.
' Licensed under the Apache License, Version 2.0 (the "License");
'
' Copyright © 2010-2014 Telerik AD
' JustMock Lite
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Imports Telerik.JustMock.Helpers
Namespace JustMock.NonElevatedExamples.BasicUsage.Mock_Returns
''' <summary>
''' The Returns method is used with non void calls to ignore the actual call and return a custom value.
''' See http://www.telerik.com/help/justmock/basic-usage-mock-returns.html for full documentation of the feature.
''' </summary>
<TestClass> _
Public Class Mock_Returns_Tests
<TestMethod> _
Public Sub ShouldAssertPropertyGetCall()
Dim expected = 10
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: When foo.Bar is called, it should return the expected value.
Mock.Arrange(Function() foo.Bar).Returns(expected)
' ACT
Dim actual = foo.Bar
' ASSERT
Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(expected, actual)
End Sub
<TestMethod> _
Public Sub ShouldAssertMethodCallWithMatcher1()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: When foo.Echo() is called with any integer as an argument, it should return 1 + that argument.
Mock.Arrange(Function() foo.Echo(Arg.IsAny(Of Integer)())).Returns(Function(i As Integer) System.Threading.Interlocked.Increment(i))
' ACT
Dim actual = foo.Echo(10)
' ASSERT
Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(11, actual)
End Sub
<TestMethod> _
Public Sub ShouldAssertMethodCallWithMatcher2()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: When foo.Echo() is called with an integer argument exactly matching 10,
' it should return that argument.
Mock.Arrange(Function() foo.Echo(Arg.Matches(Of Integer)(Function(x) x = 10))).Returns(Function(i As Integer) i)
' ACT
Dim actual = foo.Echo(10)
' ASSERT
Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(10, actual)
End Sub
<TestMethod> _
Public Sub ShouldReturnWhateverSecondArgIs()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: When foo.Execute() is called with any integer arguments, it should return the second argument.
Mock.Arrange(Function() foo.Execute(Arg.IsAny(Of Integer)(), Arg.IsAny(Of Integer)())).Returns(Function(id As Integer, i As Integer) i)
' ACT
Dim actual = foo.Execute(100, 10)
' ASSERT
Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(actual, 10)
End Sub
<TestMethod> _
Public Sub ShouldReturnInSequence()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
Dim values As Integer() = New Integer(2) {1, 2, 3}
' Arranging: When foo.Bar_GET is called number of times, it should return the array values in sequence.
Mock.Arrange(Function() foo.Bar).ReturnsMany(values)
' ACT
Dim first = foo.Bar
Dim second = foo.Bar
Dim third = foo.Bar
' ASSERT
Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(first, 1)
Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(second, 2)
Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(third, 3)
End Sub
End Class
#Region "SUT"
Public Interface IFoo
Property Bar() As Integer
Function Echo(myInt As Integer) As Integer
Function Execute(myInt1 As Integer, myInt2 As Integer) As Integer
End Interface
#End Region
End Namespace

Просмотреть файл

@ -0,0 +1,62 @@
' JustMock Lite
' Copyright © 2010-2014 Telerik AD
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Namespace JustMock.NonElevatedExamples.BasicUsage.Mock_Throws
''' <summary>
''' The Throws method is used to throw an exception when a given call is made.
''' See http://www.telerik.com/help/justmock/basic-usage-mock-throws.html for full documentation of the feature.
''' </summary>
<TestClass> _
Public Class Mock_Throws_Tests
<TestMethod> _
<ExpectedException(GetType(ArgumentException))> _
Public Sub ShouldThrowExceptionOnMethodCall()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: When foo.Execute() is called with any string as an argument, it should throw an ArgumentException.
Mock.Arrange(Function() foo.Execute(Arg.AnyString)).Throws(Of ArgumentException)()
' ACT
foo.Execute(String.Empty)
End Sub
<TestMethod> _
<ExpectedException(GetType(ArgumentException))> _
Public Sub ShouldThrowExceptionWithArgumentsOnMethodCall()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: When foo.Execute() is called with an empty string as an argument,
' it should throw an ArgumentException with args: "Argument shouldn't be empty.".
Mock.Arrange(Function() foo.Execute(String.Empty)).Throws(Of ArgumentException)("Argument shouldn't be empty.")
' ACT
foo.Execute(String.Empty)
End Sub
End Class
#Region "SUT"
Public Interface IFoo
Function Execute(myStr As String) As String
End Interface
#End Region
End Namespace

Просмотреть файл

@ -0,0 +1,147 @@
' limitations under the License.
' See the License for the specific language governing permissions and
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' distributed under the License is distributed on an "AS IS" BASIS,
' Unless required by applicable law or agreed to in writing, software
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' You may obtain a copy of the License at
' you may not use this file except in compliance with the License.
' Licensed under the Apache License, Version 2.0 (the "License");
'
' Copyright © 2010-2014 Telerik AD
' JustMock Lite
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Namespace JustMock.NonElevatedExamples.BasicUsage.MockingProperties
''' <summary>
''' Mocking properties is similar to mocking methods, but there are a few cases that need special attention
''' like mocking indexers and particular set operations.
''' See http://www.telerik.com/help/justmock/basic-usage-mock-properties.html for full documentation of the feature.
''' </summary>
<TestClass> _
Public Class MockingProperties_Tests
<TestMethod> _
Public Sub ShouldFakePropertyGet()
Dim expectedValue = 25
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: When foo.Value_GET is called, it should return expectedValue.
Mock.Arrange(Function() foo.Value).Returns(expectedValue)
' ACT
Dim actual = foo.Value
' ASSERT
Assert.AreEqual(expectedValue, actual)
End Sub
<TestMethod> _
Public Sub ShouldAssertPropertySet()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: That foo.Value must be set to 1 during the test method.
Mock.ArrangeSet(Sub() foo.Value = 1).MustBeCalled()
' ACT
foo.Value = 1
' ASSERT - Asserting the expected foo.Value_SET.
Mock.AssertSet(Sub() foo.Value = 1)
End Sub
<TestMethod> _
<ExpectedException(GetType(StrictMockException))> _
Public Sub ShouldThrowExceptionOnTheThirdPropertySetCall()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface with Behavior.Strict.
Dim foo = Mock.Create(Of IFoo)(Behavior.[Strict])
' Arranging: That foo.Value should be set to an integer bigger than 3.
Mock.ArrangeSet(Sub() foo.Value = Arg.Matches(Of Integer)(Function(x) x > 3))
' ACT - These lines will not trigger the Strict behavior, because they satisfy the expectations.
foo.Value = 4
foo.Value = 5
' This throws MockException because matching criteria is not met.
foo.Value = 3
End Sub
<TestMethod> _
Public Sub MockIndexers()
' ARRANGE
' Creating a mocked instance of the "IIndexedFoo" interface.
Dim indexedFoo = Mock.Create(Of IIndexedFoo)()
' Arranging: That the [0] element of indexedFoo should return "ping".
Mock.Arrange(Function() indexedFoo(0)).Returns("ping")
' Arranging: That the [1] element of indexedFoo should return "pong".
Mock.Arrange(Function() indexedFoo(1)).Returns("pong")
' ACT
Dim actualFirst As String = indexedFoo(0)
Dim actualSecond As String = indexedFoo(1)
' ASSERT
Assert.AreEqual("ping", actualFirst)
Assert.AreEqual("pong", actualSecond)
End Sub
<TestMethod> _
<ExpectedException(GetType(StrictMockException))> _
Public Sub ShouldThrowExceptionForNotArrangedPropertySet()
' ARRANGE
' Creating a mocked instance of the "IIndexedFoo" interface with Behavior.Strict.
Dim foo = Mock.Create(Of IIndexedFoo)(Behavior.[Strict])
' Arranging: That the [0] element of foo should be set to "foo".
Mock.ArrangeSet(Sub() foo(0) = "foo")
' ACT - This meets the expectations.
foo(0) = "foo"
' This throws MockException because matching criteria is not met.
foo(0) = "bar"
End Sub
<TestMethod> _
<ExpectedException(GetType(StrictMockException))> _
Public Sub ShouldAssertIndexedSetWithMatcher()
' ARRANGE
' Creating a mocked instance of the "IIndexedFoo" interface with Behavior.Strict.
Dim foo = Mock.Create(Of IIndexedFoo)(Behavior.[Strict])
' Arranging: That the [0] element of foo should match a string "ping".
Mock.ArrangeSet(Sub() foo(0) = Arg.Matches(Of String)(Function(x) x.Equals("ping")))
' Arranging: That the [1] element of foo should be any string.
Mock.ArrangeSet(Sub() foo(1) = Arg.IsAny(Of String)())
' ACT - These lines will not trigger the Strict behavior, because they satisfy the expectations.
foo(0) = "ping"
foo(1) = "pong"
' This line does not satisfy the matching criteria and throws a MockException.
foo(0) = "bar"
End Sub
End Class
#Region "SUT"
Public Interface IIndexedFoo
Default Property Item(key As Integer) As String
End Interface
Public Interface IFoo
Property Value() As Integer
End Interface
#End Region
End Namespace

Просмотреть файл

@ -0,0 +1,135 @@
' JustMock Lite
' Copyright © 2010-2014 Telerik AD
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Namespace JustMock.NonElevatedExamples.BasicUsage.RecursiveMocking
''' <summary>
''' Recursive mocks enable you to mock members that are obtained as a result of "chained" calls on a mock.
''' For example, recursive mocking is useful in the cases when you test code like this: foo.Bar.Baz.Do("x").
''' See http://www.telerik.com/help/justmock/basic-usage-recursive-mocking.html for full documentation of the feature.
''' </summary>
<TestClass> _
Public Class RecursiveMocking_Tests
<TestMethod> _
Public Sub ShouldAssertNestedVeriables()
Dim pingArg As String = "ping"
Dim expected = "test"
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: When foo.Bar.Do() is called, it should return the expected string.
' This will automatically create mock of foo.Bar and a NullReferenceException will be avoided.
Mock.Arrange(Function() foo.Bar.[Do](pingArg)).Returns(expected)
' ACT
Dim actualFooBarDo = foo.Bar.[Do](pingArg)
' ASSERT
Assert.AreEqual(expected, actualFooBarDo)
End Sub
<TestMethod> _
Public Sub ShouldNotInstantiateFooBar()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' ASSERT - Not arranged members in a RecursiveLoose mocks should not be null.
Assert.IsNotNull(foo.Bar)
End Sub
<TestMethod> _
Public Sub ShouldAssertNestedPropertyGet()
Dim expected = 10
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: When foo.Bar.Value is called, it should return expected value.
' This will automatically create mock of foo.Bar and a NullReferenceException will be avoided.
Mock.Arrange(Function() foo.Bar.Value).Returns(expected)
' ACT
Dim actual = foo.Bar.Value
' ASSERT
Assert.AreEqual(expected, actual)
End Sub
<TestMethod> _
Public Sub ShouldAssertNestedPropertySet()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: Setting foo.Bar.Value to 5, should do nothing.
' This will automatically create mock of foo.Bar and a NullReferenceException will be avoided.
Mock.ArrangeSet(Sub() foo.Bar.Value = 5).DoNothing().MustBeCalled()
' ACT
foo.Bar.Value = 5
' ASSERT
Mock.Assert(foo)
End Sub
<TestMethod> _
Public Sub NestedPropertyAndMethodCalls()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: When foo.Bar.Do() is called with "x" as an argument, it return "xit".
' This will automatically create mock of foo.Bar and a NullReferenceException will be avoided.
Mock.Arrange(Function() foo.Bar.[Do]("x")).Returns("xit")
' Arranging: When foo.Bar.Baz.Do() is called with "y" as an argument, it return "yit".
' This will automatically create mock of foo.Bar and foo.Bar.Baz and a
' NullReferenceException will be avoided.
Mock.Arrange(Function() foo.Bar.Baz.[Do]("y")).Returns("yit")
' ACT
Dim actualFooBarDo = foo.Bar.[Do]("x")
Dim actualFooBarBazDo = foo.Bar.Baz.[Do]("y")
' ASSERT
Assert.AreEqual("xit", actualFooBarDo)
Assert.AreEqual("yit", actualFooBarBazDo)
End Sub
End Class
#Region "SUT"
Public Interface IFoo
Property Bar() As IBar
Function [Do](command As String) As String
End Interface
Public Interface IBar
Property Value() As Integer
Function [Do](command As String) As String
Property Baz() As IBaz
End Interface
Public Interface IBaz
Function [Do](command As String) As String
End Interface
#End Region
End Namespace

Просмотреть файл

@ -0,0 +1,123 @@
' limitations under the License.
' See the License for the specific language governing permissions and
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' distributed under the License is distributed on an "AS IS" BASIS,
' Unless required by applicable law or agreed to in writing, software
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' You may obtain a copy of the License at
' you may not use this file except in compliance with the License.
' Licensed under the Apache License, Version 2.0 (the "License");
'
' Copyright © 2010-2014 Telerik AD
' JustMock Lite
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Imports Telerik.JustMock.Helpers
Namespace JustMock.NonElevatedExamples.BasicUsage.SequentialMocking
''' <summary>
''' Sequential mocking allows you to return different values on the same or different consecutive calls to
''' one and the same type. In other words, you can set up expectations for successive calls of the same type.
''' See http://www.telerik.com/help/justmock/basic-usage-sequential-mocking.html for full documentation of the feature.
''' </summary>
<TestClass> _
Public Class SequentialMocking_Tests
<TestMethod> _
Public Sub ShouldArrangeAndAssertInASequence()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: Sequence calls to foo.GetIntValue() should return different values.
Mock.Arrange(Function() foo.GetIntValue()).Returns(0).InSequence()
Mock.Arrange(Function() foo.GetIntValue()).Returns(1).InSequence()
Mock.Arrange(Function() foo.GetIntValue()).Returns(2).InSequence()
' ACT
Dim actualFirstCall As Integer = foo.GetIntValue()
Dim actualSecondCall As Integer = foo.GetIntValue()
Dim actualThirdCall As Integer = foo.GetIntValue()
' ASSERT
Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0, actualFirstCall)
Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(1, actualSecondCall)
Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(2, actualThirdCall)
End Sub
<TestMethod> _
Public Sub ShouldAssertSequentlyWithAMatchers()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim iFoo = Mock.Create(Of IFoo)()
' Arranging:
' When iFoo.Execute() is called with "foo" as an argument, it should return "hello".
' Next iFoo.Execute() calls with any string as an argument should return "bye".
Mock.Arrange(Function() iFoo.Execute("foo")).Returns("hello").InSequence()
Mock.Arrange(Function() iFoo.Execute(Arg.IsAny(Of String)())).Returns("bye").InSequence()
' ACT
Dim actualFirstCall As String = iFoo.Execute("foo")
Dim actualSecondCall As String = iFoo.Execute("bar")
' This will also return "bye" as this is the last arrange in the sequence.
Dim actualThirdCall As String = iFoo.Execute("foobar")
' ASSERT
Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual("hello", actualFirstCall)
Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual("bye", actualSecondCall)
Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual("bye", actualThirdCall)
End Sub
<TestMethod> _
Public Sub ShouldAssertMultipleCallsWithDifferentMatchers()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: First call to foo.Echo() with any integer bigger than 10 as an argument should return 10,
' every next call to foo.Echo() with any integer bigger than 20 as an argument should return 20.
Mock.Arrange(Function() foo.Echo(Arg.Matches(Of Integer)(Function(x) x > 10))).Returns(10).InSequence()
Mock.Arrange(Function() foo.Echo(Arg.Matches(Of Integer)(Function(x) x > 20))).Returns(20).InSequence()
' ACT
Dim actualFirstCall As Integer = foo.Echo(11)
Dim actualSecondCall As Integer = foo.Echo(21)
' ASSERT
Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(10, actualFirstCall)
Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(20, actualSecondCall)
End Sub
<TestMethod> _
Public Sub ShouldArrangeInSequencedReturns()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface.
Dim foo = Mock.Create(Of IFoo)()
' Arranging: First call to foo.Echo() with any integer as an argument should return 10,
' every next call to foo.Echo() (using the same matcher) should return 11.
Mock.Arrange(Function() foo.Echo(Arg.AnyInt)).Returns(10).Returns(11)
' ACT
Dim ctualFirstCall = foo.Echo(1)
Dim actualSecondCall = foo.Echo(2)
' ASSERT
Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(10, ctualFirstCall)
Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(11, actualSecondCall)
End Sub
End Class
#Region "SUT"
Public Interface IFoo
Function Execute(arg As String) As String
Function Echo(arg1 As Integer) As Integer
Function GetIntValue() As Integer
End Interface
#End Region
End Namespace

Просмотреть файл

@ -0,0 +1,59 @@
' JustMock Lite
' Copyright © 2010-2014 Telerik AD
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.
Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Namespace JustMock.NonElevatedExamples.BasicUsage.StrictMocking
''' <summary>
''' You may have a case where you want to enable only arranged calls and to reject others.
''' In such cases you need to set the mock Behavior to Strict.
''' See http://www.telerik.com/help/justmock/basic-usage-strict-mocking.html for full documentation of the feature.
''' </summary>
<TestClass> _
Public Class StrictMocking_Tests
<ExpectedException(GetType(StrictMockException))> _
<TestMethod> _
Public Sub ArbitraryCallsShouldGenerateException()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface with Behavior.Strict.
' This means, every non-arranged call from this instance will throw MockException.
Dim foo = Mock.Create(Of IFoo)(Behavior.Strict)
'ACT - As foo.VoidCall() is not arranged, it should throw an exception.
foo.VoidCall()
End Sub
<TestMethod> _
<ExpectedException(GetType(StrictMockException))> _
Public Sub ArbitraryCallsShouldGenerateExpectedException()
' ARRANGE
' Creating a mocked instance of the "IFoo" interface with Behavior.Strict.
' This means, every non-arranged call from this instance will throw MockException.
Dim foo = Mock.Create(Of IFoo)(Behavior.Strict)
'ACT - As foo.VoidCall() is not arranged, it should throw an exception.
foo.GetGuid()
End Sub
End Class
#Region "SUT"
Public Interface IFoo
Sub VoidCall()
Function GetGuid() As Guid
End Interface
#End Region
End Namespace

Просмотреть файл

@ -0,0 +1,121 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>
</ProductVersion>
<SchemaVersion>
</SchemaVersion>
<ProjectGuid>{969B7E82-7FF1-4C0C-8668-8332A0A2FD3D}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>JustMock.NonElevatedExamples</RootNamespace>
<AssemblyName>JustMock.NonElevatedExamples</AssemblyName>
<FileAlignment>512</FileAlignment>
<MyType>Windows</MyType>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{F184B08F-C81C-45F6-A57F-5ABD9991F28F}</ProjectTypeGuids>
<ReferencePath>$(DevEnvDir)PublicAssemblies\</ReferencePath>
<SccProjectName>SAK</SccProjectName>
<SccLocalPath>SAK</SccLocalPath>
<SccAuxPath>SAK</SccAuxPath>
<SccProvider>SAK</SccProvider>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<DefineDebug>true</DefineDebug>
<DefineTrace>true</DefineTrace>
<OutputPath>bin\Debug\</OutputPath>
<DocumentationFile>JustMock.NonElevatedExamples.xml</DocumentationFile>
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<DefineDebug>false</DefineDebug>
<DefineTrace>true</DefineTrace>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DocumentationFile>JustMock.NonElevatedExamples.xml</DocumentationFile>
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
</PropertyGroup>
<PropertyGroup>
<OptionExplicit>On</OptionExplicit>
</PropertyGroup>
<PropertyGroup>
<OptionCompare>Binary</OptionCompare>
</PropertyGroup>
<PropertyGroup>
<OptionStrict>Off</OptionStrict>
</PropertyGroup>
<PropertyGroup>
<OptionInfer>On</OptionInfer>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq" />
<Reference Include="Telerik.JustMock, Version=2013.3.819.0, Culture=neutral, PublicKeyToken=721b6c5bc0326b3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\..\..\Program Files (x86)\Telerik\JustMock\Libraries\Telerik.JustMock.dll</HintPath>
</Reference>
<Reference Include="Telerik.JustMock.Container, Version=2013.3.819.0, Culture=neutral, PublicKeyToken=721b6c5bc0326b3a, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\..\..\Program Files (x86)\Telerik\JustMock\Libraries\Telerik.JustMock.Container.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Import Include="System" />
<Import Include="System.Collections" />
<Import Include="System.Collections.Generic" />
<Import Include="System.Data" />
<Import Include="System.Diagnostics" />
<Import Include="System.Linq" />
<Import Include="System.Xml.Linq" />
<Import Include="Microsoft.VisualBasic" />
<Import Include="Microsoft.VisualStudio.TestTools.UnitTesting" />
<Import Include="Telerik.JustMock" />
</ItemGroup>
<ItemGroup>
<CodeAnalysisDependentAssemblyPaths Condition=" '$(VS100COMNTOOLS)' != '' " Include="$(VS100COMNTOOLS)..\IDE\PrivateAssemblies">
<Visible>False</Visible>
</CodeAnalysisDependentAssemblyPaths>
</ItemGroup>
<ItemGroup>
<Compile Include="AdvancedUsage\ConcreteMocking.vb" />
<Compile Include="AdvancedUsage\MockingDelegates.vb" />
<Compile Include="AdvancedUsage\PrivateAccessor.vb" />
<Compile Include="BasicUsage\AssertingOccurrences.vb" />
<Compile Include="BasicUsage\Automocking.vb" />
<Compile Include="BasicUsage\CreateMocksByExample.vb" />
<Compile Include="BasicUsage\FluentMocking.vb" />
<Compile Include="BasicUsage\Generics.vb" />
<Compile Include="BasicUsage\Matchers.vb" />
<Compile Include="BasicUsage\Mock.CallOriginal.vb" />
<Compile Include="BasicUsage\Mock.DoInstead.vb" />
<Compile Include="BasicUsage\Mock.DoNothing.vb" />
<Compile Include="BasicUsage\Mock.MustBeCalled.vb" />
<Compile Include="BasicUsage\Mock.Raise.vb" />
<Compile Include="BasicUsage\Mock.Raises.vb" />
<Compile Include="BasicUsage\Mock.Returns.vb" />
<Compile Include="BasicUsage\Mock.Throws.vb" />
<Compile Include="BasicUsage\MockingProperties.vb" />
<Compile Include="BasicUsage\RecursiveMocking.vb" />
<Compile Include="BasicUsage\SequentialMocking.vb" />
<Compile Include="BasicUsage\StrictMocking.vb" />
<Compile Include="My Project\AssemblyInfo.vb" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildBinPath)\Microsoft.VisualBasic.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Просмотреть файл

@ -0,0 +1,52 @@
' JustMock Lite
' Copyright © 2010-2014 Telerik AD
'
' Licensed under the Apache License, Version 2.0 (the "License");
' you may not use this file except in compliance with the License.
' You may obtain a copy of the License at
'
' http://www.apache.org/licenses/LICENSE-2.0
'
' Unless required by applicable law or agreed to in writing, software
' distributed under the License is distributed on an "AS IS" BASIS,
' WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' See the License for the specific language governing permissions and
' limitations under the License.
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("JustMock.NonElevatedExamples")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("JustMock.NonElevatedExamples")>
<Assembly: AssemblyCopyright("Copyright © 2013")>
<Assembly: AssemblyTrademark("")>
<Assembly: CLSCompliant(True)>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("fdbd0f9a-1e75-446e-8cef-d85a02a5faee")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>

Просмотреть файл

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<TestSettings name="Local" id="dc2d353f-3253-4f7a-bd43-27d144209779" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010">
<Description>These are default test settings for a local test run.</Description>
<Deployment enabled="false" />
<Execution>
<TestTypeSpecific />
<AgentRule name="Execution Agents">
</AgentRule>
</Execution>
</TestSettings>

Просмотреть файл

@ -0,0 +1,34 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "JustMock.NonElevatedExamples", "JustMock.NonElevatedExamples\JustMock.NonElevatedExamples.vbproj", "{969B7E82-7FF1-4C0C-8668-8332A0A2FD3D}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{8D16F8FC-190C-4DD0-9157-3B9E0C3CD4C2}"
ProjectSection(SolutionItems) = preProject
Local.testsettings = Local.testsettings
EndProjectSection
EndProject
Global
GlobalSection(TeamFoundationVersionControl) = preSolution
SccNumberOfProjects = 2
SccEnterpriseProvider = {4CA58AB2-18FA-4F8D-95D4-32DDF27D184C}
SccTeamFoundationServer = http://tfs:8082/defaultcollection
SccProjectUniqueName0 = JustMock.NonElevatedExamples\\JustMock.NonElevatedExamples.vbproj
SccProjectName0 = JustMock.NonElevatedExamples
SccLocalPath0 = JustMock.NonElevatedExamples
SccLocalPath1 = .
EndGlobalSection
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{969B7E82-7FF1-4C0C-8668-8332A0A2FD3D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{969B7E82-7FF1-4C0C-8668-8332A0A2FD3D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{969B7E82-7FF1-4C0C-8668-8332A0A2FD3D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{969B7E82-7FF1-4C0C-8668-8332A0A2FD3D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

202
LICENSE Normal file
Просмотреть файл

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Двоичные данные
Lib/EQATEC/AnalyticsMonitor.chm Normal file

Двоичный файл не отображается.

Двоичные данные
Lib/EQATEC/EQATEC.Analytics.Monitor.dll Normal file

Двоичный файл не отображается.

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Двоичные данные
Lib/EQATEC/EQATEC.Analytics.MonitorSL.dll Normal file

Двоичный файл не отображается.

Разница между файлами не показана из-за своего большого размера Загрузить разницу

24
Lib/EQATEC/License.txt Normal file
Просмотреть файл

@ -0,0 +1,24 @@
* Copyright (c) 2008-2012, EQATEC A/S - Copenhagen - Denmark - www.eqatec.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the company EQATEC nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY EQATEC "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL EQATEC BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

1
README.md Normal file
Просмотреть файл

@ -0,0 +1 @@
Write Me!

Двоичные данные
Solution Items/JustMockLite - Shortcut.lnk Normal file

Двоичный файл не отображается.

Двоичные данные
Solution Items/snkey_lite.snk Normal file

Двоичный файл не отображается.

Просмотреть файл

@ -0,0 +1,44 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
namespace Telerik.JustMock.Container.Abstraction
{
/// <summary>
/// Provides an abstraction between service locator and IOC container.
/// </summary>
public interface IContainer
{
/// <summary>
/// Registers the specified instance for its corresponding type.
/// </summary>
void Register(Type @interface, object instance);
/// <summary>
/// Resolves the target instance with dependencies.
/// </summary>
object Resolve(Type targetType);
/// <summary>
/// Resolves all registered instances for a specific service type.
/// </summary>
IList<object> ResolveAll(Type serviceType);
}
}

Просмотреть файл

@ -0,0 +1,39 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Telerik.JustMock.Container
{
/// <summary>
/// The exception thrown by the mocking container.
/// </summary>
public sealed class AutoMockException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="AutoMockException" /> class.
/// </summary>
/// <param name="message">The message of the exception.</param>
public AutoMockException(string message) : base(message)
{
// intentionally left blank
}
}
}

Просмотреть файл

@ -0,0 +1,76 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.ServiceLocation;
using Telerik.JustMock.Container.Abstraction;
namespace Telerik.JustMock.Container
{
/// <summary>
/// JustMockServiceLocator class.
/// </summary>
public sealed class JustMockServiceLocator : ServiceLocatorImplBase
{
/// <summary>
/// Initializes a new instance of the <see cref="JustMockServiceLocator"/> class.
/// </summary>
internal JustMockServiceLocator(IContainer container)
{
this.container = container;
}
/// <summary>
/// Gets the container associated with this locator.
/// </summary>
internal IContainer Container
{
get
{
return container;
}
}
/// <summary>
/// Gets all the instances for a target type.
/// </summary>
protected override IEnumerable<object> DoGetAllInstances(Type serviceType)
{
if (serviceType != null)
{
return container.ResolveAll(serviceType);
}
return null;
}
/// <summary>
/// Gets the specific instance for target type.
/// </summary>
protected override object DoGetInstance(Type serviceType, string key)
{
if (serviceType != null)
{
return container.Resolve(serviceType);
}
return null;
}
private readonly IContainer container;
}
}

89
Telerik.JustMock.Container/Messages.Designer.cs сгенерированный Normal file
Просмотреть файл

@ -0,0 +1,89 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18010
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Telerik.JustMock.Container {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Messages {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Messages() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Telerik.JustMock.Container.Messages", typeof(Messages).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Profiler must enabled to auto mock concrete dependencies.
/// </summary>
internal static string ProfilerMustBeEnabled {
get {
return ResourceManager.GetString("ProfilerMustBeEnabled", resourceCulture);
}
}
}
}

Просмотреть файл

@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="ProfilerMustBeEnabled" xml:space="preserve">
<value>Profiler must enabled to auto mock concrete dependencies</value>
</data>
</root>

Просмотреть файл

@ -0,0 +1,324 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Linq;
using Microsoft.Practices.ServiceLocation;
using Telerik.JustMock.Container.Abstraction;
using Telerik.JustMock.Helpers;
using Telerik.JustMock.Expectations;
using System.Linq.Expressions;
using System.Collections;
using System.Collections.Generic;
namespace Telerik.JustMock.Container
{
/// <summary>
/// Entry-point class for auto mocking.
/// </summary>
/// <typeparam name="T">The type of the mocked class.</typeparam>
public class MockingContainer<T> where T : class
{
private readonly IServiceLocator serviceLocator;
private T instance;
/// <summary>
/// Initializes a new instance of the <see cref="MockingContainer{T}" /> class.
/// <param name="dependenciesType">Specifies the type(s) on which the constructor is dependent.
/// <remarks>Empty for resolving container with default/first constructor.</remarks></param>
/// </summary>
/// <param name="dependenciesType">Type of the dependencies.</param>
public MockingContainer(params Type[] dependenciesType)
{
this.container = new UnityContainer(dependenciesType);
this.serviceLocator = new JustMockServiceLocator(container);
this.dependencies = new List<object>();
RegisterDependencies(typeof(T));
}
/// <summary>
/// Resolves the instance of the underlying type with all dependencies injected.
/// </summary>
public T Instance
{
get
{
if (instance == null)
{
instance = (T)container.Resolve(typeof(T));
}
return instance;
}
}
/// <summary>
/// Entry-point for setting expectations.
/// </summary>
/// <typeparam name="TInterface">Mocking interface</typeparam>
/// <param name="expression">Target expression</param>
/// <returns>
/// Reference to <see cref="FuncExpectation{TResult}"/> to setup the mock.
/// </returns>
public FuncExpectation<object> Arrange<TInterface>(Expression<Func<TInterface, object>> expression)
{
return this.serviceLocator.GetInstance<TInterface>().Arrange(expression);
}
/// <summary>
/// Entry-point for setting expectations.
/// </summary>
/// <typeparam name="TInterface">Mocking interface</typeparam>
/// <param name="expression">Target expression</param>
/// <param name="take">Specifics the instance to resolve.</param>
/// <returns>
/// Reference to <see cref="FuncExpectation{TResult}" /> to setup the mock.
/// </returns>
public FuncExpectation<object> Arrange<TInterface>(Expression<Func<TInterface, object>> expression, Take take)
{
return take.Instance<TInterface>(this.serviceLocator).Arrange(expression);
}
/// <summary>
/// Entry-point for setting expectations.
/// </summary>
/// <typeparam name="TInterface">
/// Mocking interface
/// </typeparam>
/// <param name="expression">Target expression</param>
/// <param name="take">Specifics the instance to resolve</param>
/// <returns>
/// Reference to <see cref="ActionExpectation"/> to setup the mock.
/// </returns>
public ActionExpectation Arrange<TInterface>(Expression<Action<TInterface>> expression)
{
return this.serviceLocator.GetInstance<TInterface>().Arrange(expression);
}
/// <summary>
/// Entry-point for setting expectations.
/// </summary>
/// <typeparam name="TInterface">
/// Mocking interface
/// </typeparam>
/// <param name="expression">Target expression</param>
/// <param name="take">Specifics the instance to resolve.</param>
/// <returns>
/// Reference to <see cref="ActionExpectation"/> to setup the mock.
/// </returns>
public ActionExpectation Arrange<TInterface>(Expression<Action<TInterface>> expression, Take take)
{
return take.Instance<TInterface>(this.serviceLocator).Arrange(expression);
}
/// <summary>
/// Asserts all expected setups.
/// </summary>
public void AssertAll()
{
foreach (Type serviceType in dependencies)
{
this.serviceLocator.GetAllInstances(serviceType).ToList().ForEach(x => x.AssertAll());
}
}
/// <summary>
/// Asserts all expected calls that are marked as must or
/// to be occurred a certain number of times.
/// </summary>
public void Assert()
{
foreach (Type serviceType in dependencies)
{
this.serviceLocator.GetAllInstances(serviceType).ToList().ForEach(x => x.Assert());
}
}
/// <summary>
/// Asserts the specific call
/// </summary>
/// <typeparam name="TService">Service type.</typeparam>
/// <param name="expression">Target expression.</param>
public void Assert<TService>(Expression<Action<TService>> expression)
{
this.serviceLocator.GetInstance<TService>().Assert(expression);
}
/// <summary>
/// Asserts the specific call
/// </summary>
/// <typeparam name="TService">Service type.</typeparam>
/// <param name="expression">Target expression</param>
public void Assert<TService>(Expression<Func<TService, object>> expression)
{
Assert(expression, Occurs.NotAvailable());
}
/// <summary>
/// Asserts a specific dependency
/// </summary>
/// <typeparam name="TService">Service type.</typeparam>
public void Assert<TService>()
{
this.serviceLocator.GetInstance<TService>().Assert();
}
/// <summary>
/// Asserts a specific dependency
/// </summary>
/// <typeparam name="TService">Service Type.</typeparam>
/// <param name="take">Specifies the instance to resolve.</param>
public void Assert<TService>(Take take)
{
take.Instance<TService>(this.serviceLocator).Assert();
}
/// <summary>
/// Asserts the specific call
/// </summary>
/// <typeparam name="TService">Service Type.</typeparam>
/// <param name="expression">Target expression.</param>
/// <param name="occurs">Specifies the number of times a mock call should occur.</param>
public void Assert<TService>(Expression<Func<TService, object>> expression, Occurs occurs)
{
this.serviceLocator.GetInstance<TService>().Assert(expression, occurs);
}
/// <summary>
/// Asserts the specific call
/// </summary>
/// <typeparam name="TService">Service Type.</typeparam>
/// <param name="expression">Target expression</param>
/// <param name="occurs">Specifies the number of times a mock call should occur.</param>
public void Assert<TService>(Expression<Action<TService>> expression, Occurs occurs)
{
this.serviceLocator.GetInstance<TService>().Assert(expression, occurs);
}
/// <summary>
/// Asserts the specific call
/// </summary>
/// <typeparam name="TService">Service Type.</typeparam>
/// <param name="expression">Target expression.</param>
/// <param name="take">Specifies the instance to resolve.</param>
public void Assert<TService>(Expression<Func<TService, object>> expression, Take take)
{
take.Instance<TService>(this.serviceLocator).Assert(expression);
}
/// <summary>
/// Asserts the specific call
/// </summary>
/// <typeparam name="TService">Service Type.</typeparam>
/// <param name="expression">Target expression.</param>
/// <param name="take">Specifies the instance to resolve.</param>
public void Assert<TService>(Expression<Action<TService>> expression, Take take)
{
take.Instance<TService>(this.serviceLocator).Assert(expression);
}
/// <summary>
/// Asserts the specific call
/// </summary>
/// <typeparam name="TService">Service Type.</typeparam>
/// <param name="expression">Target expression.</param>
/// <param name="occurs">Specifies the number of times a mock call should occur.</param>
/// <param name="take">Specifies the instance to resolve.</param>
public void Assert<TService>(Expression<Func<TService, object>> expression, Occurs occurs, Take take)
{
take.Instance<TService>(this.serviceLocator).Assert(expression, occurs);
}
/// <summary>
/// Asserts the specific call
/// </summary>
/// <typeparam name="TService">Service Type.</typeparam>
/// <param name="expression">Target expression.</param>
/// <param name="occurs">Specifies the number of times a mock call should occur.</param>
/// <param name="take">Specifies the instance to resolve.</param>
public void Assert<TService>(Expression<Action<TService>> expression, Occurs occurs, Take take)
{
take.Instance<TService>(this.serviceLocator).Assert(expression, occurs);
}
/// <summary>
/// Returns the registered service instance.
/// </summary>
/// <typeparam name="TService">Service Type.</typeparam>
/// <returns>The resolved instance.</returns>
public TService Get<TService>()
{
return this.serviceLocator.GetInstance<TService>();
}
/// <summary>
/// Returns the registered service instance.
/// </summary>
/// <typeparam name="TService">The type of instance to resolve.</typeparam>
/// <param name="take">Specifies the kind of instance to resolve.</param>
/// <returns>The resolved instance.</returns>
public TService Get<TService>(Take take)
{
return take.Instance<TService>(this.serviceLocator);
}
private void RegisterDependencies(Type targetType, params Type[] dependenciesType)
{
foreach (var constructor in targetType.GetConstructors())
{
var parameterInfos = constructor.GetParameters();
foreach (var parameterInfo in parameterInfos)
{
RegisterService(parameterInfo.ParameterType);
}
}
}
private void RegisterService(Type serviceType)
{
if (!serviceType.IsInterface && serviceType.GetConstructors().Length > 0)
{
if (serviceType.GetConstructor(Type.EmptyTypes) == null)
{
RegisterDependencies(serviceType);
AppendToDependenciesList(serviceType);
return;
}
}
if (serviceType.IsSealed && !Mock.IsProfilerEnabled)
throw new AutoMockException(Messages.ProfilerMustBeEnabled);
container.Register(serviceType, Mock.Create(serviceType));
AppendToDependenciesList(serviceType);
}
private void AppendToDependenciesList(Type serviceType)
{
if (!dependencies.Contains(serviceType))
dependencies.Add(serviceType);
}
private readonly IList dependencies;
private readonly IContainer container;
}
}

Просмотреть файл

@ -0,0 +1,35 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Telerik.JustMock.Container")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("07ed19c4-e5d5-43b3-8ba5-d296311af3c4")]

Просмотреть файл

@ -0,0 +1,74 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Linq;
using Microsoft.Practices.ServiceLocation;
using System.Linq.Expressions;
namespace Telerik.JustMock.Container
{
/// <summary>
/// Defines the auto mocking instance to resolve.
/// </summary>
public sealed class Take
{
/// <summary>
/// Initializes a new instance of the <see cref="Take" /> class.
/// </summary>
/// <param name="predicate">Predicate of the instance.</param>
public Take(Expression<Func<IServiceLocator, Type, object>> predicate)
{
this.predicate = predicate;
}
/// <summary>
/// Specifies to resolve the first instance.
/// </summary>
/// <returns>Take configuration.</returns>
public static Take First()
{
return new Take((serviceLocator, x) => serviceLocator.GetAllInstances(x).First());
}
/// <summary>
/// Specifies to resolve the last instance.
/// </summary>
/// <returns>Take configuration.</returns>
public static Take Last()
{
return new Take((serviceLocator, x) => serviceLocator.GetAllInstances(x).Last());
}
/// <summary>
/// Specifies to resolve instance at index.
/// </summary>
/// <param name="index">Position of the instance that will be taken.</param>
/// <returns>Take configuration.</returns>
public static Take At(int index)
{
return new Take((serviceLocator, x) => serviceLocator.GetAllInstances(x).Skip(index).First());
}
internal TInterface Instance<TInterface>(IServiceLocator serviceLocator)
{
return (TInterface) predicate.Compile()(serviceLocator, typeof(TInterface));
}
private readonly Expression<Func<IServiceLocator, Type, object>> predicate;
}
}

Просмотреть файл

@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{780F30EF-9715-4FA4-A4CD-7410F86D0853}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Telerik.JustMock.Container</RootNamespace>
<AssemblyName>Telerik.JustMock.Container</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<SccProjectName>
</SccProjectName>
<SccLocalPath>
</SccLocalPath>
<SccAuxPath>
</SccAuxPath>
<SccProvider>
</SccProvider>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\..\..\Binaries\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\..\..\Binaries\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<DocumentationFile>..\..\..\Binaries\Release\Telerik.JustMock.Container.xml</DocumentationFile>
</PropertyGroup>
<PropertyGroup>
<SignAssembly>true</SignAssembly>
</PropertyGroup>
<PropertyGroup>
<AssemblyOriginatorKeyFile>..\Solution Items\snkey_lite.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'ReleaseFree|AnyCPU'">
<OutputPath>..\..\..\Binaries\ReleaseFree\</OutputPath>
<DefineConstants>TRACE;LITE_EDITION</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisIgnoreBuiltInRuleSets>false</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisIgnoreBuiltInRules>true</CodeAnalysisIgnoreBuiltInRules>
<CodeAnalysisFailOnMissingRules>true</CodeAnalysisFailOnMissingRules>
<DocumentationFile>..\..\..\Binaries\ReleaseFree\Telerik.JustMock.Container.xml</DocumentationFile>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'DebugFree|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>..\..\..\Binaries\DebugFree\</OutputPath>
<DefineConstants>TRACE;DEBUG;LITE_EDITION</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Practices.ServiceLocation">
<HintPath>..\packages\CommonServiceLocator.1.0\lib\NET35\Microsoft.Practices.ServiceLocation.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Practices.Unity, Version=1.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\packages\Unity.2.1.505.2\lib\NET35\Microsoft.Practices.Unity.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Practices.Unity.Configuration">
<HintPath>..\packages\Unity.2.1.505.2\lib\NET35\Microsoft.Practices.Unity.Configuration.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\JustMockLite\CommonAssemblyInfo.cs">
<Link>Properties\CommonAssemblyInfo.cs</Link>
</Compile>
<Compile Include="Abstraction\IContainer.cs" />
<Compile Include="AutoMockException.cs" />
<Compile Include="JustMockServiceLocator.cs" />
<Compile Include="Messages.Designer.cs" />
<Compile Include="MockingContainer.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Take.cs" />
<Compile Include="UnityContainer.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Messages.resx" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\JustMockLite\Telerik.JustMock\Telerik.JustMock.csproj">
<Project>{0749EBC2-4E83-4960-BF28-1FF5C2DEB2B9}</Project>
<Name>Telerik.JustMock</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="..\Solution Items\snkey_lite.snk">
<Link>snkey_lite.snk</Link>
</None>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Просмотреть файл

@ -0,0 +1,126 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.Practices.Unity;
using Telerik.JustMock.Container.Abstraction;
namespace Telerik.JustMock.Container
{
/// <summary>
/// Wrapper over original unity container.
/// </summary>
public class UnityContainer : IContainer
{
/// <summary>
/// Initializes a new instance of the <see cref="UnityContainer" /> class.
/// </summary>
/// <param name="dependenciesType">Type of the dependencies.</param>
public UnityContainer(params Type[] dependenciesType)
{
this.dependenciesType = dependenciesType;
this.container = new Microsoft.Practices.Unity.UnityContainer();
}
/// <summary>
/// Registers the specified instance for its corresponding type.
/// </summary>
/// <param name="serviceType">Corresponding type.</param>
/// <param name="instance">Instance to be registered.</param>
public void Register(Type serviceType, object instance)
{
string instanceName = string.Format("{0}+{1}", serviceType.Name, instance.GetHashCode());
if (!container.IsRegistered(serviceType, instanceName))
{
container.RegisterInstance(serviceType, instanceName, instance);
}
}
/// <summary>
/// Resolve the target type with necessary dependencies.
/// </summary>
/// <param name="serviceType">Service type.</param>
/// <returns>Resolved object.</returns>
public object Resolve(Type serviceType)
{
var instance = ResolveAll(serviceType).FirstOrDefault();
if (instance != null)
return instance;
if (!serviceType.IsInterface)
{
var constructor = serviceType.GetConstructor(dependenciesType);
if (constructor == null && dependenciesType.Length == 0)
constructor = serviceType.GetConstructors().FirstOrDefault();
if (constructor.GetParameters().Length > 0)
return ResolveInstance(constructor);
else
return constructor.Invoke(null);
}
return null;
}
private object ResolveInstance(ConstructorInfo constructor)
{
var parameterInfos = constructor.GetParameters();
var parameters = new List<object>();
int count = 0;
Type lastParameterType = null;
for (int index = 0; index < parameterInfos.Length; index++)
{
Type parameterType = parameterInfos[index].ParameterType;
if (lastParameterType != parameterType)
count = 0;
IList<object> instances = ResolveAll(parameterType);
// add the concrete type directly if not registered.
if (instances.Count > 0)
parameters.Add(instances[count++]);
else if (parameterType.IsClass)
parameters.Add(ResolveInstance(parameterType.GetConstructors().First()));
lastParameterType = parameterType;
}
return constructor.Invoke(parameters.ToArray());
}
/// <summary>
/// Resolves all registered instances for a specific service type.
/// </summary>
/// <param name="serviceType">Service type.</param>
/// <returns>Returns collection of the resolved objects.</returns>
public IList<object> ResolveAll(Type serviceType)
{
return container.ResolveAll(serviceType).ToList();
}
private readonly IUnityContainer container;
private readonly Type[] dependenciesType;
}
}

Просмотреть файл

@ -0,0 +1,42 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
namespace Telerik.JustMock.DemoLib
{
public class ChannelManager
{
internal static IPAddress Address { get; set; }
public static void Open()
{
ChannelManager.Address = IPAddress.Parse("10.10.1.1");
var address = ChannelManager.Address;
if (address != null)
{
throw new Exception("Invalid IP address");
}
}
}
}

Просмотреть файл

@ -0,0 +1,33 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Telerik.JustMock.DemoLib.Objects;
namespace Telerik.JustMock.DemoLib
{
public static class ConfigurationService
{
public static Configuration GetConfiguration()
{
return null;
}
}
}

Просмотреть файл

@ -0,0 +1,37 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Telerik.JustMock.DemoLib
{
public abstract class ExpressionNode
{
protected internal virtual ExpressionNode Accept(ExpressionNodeVisitor visitor)
{
return visitor.VisitExtension(this);
}
protected internal virtual ExpressionNode VisitChildren(ExpressionNodeVisitor visitor)
{
return this;
}
}
}

Просмотреть файл

@ -0,0 +1,32 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Telerik.JustMock.DemoLib
{
public abstract class ExpressionNodeVisitor
{
protected internal virtual ExpressionNode VisitExtension(ExpressionNode node)
{
return node.VisitChildren(this);
}
}
}

Просмотреть файл

@ -0,0 +1,29 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
namespace Telerik.JustMock.DemoLib
{
internal class FooInternal
{
internal virtual int Echo(int arg)
{
throw new NotImplementedException();
}
}
}

Просмотреть файл

@ -0,0 +1,29 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
namespace Telerik.JustMock.DemoLib
{
internal sealed class FooInternalSealed
{
internal int Echo(int arg)
{
throw new NotImplementedException();
}
}
}

Просмотреть файл

@ -0,0 +1,27 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Linq;
namespace Telerik.JustMock.DemoLib
{
internal interface IFooInternal
{
int Echo(int arg);
}
}

Просмотреть файл

@ -0,0 +1,29 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Telerik.JustMock.DemoLib
{
public static class JustMock
{
public const string FullyQualifiedAssemblyName = "Telerik.JustMock, PublicKey=0024000004800000940000000602000000240000525341310004000001000100098b1434e598c656b22eb59000b0bf73310cb8488a6b63db1d35457f2f939f927414921a769821f371c31a8c1d4b73f8e934e2a0769de4d874e0a517d3d7b9c36cd0ffcea2142f60974c6eb00801de4543ef7e93f79687b040d967bb6bd55ca093711b013967a096d524a9cadf94e3b748ebdae7947ea6de6622eabf6548448e";
}
}

Просмотреть файл

@ -0,0 +1,28 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Telerik.JustMock.DemoLib.Objects
{
public class Configuration
{
}
}

Просмотреть файл

@ -0,0 +1,32 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Telerik.JustMock.DemoLib.Objects
{
/// <summary>
/// Logger API
/// </summary>
public interface ILogger
{
void Log(string message);
}
}

Просмотреть файл

@ -0,0 +1,32 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Telerik.JustMock.DemoLib.Objects
{
public class InternalObject
{
internal InternalObject()
{
}
}
}

Просмотреть файл

@ -0,0 +1,40 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Telerik.JustMock.DemoLib.Objects
{
/// <summary>
/// Dummy account class.
/// </summary>
internal class Logger : ILogger
{
internal void LogInternal(string messaage)
{
throw new NotImplementedException();
}
public void Log(string message)
{
LogInternal(message);
}
}
}

Просмотреть файл

@ -0,0 +1,45 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Telerik.JustMock.DemoLib.Objects
{
public class TransactionHeaderViewModel
{
public void SetLineNumbers()
{
}
public void SaveTicket()
{
}
public void SetPaidAmount()
{
}
public string OperatorId { get; set; }
public int ReservationNumber { get; set; }
}
}

Просмотреть файл

@ -0,0 +1,29 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Telerik.JustMock.DemoLib.Objects
{
public class User
{
public string UserId { get; set;}
}
}

Просмотреть файл

@ -0,0 +1,50 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Telerik.JustMock.DemoLib
{
public class OpenAccessContextBase : System.Object
{
[System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public OpenAccessContextBase(){}
public void SaveChanges() {
this.SaveChanges();
}
/// <summary>
/// Saves the changes with the specified concurency mode
/// </summary>
/// <param name="failureMode">Mode to use</param>
public virtual void SaveChanges(string failureMode) {
}
public void Add(System.Collections.IEnumerable entities) {
this.Add(entities);
}
public void Add(object entity) {
throw new NotImplementedException();
}
}
}

Просмотреть файл

@ -0,0 +1,29 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Telerik.JustMock.DemoLib
{
public partial class VerifyModel : OpenAccessContextBase
{
public VerifyModel() { }
}
}

Просмотреть файл

@ -0,0 +1,59 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Telerik.JustMock.DemoLib")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Telerik.JustMock.DemoLib")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyCompany("Telerik AD")]
[assembly: AssemblyCopyright("Copyright <20> Telerik 2010-2013 Telerik AD")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("60f21ed4-498b-4cdf-b16c-05f1ea3e4f60")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: InternalsVisibleTo("Telerik.JustMock.Nunit.Tests")]
[assembly: InternalsVisibleTo("Telerik.JustMock.Tests")]
[assembly: InternalsVisibleTo(Telerik.JustMock.DemoLib.JustMock.FullyQualifiedAssemblyName)]
[assembly: InternalsVisibleTo("Telerik.JustMock.Tests.Elevated")]

Просмотреть файл

@ -0,0 +1,40 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using ModelContent = Telerik.Sitefinity.GenericContent.Model.Content;
using Telerik.Sitefinity.Model;
namespace Telerik.Sitefinity.Fluent.AnyContent.Implementation
{
public class AnyContentManager : IAnyContentManager
{
public ModelContent Unpublish(ModelContent item, CultureInfo culture)
{
var hasTracking = item as IHasTrackingContext;
if (hasTracking != null)
{
hasTracking.RegisterOperation(OperationStatus.Unpublished, null);
}
return null;
}
}
}

Просмотреть файл

@ -0,0 +1,41 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Telerik.Sitefinity.Fluent.Definitions.Fields;
using Telerik.Sitefinity.Web.UI.Fields.Config;
namespace Telerik.Sitefinity
{
/// <summary>
/// Base Fluent API for wrapping of ChoiceFieldElement
/// </summary>
/// <typeparam name="TParentFacade">Type of the parent facade</typeparam>
/// <typeparam name="TActualFacade">Type of the class implementing this abstract class</typeparam>
/// <typeparam name="TConfig">Type of the configuration element</typeparam>
public abstract class BaseChoiceFieldDefinitionFacade<TConfig, TActualFacade, TParentFacade>
: FieldControlDefinitionFacade<TConfig, TActualFacade, TParentFacade>
where TParentFacade : class
where TActualFacade : class
where TConfig : ChoiceFieldElement
{
}
}

Просмотреть файл

@ -0,0 +1,32 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Telerik.Sitefinity.Web.UI.Fields.Config;
namespace Telerik.Sitefinity.Fluent.Definitions.Fields
{
public class ChoiceFieldDefinitionFacade<TParentFacade>
: BaseChoiceFieldDefinitionFacade<ChoiceFieldElement, ChoiceFieldDefinitionFacade<TParentFacade>, TParentFacade>
where TParentFacade : class
{
}
}

Просмотреть файл

@ -0,0 +1,35 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Telerik.Sitefinity.Web.UI.Fields.Config;
using Telerik.Sitefinity.Web.UI.Fields.Contracts;
namespace Telerik.Sitefinity.Web.UI.Fields.Config
{
public class ChoiceFieldElement : FieldControlDefinitionElement, IChoiceFieldDefinition
{
public List<IChoiceDefinition> Choices
{
get {return new List<IChoiceDefinition>(); }
}
}
}

Просмотреть файл

@ -0,0 +1,41 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Telerik.Sitefinity.Model;
namespace Telerik.Sitefinity.GenericContent.Model
{
public abstract class Content
: IContent
, IHasTrackingContext
{
ITrackingContext IHasTrackingContext.TrackingContext
{
get { return new TrackingContext(); }
}
public DateTime DateCreated
{
get;
set;
}
}
}

Просмотреть файл

@ -0,0 +1,48 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using Telerik.Sitefinity.Web.UI.Fields.Config;
using Telerik.Sitefinity.Web.UI.Fields.Enums;
using Telerik.Sitefinity.Web.UI.Fields;
namespace Telerik.Sitefinity.Fluent.Definitions.Fields
{
/// <summary>
/// Fluent API wrapper for <c>ExpandableFieldElement</c>
/// </summary>
/// <typeparam name="TParentFacade">Type of the parent facade</typeparam>
public class ExpandableFieldDefinitionFacade<TParentFacade>
: FieldControlDefinitionFacade<ExpandableFieldElement, ExpandableFieldDefinitionFacade<TParentFacade>, TParentFacade>
, IHasFieldControls<ExpandableFieldDefinitionFacade<TParentFacade>>
where TParentFacade : class
{
internal virtual IHasFieldControls<ExpandableFieldDefinitionFacade<TParentFacade>> FieldsCollection
{
get { return this.fields; }
}
/// <inheritdoc />
public ChoiceFieldDefinitionFacade<ExpandableFieldDefinitionFacade<TParentFacade>> AddChoiceField<TFieldControl>(string fieldName, RenderChoicesAs renderAs)
where TFieldControl : ChoiceField
{
return this.FieldsCollection.AddChoiceField<TFieldControl>(fieldName, renderAs);
}
IHasFieldControls<ExpandableFieldDefinitionFacade<TParentFacade>> fields;
}
}

Просмотреть файл

@ -0,0 +1,45 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Telerik.Sitefinity.Web.UI.Fields.Config;
using Telerik.Sitefinity.Web.UI.Fields.Contracts;
namespace Telerik.Sitefinity
{
public class ExpandableFieldElement : FieldControlDefinitionElement, IExpandableFieldDefinition
{
public IChoiceFieldDefinition ExpandFieldDefinition
{
get { return null; }
}
}
public interface IExpandableFieldDefinition : IFieldControlDefinition
{
/// <summary>
/// Gets the definition for the control that when clicked expands the hidden part of the whole
/// control.
/// </summary>
/// <value>The expand control.</value>
IChoiceFieldDefinition ExpandFieldDefinition { get; }
}
}

Просмотреть файл

@ -0,0 +1,32 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Telerik.Sitefinity.Web.UI.Fields
{
public abstract class FieldControl
{
}
public class ChoiceField : FieldControl
{
}
}

Просмотреть файл

@ -0,0 +1,35 @@
/*
JustMock Lite
Copyright © 2010-2014 Telerik AD
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Telerik.Sitefinity.Web.UI.Fields.Config;
using Telerik.Sitefinity.Web.UI.Fields.Contracts;
namespace Telerik.Sitefinity.Web.UI.Fields.Config
{
public abstract class FieldControlDefinitionElement : FieldDefinitionElement, IFieldControlDefinition
{
public string ID
{
get;
set;
}
}
}

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше