convert to FakeItEasy

This commit is contained in:
Marko Lahma
2017-04-01 14:46:17 +03:00
parent bd3a729ae3
commit ba10504023
126 changed files with 2948 additions and 10546 deletions

View File

@@ -573,255 +573,24 @@ Commandline Examples:
</target>
<target name="clean-obj" description="Clean all 'obj' and 'bin' folders">
<delete dir="src/Spring/Spring.Aop/obj" failonerror="false"/>
<delete dir="src/Spring/Spring.Aop/bin" failonerror="false"/>
<delete dir="src/Spring/Spring.Core/obj" failonerror="false"/>
<delete dir="src/Spring/Spring.Core/bin" failonerror="false"/>
<delete dir="src/Spring/Spring.Data/obj" failonerror="false"/>
<delete dir="src/Spring/Spring.Data/bin" failonerror="false"/>
<delete dir="src/Spring/Spring.Data.NHibernate3/obj" failonerror="false"/>
<delete dir="src/Spring/Spring.Data.NHibernate3/bin" failonerror="false"/>
<delete dir="src/Spring/Spring.Data.NHibernate4/obj" failonerror="false"/>
<delete dir="src/Spring/Spring.Data.NHibernate4/bin" failonerror="false"/>
<delete dir="src/Spring/Spring.Services/obj" failonerror="false"/>
<delete dir="src/Spring/Spring.Services/bin" failonerror="false"/>
<delete dir="src/Spring/Spring.Messaging.Nms/obj" failonerror="false"/>
<delete dir="src/Spring/Spring.Messaging.Nms/bin" failonerror="false"/>
<delete dir="src/Spring/Spring.Messaging.Ems/obj" failonerror="false"/>
<delete dir="src/Spring/Spring.Messaging.Ems/bin" failonerror="false"/>
<delete dir="src/Spring/Spring.Messaging/obj" failonerror="false"/>
<delete dir="src/Spring/Spring.Messaging/bin" failonerror="false"/>
<delete dir="src/Spring/Spring.Scheduling.Quartz2/obj" failonerror="false"/>
<delete dir="src/Spring/Spring.Scheduling.Quartz2/bin" failonerror="false"/>
<delete dir="src/Spring/Spring.Template.Velocity/obj" failonerror="false"/>
<delete dir="src/Spring/Spring.Template.Velocity/bin" failonerror="false"/>
<delete dir="src/Spring/Spring.Testing.NUnit/obj" failonerror="false"/>
<delete dir="src/Spring/Spring.Testing.NUnit/bin" failonerror="false"/>
<delete dir="src/Spring/Spring.Testing.Microsoft/obj" failonerror="false"/>
<delete dir="src/Spring/Spring.Testing.Microsoft/bin" failonerror="false"/>
<delete dir="src/Spring/Spring.Web/obj" failonerror="false"/>
<delete dir="src/Spring/Spring.Web.Conversation.NHibernate3/obj" failonerror="false"/>
<delete dir="src/Spring/Spring.Web.Conversation.NHibernate3/bin" failonerror="false"/>
<delete dir="src/Spring/Spring.Web.Conversation.NHibernate4/obj" failonerror="false"/>
<delete dir="src/Spring/Spring.Web.Conversation.NHibernate4/bin" failonerror="false"/>
<delete dir="src/Spring/Spring.Web/bin" failonerror="false"/>
<delete dir="src/Spring/Spring.Web.Extensions/obj" failonerror="false"/>
<delete dir="src/Spring/Spring.Web.Extensions/bin" failonerror="false"/>
<delete dir="src/Spring/Spring.Web.Mvc3/obj" failonerror="false"/>
<delete dir="src/Spring/Spring.Web.Mvc3/bin" failonerror="false"/>
<delete dir="src/Spring/Spring.Web.Mvc4/obj" failonerror="false"/>
<delete dir="src/Spring/Spring.Web.Mvc4/bin" failonerror="false"/>
<delete dir="src/Spring/Spring.Web.Mvc5/obj" failonerror="false"/>
<delete dir="src/Spring/Spring.Web.Mvc5/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Messaging.Ems.Integration.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Messaging.Ems.Integration.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Scheduling.Quartz2.Integration.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Scheduling.Quartz2.Integration.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Web.Mvc3.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Web.Mvc3.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Web.Mvc4.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Web.Mvc4.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Web.Mvc5.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Web.Mvc5.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Aop.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Aop.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Core.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Core.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Data.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Data.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Data.Integration.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Data.Integration.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Data.NHibernate3.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Data.NHibernate3.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Data.NHibernate3.Integration.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Data.NHibernate3.Integration.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Data.NHibernate4.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Data.NHibernate4.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Data.NHibernate4.Integration.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Data.NHibernate4.Integration.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Data.NHibernate4.NestedTxSuspension.Integration.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Data.NHibernate4.NestedTxSuspension.Integration.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Services.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Services.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Messaging.Nms.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Messaging.Nms.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Messaging.Nms.Integration.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Messaging.Nms.Integeration.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Messaging.Ems.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Messaging.Ems.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Messaging.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Messaging.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Scheduling.Quartz2.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Scheduling.Quartz2.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Template.Velocity.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Template.Velocity.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Web.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Web.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Testing.Microsoft.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Testing.Microsoft.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Testing.NUnit.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Testing.NUnit.Tests/bin" failonerror="false"/>
<delete failonerror="false">
<fileset basedir="test/Spring/Spring.Web.Conversation.NHibernate3.Tests/Data/Spring/ConversationWA/WebConversationStateTest/Bin">
<include name="*.dll"/>
<include name="*.xml"/>
<include name="*.pdb"/>
</fileset>
<fileset basedir="test/Spring/Spring.Web.Conversation.NHibernate4.Tests/Data/Spring/ConversationWA/WebConversationStateTest/Bin">
<include name="*.dll"/>
<include name="*.xml"/>
<include name="*.pdb"/>
</fileset>
</delete>
<delete dir="test/Spring/Spring.Messaging.Ems.Integration.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Messaging.Ems.Integration.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Scheduling.Quartz2.Integration.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Scheduling.Quartz2.Integration.Tests/obj" failonerror="false"/>
<delete failonerror="false">
<fileset basedir="test/Spring/Spring.Services.Tests/Data/Spring/WindowsService/Cassini/wwwroot/bin">
<include name="*.dll"/>
<include name="*.xml"/>
<include name="*.pdb"/>
</fileset>
</delete>
<delete dir="test/Spring/Spring.Web.Mvc3.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Web.Mvc3.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Web.Mvc4.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Web.Mvc4.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Web.Mvc5.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Web.Mvc5.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Web.Conversation.NHibernate3.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Web.Conversation.NHibernate3.Tests/bin" failonerror="false"/>
<delete dir="test/Spring/Spring.Web.Conversation.NHibernate4.Tests/obj" failonerror="false"/>
<delete dir="test/Spring/Spring.Web.Conversation.NHibernate4.Tests/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.CachingQuickStart/src/Spring.CachingQuickStart.Web/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.CachingQuickStart/src/Spring.CachingQuickStart.Web/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.Calculator/src/Spring.Aspects/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.Calculator/src/Spring.Aspects/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.Calculator/src/Spring.Calculator.ClientApp/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.Calculator/src/Spring.Calculator.ClientApp/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.Calculator/src/Spring.Calculator.Contract/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.Calculator/src/Spring.Calculator.Contract/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.Calculator/src/Spring.Calculator.RegisterComponentServices/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.Calculator/src/Spring.Calculator.RegisterComponentServices/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.Calculator/src/Spring.Calculator.RemoteApp/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.Calculator/src/Spring.Calculator.RemoteApp/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.Calculator/src/Spring.Calculator.Services/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.Calculator/src/Spring.Calculator.Services/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.Calculator/src/Spring.Calculator.Web.2003/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.Calculator/src/Spring.Calculator.Web.2003/bin" failonerror="false"/>
<delete dir="examples/Spring/SpringAir/src/SpringAir.Core/obj" failonerror="false"/>
<delete dir="examples/Spring/SpringAir/src/SpringAir.Core/bin" failonerror="false"/>
<delete dir="examples/Spring/SpringAir/src/SpringAir.Data.Ado/obj" failonerror="false"/>
<delete dir="examples/Spring/SpringAir/src/SpringAir.Data.Ado/bin" failonerror="false"/>
<delete dir="examples/Spring/SpringAir/src/SpringAir.Data.IBatis/obj" failonerror="false"/>
<delete dir="examples/Spring/SpringAir/src/SpringAir.Data.IBatis/bin" failonerror="false"/>
<delete dir="examples/Spring/SpringAir/test/SpringAir.Core.Tests/obj" failonerror="false"/>
<delete dir="examples/Spring/SpringAir/test/SpringAir.Core.Tests/bin" failonerror="false"/>
<delete dir="examples/Spring/SpringAir/test/SpringAir.Data.Ado.Tests/obj" failonerror="false"/>
<delete dir="examples/Spring/SpringAir/test/SpringAir.Data.Ado.Tests/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.AopQuickStart/src/Spring.AopQuickStart.Common/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.AopQuickStart/src/Spring.AopQuickStart.Common/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.AopQuickStart/src/Spring.AopQuickStart.Step1/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.AopQuickStart/src/Spring.AopQuickStart.Step1/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.AopQuickStart/src/Spring.AopQuickStart.Step2/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.AopQuickStart/src/Spring.AopQuickStart.Step2/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.AopQuickStart/src/Spring.AopQuickStart.Step3/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.AopQuickStart/src/Spring.AopQuickStart.Step3/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.AopQuickStart/src/Spring.AopQuickStart.Step4/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.AopQuickStart/src/Spring.AopQuickStart.Step4/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.AopQuickStart/src/Spring.AopQuickStart.Step5/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.AopQuickStart/src/Spring.AopQuickStart.Step5/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.AopQuickStart/src/Spring.AopQuickStart.Step6/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.AopQuickStart/src/Spring.AopQuickStart.Step6/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.AopQuickStart/src/Spring.AopQuickStart.Step7/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.AopQuickStart/src/Spring.AopQuickStart.Step7/obj" failonerror="false"/>
<delete failonerror="false">
<fileset basedir="examples/Spring/Spring.Calculator/src/Spring.Calculator.Web.2005/Bin">
<include name="*.dll"/>
<include name="*.xml"/>
<include name="*.pdb"/>
</fileset>
</delete>
<delete failonerror="false">
<fileset basedir="examples/Spring/Spring.Calculator/src/Spring.Calculator.Web.2005/Bin">
<include name="*.dll"/>
<include name="*.xml"/>
<include name="*.pdb"/>
</fileset>
</delete>
<delete dir="examples/Spring/Spring.DataQuickStart/src/Spring/Spring.DataQuickStart/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.DataQuickStart/test/Spring/Spring.DataQuickStart.Tests/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.IoCQuickStart.AppContext/src/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.IoCQuickStart.AppContext/src/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.IoCQuickStart.EventRegistry/src/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.IoCQuickStart.EventRegistry/src/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.IoCQuickStart.MovieFinder/src/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.IoCQuickStart.MovieFinder/src/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.MsmqQuickStart/src/Spring/Spring.MsmqQuickStart.Client/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.MsmqQuickStart/src/Spring/Spring.MsmqQuickStart.Client/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.MsmqQuickStart/src/Spring/Spring.MsmqQuickStart.Common/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.MsmqQuickStart/src/Spring/Spring.MsmqQuickStart.Common/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.MsmqQuickStart/src/Spring/Spring.MsmqQuickStart.Server/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.MsmqQuickStart/src/Spring/Spring.MsmqQuickStart.Server/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.NmsQuickStart/src/Spring/Spring.NmsQuickStart.Client/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.NmsQuickStart/src/Spring/Spring.NmsQuickStart.Client/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.NmsQuickStart/src/Spring/Spring.NmsQuickStart.Common/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.NmsQuickStart/src/Spring/Spring.NmsQuickStart.Common/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.NmsQuickStart/src/Spring/Spring.NmsQuickStart.Server/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.NmsQuickStart/src/Spring/Spring.NmsQuickStart.Server/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.TxQuickStart/src/Spring/Spring.TxQuickStart/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.TxQuickStart/src/Spring/Spring.TxQuickStart/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.TxQuickStart/test/Spring/Spring.TxQuickStart.Tests/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.TxQuickStart/test/Spring/Spring.TxQuickStart.Tests/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.WcfQuickStart/src/Spring.WcfQuickStart.Aspects/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.WcfQuickStart/src/Spring.WcfQuickStart.Aspects/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.WcfQuickStart/src/Spring.WcfQuickStart.ClientApp/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.WcfQuickStart/src/Spring.WcfQuickStart.ClientApp/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.WcfQuickStart/src/Spring.WcfQuickStart.Contracts/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.WcfQuickStart/src/Spring.WcfQuickStart.Contracts/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.WcfQuickStart/src/Spring.WcfQuickStart.ServerApp/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.WcfQuickStart/src/Spring.WcfQuickStart.ServerApp/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.WcfQuickStart/src/Spring.WcfQuickStart.ServerWeb/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.WcfQuickStart/src/Spring.WcfQuickStart.ServerWeb/obj" failonerror="false"/>
<delete failonerror="false">
<fileset basedir="examples/Spring/Spring.Web.Extensions.Example/src/Spring.Web.Extensions.Example.2008/Bin">
<include name="*.dll"/>
<include name="*.xml"/>
<include name="*.pdb"/>
</fileset>
</delete>
<delete failonerror="false">
<fileset basedir="examples/Spring/Spring.Web.Extensions.Example/src/Spring.Web.Extensions.Example.2010/Bin">
<include name="*.dll"/>
<include name="*.xml"/>
<include name="*.pdb"/>
</fileset>
</delete>
<delete dir="examples/Spring/SpringAir/src/SpringAir.Web.2005.References/bin" failonerror="false"/>
<delete dir="examples/Spring/SpringAir/src/SpringAir.Web.2005.References/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.Data.NHibernate.Northwind/src/Spring.Northwind.Dao/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.Data.NHibernate.Northwind/src/Spring.Northwind.Dao/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.Data.NHibernate.Northwind/src/Spring.Northwind.Dao.NHibernate/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.Data.NHibernate.Northwind/src/Spring.Northwind.Dao.NHibernate/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.Data.NHibernate.Northwind/src/Spring.Northwind.Service/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.Data.NHibernate.Northwind/src/Spring.Northwind.Service/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.Data.NHibernate.Northwind/src/Spring.Northwind.Web/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.Data.NHibernate.Northwind/src/Spring.Northwind.Web/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.Data.NHibernate.Northwind/src/Spring.Northwind.Web.ConvWA/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.Data.NHibernate.Northwind/src/Spring.Northwind.Web.ConvWA/bin" failonerror="false"/>
<delete dir="examples/Spring/Spring.Data.NHibernate.Northwind/test/Spring.Northwind.IntegrationTests/obj" failonerror="false"/>
<delete dir="examples/Spring/Spring.Data.NHibernate.Northwind/test/Spring.Northwind.IntegrationTests/bin" failonerror="false"/>
<delete>
<fileset basedir="src/">
<include name="**/bin/**/*.*" />
<include name="**/obj/**/*.*" />
</fileset>
</delete>
<delete>
<fileset basedir="test/">
<include name="**/bin/**/*.*" />
<include name="**/obj/**/*.*" />
</fileset>
</delete>
<delete>
<fileset basedir="examples/">
<include name="**/bin/**/*.*" />
<include name="**/obj/**/*.*" />
</fileset>
</delete>
</target>
<target name="package" depends="set-package-configuration" description="Build and Package distribution">

Binary file not shown.

Binary file not shown.

File diff suppressed because it is too large Load Diff

View File

@@ -31,8 +31,8 @@
<NeutralLanguage>en-US</NeutralLanguage>
<WarningsAsErrors>True</WarningsAsErrors>
<RepositoryType>git</RepositoryType>
<RepositoryUrl>https://github.com/spring-projects/spring-net</RepositoryUrl>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<TreatWarningsAsErrors>True</TreatWarningsAsErrors>
@@ -46,8 +46,13 @@
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup Condition="'$(SourceLinkEnabled)' != 'false'">
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0-beta-63127-02" PrivateAssets="All"/>
</ItemGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugType>Full</DebugType>
<DefineConstants>DEBUG;TRACE;DEBUG_DYNAMIC;$(DefineConstants)</DefineConstants>
</PropertyGroup>

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
* Copyright © 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
* Copyright © 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -41,7 +41,7 @@ namespace Spring.Aop.Framework
/// advice configuration.
/// </p>
/// <p>
/// To expose the current proxy, set the <see cref="Spring.Aop.Framework.ProxyConfig.ExposeProxy"/>
/// To expose the current proxy, set the <see cref="Spring.Aop.Framework.ProxyConfig.ExposeProxy"/>
/// property on the controlling proxy to <see langword="true"/>.
/// The default value for the <see cref="Spring.Aop.Framework.ProxyConfig.ExposeProxy"/> property
/// is <see langword="false"/>, for performance reasons.
@@ -70,7 +70,7 @@ namespace Spring.Aop.Framework
/// </summary>
private static Stack ProxyStack
{
get
get
{
if (tls_ProxyStack == null)
{
@@ -90,7 +90,7 @@ namespace Spring.Aop.Framework
/// on the controlling proxy has been set to <see langword="true"/>.
/// </p>
/// <p>
/// The default value for the
/// The default value for the
/// <see cref="Spring.Aop.Framework.ProxyConfig.ExposeProxy"/> property
/// is <see langword="false"/>, for performance reasons.
/// </p>
@@ -99,7 +99,7 @@ namespace Spring.Aop.Framework
{
get
{
return (tls_ProxyStack != null && tls_ProxyStack.Count > 0);
return (tls_ProxyStack != null && tls_ProxyStack.Count > 0);
}
}
@@ -125,7 +125,7 @@ namespace Spring.Aop.Framework
}
/// <summary>
/// Sets the current proxy by pushing it to the proxy stack.
/// Sets the current proxy by pushing it to the proxy stack.
/// </summary>
/// <remarks>
/// <p>

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
* Copyright © 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -109,13 +109,13 @@ namespace Spring.Aop.Framework.AutoProxy
/// Indicates whether to mark the create proxy as immutable.
/// </summary>
/// <remarks>
/// Setting this to true effectively disables modifying the generated
/// Setting this to true effectively disables modifying the generated
/// proxy's advisor configuration
/// </remarks>
private bool freezeProxy = false;
/// <summary>
/// Names of common interceptors.
/// Names of common interceptors.
/// We must use object name rather than object references
/// to handle prototype advisors/interceptors.
/// Default is the empty array: no common interceptors.
@@ -142,7 +142,7 @@ namespace Spring.Aop.Framework.AutoProxy
#region Properties
/// <summary>
/// Sets the AdvisorAdapterRegistry to use.
/// Sets the AdvisorAdapterRegistry to use.
/// </summary>
/// <remarks>
/// Default is the global AdvisorAdapterRegistry.
@@ -170,19 +170,19 @@ namespace Spring.Aop.Framework.AutoProxy
set { customTargetSourceCreators = value; }
}
/// <summary>
/// Sets the common interceptors, a list of <see cref="AopAlliance.Aop.IAdvice"/>,
/// <summary>
/// Sets the common interceptors, a list of <see cref="AopAlliance.Aop.IAdvice"/>,
/// <see cref="Spring.Aop.IAdvisor"/> and introduction object names.
/// </summary>
/// <remarks>
/// <para>
/// If this property isn't set, there will be zero common interceptors.
/// If this property isn't set, there will be zero common interceptors.
/// This is perfectly valid, if "specific" interceptors such as
/// matching Advisors are all we want.
/// </para>
/// </remarks>
/// <value>
/// The list of <see cref="AopAlliance.Aop.IAdvice"/>,
/// The list of <see cref="AopAlliance.Aop.IAdvice"/>,
/// <see cref="Spring.Aop.IAdvisor"/> and introduction object names.
/// </value>
/// <seealso cref="AopAlliance.Aop.IAdvice"/>
@@ -194,7 +194,7 @@ namespace Spring.Aop.Framework.AutoProxy
/// <summary>
/// Sets whether the common interceptors should be applied before
/// object-specific ones.
/// object-specific ones.
/// </summary>
/// <remarks>
/// Default is true; else, object-specific interceptors will get applied first.
@@ -683,7 +683,7 @@ namespace Spring.Aop.Framework.AutoProxy
/// <param name="pvs">The property values that the factory is about to apply (never <code>null</code>).</param>
/// <param name="pis">he relevant property infos for the target object (with ignored
/// dependency types - which the factory handles specifically - already filtered out)</param>
/// <param name="objectInstance">The object instance created, but whose properties have not yet
/// <param name="objectInstance">The object instance created, but whose properties have not yet
/// been set.</param>
/// <param name="objectName">Name of the object.</param>
/// <returns>The passed in PropertyValues</returns>

View File

@@ -2,13 +2,13 @@
/*
* Copyright © 2002-2011 the original author or authors.
*
*
* 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.

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
* Copyright © 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -236,7 +236,7 @@ namespace Spring.Context.Support
/// processors being added to the underlying <see cref="IConfigurableObjectFactory"/>
/// </summary>
/// <remarks>
/// Each time <see cref="Refresh()"/> is called on this context, the context ensures, that
/// Each time <see cref="Refresh()"/> is called on this context, the context ensures, that
/// all default <see cref="IObjectPostProcessor"/>s are registered with the underlying <see cref="IConfigurableObjectFactory"/>.
/// </remarks>
/// <param name="defaultObjectPostProcessor">The <see cref="IObjectPostProcessor"/> instance.</param>
@@ -268,7 +268,7 @@ namespace Spring.Context.Support
#endregion
// Closed event is raised before destroying objectfactory to enable registered IApplicationEventListeners
// Closed event is raised before destroying objectfactory to enable registered IApplicationEventListeners
// to handle the event before they get disposed.
PublishEvent(this, new ContextClosedEventArgs());
@@ -1046,7 +1046,7 @@ namespace Spring.Context.Support
}
/// <summary>
/// Registers well-known <see cref="IObjectPostProcessor"/>s and
/// Registers well-known <see cref="IObjectPostProcessor"/>s and
/// preregisters well-known dependencies using <see cref="IConfigurableListableObjectFactory.RegisterResolvableDependency"/>
/// </summary>
/// <param name="objectFactory">the raw object factory as returned from <see cref="RefreshObjectFactory"/></param>
@@ -1370,14 +1370,14 @@ namespace Spring.Context.Support
{
return GetObjectDefinitionNames(false);
}
/// <summary>
/// Return the names of all objects defined in this factory, if <code>includeAncestors</code>is <code>true</code>
/// includes all parent factories.
/// </summary>
/// <param name="includeAncestors">to include parent factories into result</param>
/// <returns>
/// The names of all objects defined in this factory, if <code>includeAncestors</code> is <code>true</code> includes all
/// The names of all objects defined in this factory, if <code>includeAncestors</code> is <code>true</code> includes all
/// objects defined in parent factories, or an empty array if none are defined.
/// </returns>
public IList<string> GetObjectDefinitionNames(bool includeAncestors)
@@ -1401,7 +1401,7 @@ namespace Spring.Context.Support
/// </exception>
/// <exception cref="Spring.Objects.ObjectsException">
/// In the case of errors.
/// </exception>
/// </exception>
public virtual IObjectDefinition GetObjectDefinition(string name)
{
return SafeGetObjectFactory().GetObjectDefinition(name);
@@ -1425,7 +1425,7 @@ namespace Spring.Context.Support
/// </exception>
/// <exception cref="Spring.Objects.ObjectsException">
/// In the case of errors.
/// </exception>
/// </exception>
public IObjectDefinition GetObjectDefinition(string name, bool includeAncestors)
{
return SafeGetObjectFactory().GetObjectDefinition(name, includeAncestors);
@@ -2099,7 +2099,7 @@ namespace Spring.Context.Support
/// of the given name from an ancestor object factory.
/// </summary>
/// <remarks>
///
///
/// </remarks>
/// <param name="name">The name of the object to query.</param>
/// <returns>
@@ -2115,8 +2115,8 @@ namespace Spring.Context.Support
#region IObjectDefinitionRegistry Members
/// <summary>
/// Determine whether the given object name is already in use within this context,
/// i.e. whether there is a local object. May be override by subclasses, the default
/// Determine whether the given object name is already in use within this context,
/// i.e. whether there is a local object. May be override by subclasses, the default
/// implementation simply returns <see cref="ContainsLocalObject"/>
/// </summary>
public virtual bool IsObjectNameInUse(string objectName)
@@ -2496,7 +2496,7 @@ namespace Spring.Context.Support
/// </summary>
/// <remarks>
/// <p>
///
///
/// </p>
/// </remarks>
/// <param name="sender">

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
* Copyright © 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -36,7 +36,7 @@ namespace Spring.Expressions
/// caches argumentNames of this instance
/// </summary>
private string[] argumentNames;
/// <summary>
/// caches body expression of this lambda function
/// </summary>
@@ -56,7 +56,7 @@ namespace Spring.Expressions
: base(info, context)
{
}
/// <summary>
/// Gets argument names for this lambda expression.
/// </summary>
@@ -107,7 +107,7 @@ namespace Spring.Expressions
arguments[argNames[i]] = argValues[i];
}
EvaluationContext ec = (EvaluationContext)evalContext;
EvaluationContext ec = evalContext;
using (ec.SwitchLocalVariables(arguments))
{
object result = Get(context, ec);

File diff suppressed because it is too large Load Diff

View File

@@ -1,14 +1,14 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
*
* Copyright © 2002-2011 the original author or authors.
*
* 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.
@@ -41,11 +41,11 @@ using ConfigXmlDocument = Spring.Util.ConfigXmlDocument;
namespace Spring.Objects.Factory.Config
{
/// <summary>
/// Various utility methods for .NET style .config files.
/// Various utility methods for .NET style .config files.
/// </summary>
/// <remarks>
/// <p>
/// Currently supports reading custom configuration sections and returning them as
/// Currently supports reading custom configuration sections and returning them as
/// <see cref="System.Collections.Specialized.NameValueCollection"/> objects.
/// </p>
/// </remarks>
@@ -314,7 +314,7 @@ namespace Spring.Objects.Factory.Config
if (typeof(IConfigurationSectionHandler).IsAssignableFrom(handlerType))
{
IConfigurationSectionHandler handler = (IConfigurationSectionHandler)ObjectUtils.InstantiateType(handlerType);
return ((IConfigurationSectionHandler)handler).Create(null, null, sectionContent);
return handler.Create(null, null, sectionContent);
}
// NET 2.0 ConfigurationSection
@@ -362,7 +362,7 @@ namespace Spring.Objects.Factory.Config
handlerType = defaultConfigurationSectionHandlerType;
}
}
if (xmlConfig != null)
{
XmlAttribute xmlConfigType = xmlConfig.Attributes[ConfigSectionTypeAttribute];

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
* Copyright © 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
* Copyright © 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,7 +34,7 @@ namespace Spring.Objects.Factory.Xml
/// <summary>
/// Stateful class used to parse XML object definitions.
/// </summary>
/// <remarks>Not all parsing code has been refactored into this class. See
/// <remarks>Not all parsing code has been refactored into this class. See
/// BeanDefinitionParserDelegate in Java for how this class should evolve.</remarks>
/// <author>Rob Harrop</author>
/// <author>Juergen Hoeller</author>
@@ -84,7 +84,7 @@ namespace Spring.Objects.Factory.Xml
}
/// <summary>
/// Gets the defaults definition object, or <code>null</code> if the
/// Gets the defaults definition object, or <code>null</code> if the
/// default have not yet been initialized.
/// </summary>
/// <value>The defaults.</value>
@@ -341,7 +341,7 @@ namespace Spring.Objects.Factory.Xml
{
if (aliases.Count > 0)
{
objectName = (string) aliases[0];
objectName = aliases[0];
aliases.RemoveAt(0);
if (log.IsDebugEnabled)
{
@@ -373,9 +373,9 @@ namespace Spring.Objects.Factory.Xml
objectName = readerContext.GenerateObjectName(definition);
// Register an alias for the plain object type name, if possible.
string objectTypeName = definition.ObjectTypeName;
if (objectTypeName != null
&& objectName.StartsWith(objectTypeName)
&& objectName.Length>objectTypeName.Length
if (objectTypeName != null
&& objectName.StartsWith(objectTypeName)
&& objectName.Length>objectTypeName.Length
&& !readerContext.Registry.IsObjectNameInUse(objectTypeName))
{
aliases.Add(objectTypeName);
@@ -543,7 +543,7 @@ namespace Spring.Objects.Factory.Xml
/// Returns the value of the element's attribute or <c>null</c>, if the attribute is not specified.
/// </summary>
/// <remarks>
/// This is a helper for bypassing the behavior of <see cref="XmlElement.GetAttribute(string)"/>
/// This is a helper for bypassing the behavior of <see cref="XmlElement.GetAttribute(string)"/>
/// to return <see cref="string.Empty"/> if the attribute does not exist.
/// </remarks>
public string GetAttributeValue(XmlElement element, string attributeName)
@@ -556,11 +556,11 @@ namespace Spring.Objects.Factory.Xml
}
/// <summary>
/// Returns the value of the element's attribute or <paramref name="defaultValue"/>,
/// Returns the value of the element's attribute or <paramref name="defaultValue"/>,
/// if the attribute is not specified.
/// </summary>
/// <remarks>
/// This is a helper for bypassing the behavior of <see cref="XmlElement.GetAttribute(string)"/>
/// This is a helper for bypassing the behavior of <see cref="XmlElement.GetAttribute(string)"/>
/// to return <see cref="string.Empty"/> if the attribute does not exist.
/// </remarks>
public string GetAttributeValue(XmlElement element, string attributeName, string defaultValue)

View File

@@ -276,8 +276,8 @@ namespace Spring.Objects.Factory.Xml
case ObjectDefinitionConstants.TypeAttribute:
// we're wiring up to a static event exposed on a Type (class)
myHandler.Source = parserContext.ReaderContext.Reader.Domain == null ?
(object)sourceAtt.Value :
(object)TypeResolutionUtils.ResolveType(sourceAtt.Value);
sourceAtt.Value :
TypeResolutionUtils.ResolveType(sourceAtt.Value) as object;
break;
}
events.AddHandler(myHandler);
@@ -481,7 +481,7 @@ namespace Spring.Objects.Factory.Xml
autowire = childParserContext.ParserHelper.Defaults.Autowire;
}
od.AutowireMode = GetAutowireMode(autowire);
string autowireCandidates = GetAttributeValue(element, ObjectDefinitionConstants.AutowireCandidateAttribute);
if (string.IsNullOrEmpty(autowireCandidates) || ObjectDefinitionConstants.DefaultValue.Equals(autowireCandidates))
{
@@ -695,7 +695,7 @@ namespace Spring.Objects.Factory.Xml
ObjectMetadataAttribute attribute = new ObjectMetadataAttribute(key, value);
attribute.Source = (XmlElement)node;
attributeAccessor.AddMetadataAttribute(attribute);
attributeAccessor.AddMetadataAttribute(attribute);
}
}
@@ -724,7 +724,7 @@ namespace Spring.Objects.Factory.Xml
parserContext.ReaderContext.Resource, name,
"Tag 'qualifier' must have a 'type' attribute");
}
var qualifier = new AutowireCandidateQualifier(typeName);
qualifier.Source = element;
@@ -1180,7 +1180,7 @@ namespace Spring.Objects.Factory.Xml
/// </param>
/// <returns>The set definition.</returns>
protected Set ParseSetElement(XmlElement collectionEle, string name, ParserContext parserContext)
{
{
string elementTypeName = GetAttributeValue(collectionEle, "element-type");
XmlNodeList nl = collectionEle.ChildNodes;
ManagedSet target = new ManagedSet(nl.Count);
@@ -1556,7 +1556,7 @@ namespace Spring.Objects.Factory.Xml
// /// Returns the value of the element's attribute or <c>null</c>, if the attribute is not specified.
// /// </summary>
// /// <remarks>
// /// This is a helper for bypassing the behavior of <see cref="XmlElement.GetAttribute(string)"/>
// /// This is a helper for bypassing the behavior of <see cref="XmlElement.GetAttribute(string)"/>
// /// to return <see cref="string.Empty"/> if the attribute does not exist.
// /// </remarks>
// protected static string GetAttributeValue(XmlElement element, string attributeName)
@@ -1569,11 +1569,11 @@ namespace Spring.Objects.Factory.Xml
// }
//
// /// <summary>
// /// Returns the value of the element's attribute or <paramref name="defaultValue"/>,
// /// Returns the value of the element's attribute or <paramref name="defaultValue"/>,
// /// if the attribute is not specified.
// /// </summary>
// /// <remarks>
// /// This is a helper for bypassing the behavior of <see cref="XmlElement.GetAttribute(string)"/>
// /// This is a helper for bypassing the behavior of <see cref="XmlElement.GetAttribute(string)"/>
// /// to return <see cref="string.Empty"/> if the attribute does not exist.
// /// </remarks>
// protected static string GetAttributeValue(XmlElement element, string attributeName, string defaultValue)

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
* Copyright © 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -222,7 +222,7 @@ namespace Spring.Objects.Support
#endregion
IEventHandlerValue myHandler = method.IsStatic ?
(IEventHandlerValue) new StaticEventHandlerValue() :
new StaticEventHandlerValue() :
(IEventHandlerValue) new InstanceEventHandlerValue();
myHandler.EventName = theEvent.Name;
myHandler.MethodName = method.Name;

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
* Copyright © 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -42,7 +42,7 @@ namespace Spring.Objects.Support
/// <see cref="Spring.Objects.Factory.Config.MethodInvokingFactoryObject"/>.
/// </p>
/// <p>
/// Usage: specify either the <see cref="MethodInvoker.TargetType"/> and
/// Usage: specify either the <see cref="MethodInvoker.TargetType"/> and
/// <see cref="MethodInvoker.TargetMethod"/> or the
/// <see cref="MethodInvoker.TargetObject"/> and
/// <see cref="MethodInvoker.TargetMethod"/> properties respectively, and
@@ -58,13 +58,13 @@ namespace Spring.Objects.Support
/// arguments.
/// </p>
/// <code language="C#">
/// public class Foo
/// public class Foo
/// {
/// public string ToString(string name, int age, string address)
/// {
/// return string.Format("{0}, {1} years old, {2}", name, age, address);
/// }
///
///
/// public static void Main()
/// {
/// Foo foo = new Foo();
@@ -352,7 +352,7 @@ namespace Spring.Objects.Support
}
// look up the index of where in the prepared args array we're gonna stick the named argument value
int namedArgumentsIndex = (int) argumentNamesToIndexes[argumentName];
int namedArgumentsIndex = argumentNamesToIndexes[argumentName];
PreparedArguments[namedArgumentsIndex] = argumentValue;
// we've prepped this index position, so mark it as so...
argumentNamesToIndexes[argumentName] = THE_ARGUMENT_IS_PREPARED;
@@ -420,7 +420,7 @@ namespace Spring.Objects.Support
}
if (theMethod == null)
{
// search for a method with a matching signature...
// search for a method with a matching signature...
ComposedCriteria searchCriteria = new ComposedCriteria();
searchCriteria.Add(new MethodNameMatchCriteria(genericInfo.GenericMethodName));
searchCriteria.Add(new MethodParametersCountCriteria(ArgumentCount));

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
* Copyright © 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -1,14 +1,14 @@
#region License
/*
* Copyright <20> 2002-2011 the original author or authors.
*
* Copyright <20> 2002-2011 the original author or authors.
*
* 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.
@@ -50,18 +50,18 @@ namespace Spring.Data.NHibernate.Generic
/// or handling Session lifecycle exceptions. For typical single step actions,
/// there are various convenience methods (Find, Load, SaveOrUpdate, Delete).
/// </p>
///
///
/// <p>Can be used within a service implementation via direct instantiation
/// with a ISessionFactory reference, or get prepared in an application context
/// and given to services as an object reference. Note: The ISessionFactory should
/// always be configured as an object in the application context, in the first case
/// given to the service directly, in the second case to the prepared template.
/// </p>
///
///
/// <p>This class can be considered as a direct alternative to working with the raw
/// Hibernate Session API (through SessionFactoryUtils.Session).
/// </p>
///
///
/// <p>LocalSessionFactoryObject is the preferred way of obtaining a reference
/// to a specific NHibernate ISessionFactory.
/// </p>
@@ -73,8 +73,8 @@ namespace Spring.Data.NHibernate.Generic
#region Fields
NHibernate.HibernateTemplate classicHibernateTemplate;
#endregion
#endregion
#region Constructor (s)
@@ -89,25 +89,25 @@ namespace Spring.Data.NHibernate.Generic
/// <summary>
/// Initializes a new instance of the <see cref="HibernateTemplate"/> class.
/// </summary>
/// <remarks>Allows creation of a new non-transactional session when no
/// <remarks>Allows creation of a new non-transactional session when no
/// transactional Session can be found for the current thread</remarks>
/// <param name="sessionFactory">The session factory to create sessions.</param>
public HibernateTemplate(ISessionFactory sessionFactory)
{
classicHibernateTemplate = new Spring.Data.NHibernate.HibernateTemplate(sessionFactory);
classicHibernateTemplate = new Spring.Data.NHibernate.HibernateTemplate(sessionFactory);
AfterPropertiesSet();
}
/// <summary>
/// Initializes a new instance of the <see cref="HibernateTemplate"/> class.
/// </summary>
/// <param name="sessionFactory">The session factory to create sessions.</param>
/// <param name="sessionFactory">The session factory to create sessions.</param>
/// <param name="allowCreate">if set to <c>true</c> allow creation
/// of a new non-transactional session when no transactional Session can be found
/// of a new non-transactional session when no transactional Session can be found
/// for the current thread.</param>
public HibernateTemplate(ISessionFactory sessionFactory, bool allowCreate)
{
classicHibernateTemplate = new Spring.Data.NHibernate.HibernateTemplate(sessionFactory, allowCreate);
classicHibernateTemplate = new Spring.Data.NHibernate.HibernateTemplate(sessionFactory, allowCreate);
AfterPropertiesSet();
}
@@ -247,7 +247,7 @@ namespace Spring.Data.NHibernate.Generic
}
/// <summary>
/// Gets or sets a value indicating whether to
/// Gets or sets a value indicating whether to
/// cache all queries executed by this template.
/// </summary>
/// <remarks>
@@ -344,7 +344,7 @@ namespace Spring.Data.NHibernate.Generic
/// <summary>
/// Gets or sets the proxy factory.
/// </summary>
/// <remarks>This may be useful to set if you create many instances of
/// <remarks>This may be useful to set if you create many instances of
/// HibernateTemplate and/or HibernateDaoSupport. This allows the same
/// ProxyFactory implementation to be used thereby limiting the
/// number of dynamic proxy types created in the temporary assembly, which
@@ -362,8 +362,8 @@ namespace Spring.Data.NHibernate.Generic
#region Properties
#endregion
#region Methods
@@ -374,7 +374,7 @@ namespace Spring.Data.NHibernate.Generic
/// </summary>
public void Clear()
{
classicHibernateTemplate.Clear();
classicHibernateTemplate.Clear();
}
@@ -606,13 +606,13 @@ namespace Spring.Data.NHibernate.Generic
#endif
/// <summary>
/// Copy the state of the given object onto the persistent object with the same identifier.
/// Copy the state of the given object onto the persistent object with the same identifier.
/// If there is no persistent instance currently associated with the session, it will be loaded.
/// Return the persistent instance. If the given instance is unsaved,
/// Return the persistent instance. If the given instance is unsaved,
/// save a copy of and return it as a newly persistent instance.
/// The given instance does not become associated with the session.
/// The given instance does not become associated with the session.
/// This operation cascades to associated instances if the association is mapped with cascade="merge".
/// The semantics of this method are defined by JSR-220.
/// The semantics of this method are defined by JSR-220.
/// </summary>
/// <param name="entity">The persistent object to merge.
/// (<i>not</i> necessarily to be associated with the Hibernate Session)
@@ -636,7 +636,7 @@ namespace Spring.Data.NHibernate.Generic
/// <typeparam name="T">The object type to get.</typeparam>
/// <param name="id">The id of the object to get.</param>
/// <returns>the persistent instance, or null if not found</returns>
/// <exception cref="DataAccessException">In case of Hibernate errors</exception>
/// <exception cref="DataAccessException">In case of Hibernate errors</exception>
public T Get<T>(object id)
{
return Get<T>(id, null);
@@ -668,7 +668,7 @@ namespace Spring.Data.NHibernate.Generic
/// <typeparam name="T">The object type to load.</typeparam>
/// <param name="id">An identifier of the persistent instance.</param>
/// <returns>The persistent instance</returns>
/// <exception cref="ObjectRetrievalFailureException">If not found</exception>
/// <exception cref="ObjectRetrievalFailureException">If not found</exception>
/// <exception cref="DataAccessException">In case of Hibernate errors</exception>
public T Load<T>(object id)
{
@@ -684,8 +684,8 @@ namespace Spring.Data.NHibernate.Generic
/// <param name="id">An identifier of the persistent instance.</param>
/// <param name="lockMode">The lock mode.</param>
/// <returns>The persistent instance</returns>
/// <exception cref="ObjectRetrievalFailureException">If not found</exception>
/// <exception cref="DataAccessException">In case of Hibernate errors</exception>
/// <exception cref="ObjectRetrievalFailureException">If not found</exception>
/// <exception cref="DataAccessException">In case of Hibernate errors</exception>
public T Load<T>(object id, LockMode lockMode)
{
return Execute(new LoadByTypeHibernateCallback<T>(id, lockMode), true);
@@ -715,7 +715,7 @@ namespace Spring.Data.NHibernate.Generic
/// <returns>
/// a generic List containing 0 or more persistent instances
/// </returns>
/// <exception cref="DataAccessException">In case of Hibernate errors</exception>
/// <exception cref="DataAccessException">In case of Hibernate errors</exception>
public IList<T> Find<T>(string queryString)
{
return Find<T>(queryString, (object[]) null, (IType[]) null);
@@ -731,7 +731,7 @@ namespace Spring.Data.NHibernate.Generic
/// <returns>
/// a generic List containing 0 or more persistent instances
/// </returns>
/// <exception cref="DataAccessException">In case of Hibernate errors</exception>
/// <exception cref="DataAccessException">In case of Hibernate errors</exception>
public IList<T> Find<T>(string queryString, object value)
{
return Find<T>(queryString, new object[] {value}, (IType[]) null);
@@ -748,7 +748,7 @@ namespace Spring.Data.NHibernate.Generic
/// <returns>
/// a generic List containing 0 or more persistent instances
/// </returns>
/// <exception cref="DataAccessException">In case of Hibernate errors</exception>
/// <exception cref="DataAccessException">In case of Hibernate errors</exception>
public IList<T> Find<T>(string queryString, object value, IType type)
{
return Find<T>(queryString, new object[] {value}, new IType[] {type});
@@ -762,7 +762,7 @@ namespace Spring.Data.NHibernate.Generic
/// <param name="queryString">a query expressed in Hibernate's query language</param>
/// <param name="values">the values of the parameters</param>
/// <returns>a generic List containing 0 or more persistent instances</returns>
/// <exception cref="DataAccessException">In case of Hibernate errors</exception>
/// <exception cref="DataAccessException">In case of Hibernate errors</exception>
public IList<T> Find<T>(string queryString, object[] values)
{
return Find<T>(queryString, values, (IType[]) null);
@@ -779,8 +779,8 @@ namespace Spring.Data.NHibernate.Generic
/// <returns>
/// a generic List containing 0 or more persistent instances
/// </returns>
/// <exception cref="DataAccessException">In case of Hibernate errors</exception>
/// <exception cref="ArgumentException">If values and types are not null and their lengths are not equal</exception>
/// <exception cref="DataAccessException">In case of Hibernate errors</exception>
/// <exception cref="ArgumentException">If values and types are not null and their lengths are not equal</exception>
public IList<T> Find<T>(string queryString, object[] values, IType[] types)
{
if (values != null && types != null && values.Length != types.Length)
@@ -1009,7 +1009,7 @@ namespace Spring.Data.NHibernate.Generic
/// <returns>A generic List containing 0 or more persistent instances</returns>
/// <exception cref="DataAccessException">In case of Hibernate errors</exception>
/// <exception cref="ArgumentOutOfRangeException">If paramNames length is not equal to values length or
/// if paramNames length is not equal to types length (when types is not null)</exception>
/// if paramNames length is not equal to types length (when types is not null)</exception>
public IList<T> FindByNamedQueryAndNamedParam<T>(string queryName, string[] paramNames, object[] values,
IType[] types)
{
@@ -1050,7 +1050,7 @@ namespace Spring.Data.NHibernate.Generic
/// of the given object to <i>named</i> parameters in the query string.
/// </summary>
/// <typeparam name="T">The object type to find.</typeparam>
/// <param name="queryString">A query expressed in Hibernate's query language</param>
/// <param name="queryString">A query expressed in Hibernate's query language</param>
/// <param name="valueObject">The values of the parameters</param>
/// <returns>A generic List containing 0 or more persistent instances</returns>
/// <exception cref="DataAccessException">In case of Hibernate errors</exception>

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
* Copyright © 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
* Copyright © 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -70,7 +70,7 @@ namespace Spring.Data.NHibernate
/// as autodetected by Spring's <see cref="PersistenceExceptionTranslationPostProcessor"/>
/// for AOP-based translation of PersistenceExceptionTranslationPostProcessor.
/// Hence, the presence of e.g. LocalSessionFactoryBean automatically enables
/// a PersistenceExceptionTranslationPostProcessor to translate Hibernate exceptions.
/// a PersistenceExceptionTranslationPostProcessor to translate Hibernate exceptions.
/// </para>
/// </remarks>
/// <author>Mark Pollack (.NET)</author>
@@ -117,7 +117,7 @@ namespace Spring.Data.NHibernate
private IApplicationContext applicationContext;
// Configuration time DB provider.
// Configuration time DB provider.
// This will not be available after configuration has been done.
private static IDbProvider configTimeDbProvider;
@@ -508,7 +508,7 @@ namespace Spring.Data.NHibernate
IDictionary<string, string> typedProperties = new Dictionary<string, string>();
foreach (KeyValuePair<string, string> entry in hibernateProperties)
{
typedProperties.Add((string) entry.Key, (string) entry.Value);
typedProperties.Add(entry.Key, entry.Value);
}
Dialect dialect = Dialect.GetDialect(typedProperties);
@@ -545,7 +545,7 @@ namespace Spring.Data.NHibernate
log.Info("Overriding use of Spring's Hibernate Connection Provider with [" +
hibernateProperties[Environment.ConnectionProvider] + "]");
}
#endregion
#endregion
config.Properties.Remove(Environment.ConnectionProvider);
}
@@ -625,7 +625,7 @@ namespace Spring.Data.NHibernate
}
}
if (this.eventListeners != null)
if (this.eventListeners != null)
{
// Register specified NHibernate event listeners.
foreach (DictionaryEntry entry in eventListeners)
@@ -641,7 +641,7 @@ namespace Spring.Data.NHibernate
}
object listenerObject = entry.Value;
if (listenerObject is ICollection)
if (listenerObject is ICollection)
{
ICollection listeners = (ICollection) listenerObject;
EventListeners listenerRegistry = config.EventListeners;
@@ -651,7 +651,7 @@ namespace Spring.Data.NHibernate
object[] listenerArray = (object[])items.ToArray(listenerRegistry.GetListenerClassFor(listenerType));
config.SetListeners(listenerType, listenerArray);
}
else
else
{
config.SetListener(listenerType, listenerObject);
}
@@ -694,8 +694,8 @@ namespace Spring.Data.NHibernate
if (log.IsInfoEnabled)
{
log.Info("Closing Hibernate SessionFactory");
}
#endregion
}
#endregion
sessionFactory.Close();
}
@@ -753,7 +753,7 @@ namespace Spring.Data.NHibernate
UpdateDatabaseSchema();
}
}
/// <summary>
/// Execute schema drop script, determined by the Configuration object
/// used for creating the SessionFactory. A replacement for NHibernate's
@@ -781,7 +781,7 @@ namespace Spring.Data.NHibernate
ExecuteSchemaScript(con, sql);
return null;
}));
}
/// <summary>
@@ -810,8 +810,8 @@ namespace Spring.Data.NHibernate
string[] sql = Configuration.GenerateSchemaCreationScript(dialect);
ExecuteSchemaScript(con, sql);
return null;
}));
}));
}
/// <summary>
@@ -829,7 +829,7 @@ namespace Spring.Data.NHibernate
/// connection to perform the script.
/// </p>
/// </remarks>
public virtual void UpdateDatabaseSchema()
public virtual void UpdateDatabaseSchema()
{
log.Info("Updating database schema for Hibernate SessionFactory");
HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory);
@@ -859,17 +859,17 @@ namespace Spring.Data.NHibernate
/// <param name="sql">The SQL statement to execute.</param>
protected virtual void ExecuteSchemaScript(IDbConnection con, string[] sql)
{
if (sql != null && sql.Length > 0)
if (sql != null && sql.Length > 0)
{
IDbCommand cmd = con.CreateCommand();
try
try
{
for (int i = 0; i < sql.Length; i++)
for (int i = 0; i < sql.Length; i++)
{
ExecuteSchemaStatement(cmd, sql[i]);
}
}
finally
finally
{
AdoUtils.DisposeCommand(cmd);
}
@@ -887,18 +887,18 @@ namespace Spring.Data.NHibernate
/// <param name="sql"></param>
protected virtual void ExecuteSchemaStatement(IDbCommand cmd, string sql)
{
if (log.IsDebugEnabled)
if (log.IsDebugEnabled)
{
log.Debug("Executing schema statement: " + sql);
}
try
try
{
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
catch (ADOException ex)
catch (ADOException ex)
{
if (log.IsWarnEnabled)
if (log.IsWarnEnabled)
{
log.Warn("Unsuccessful schema statement: " + sql, ex);
}
@@ -921,7 +921,7 @@ namespace Spring.Data.NHibernate
{
ISessionFactory sf = config.BuildSessionFactory();
ISessionFactoryImplementor sfImplementor = sf as ISessionFactoryImplementor;
if (sfImplementor != null)
{
DbProviderWrapper dbProviderWrapper = sfImplementor.ConnectionProvider as DbProviderWrapper;
@@ -997,7 +997,7 @@ namespace Spring.Data.NHibernate
/// </returns>
/// <seealso cref="PersistenceExceptionTranslationPostProcessor"/>
public DataAccessException TranslateExceptionIfPossible(Exception ex)
{
{
if (ex is HibernateException)
{
return ConvertHibernateException((HibernateException) ex);
@@ -1032,7 +1032,7 @@ namespace Spring.Data.NHibernate
/// </returns>
protected virtual DataAccessException ConvertAdoAccessException(ADOException ex)
{
return SessionFactoryUtils.ConvertAdoAccessException(AdoExceptionTranslator, ex);
return SessionFactoryUtils.ConvertAdoAccessException(AdoExceptionTranslator, ex);
}
#endregion

View File

@@ -36,11 +36,11 @@ namespace Spring.Web.UI.Controls
/// within the page.
/// </para>
/// <para>
/// In contrast to <see cref="Content"/> control, ContentReplacer can replace the content of
/// In contrast to <see cref="Content"/> control, ContentReplacer can replace the content of
/// any control within the current page - it is not limited to replacing ContentPlaceholders on master pages.
/// </para>
/// <para>
/// This technique is useful if you want to group e.g. rendering navigation elements on 1 ascx control, but your
/// This technique is useful if you want to group e.g. rendering navigation elements on 1 ascx control, but your
/// design requires navigation elements to be distributed across different places within the HTML code.
/// </para>
/// </remarks>
@@ -71,7 +71,7 @@ namespace Spring.Web.UI.Controls
if (!Visible) return;
//log.Debug(string.Format("OnPreRender Content['{0}']", this.contentPlaceHolderID));
Control ctlRoot = (this.Page.Master != null) ? (Control)this.Page.Master : (Control)this.Page;
Control ctlRoot = Page.Master != null ? Page.Master : (Control) Page;
Control ctl = ctlRoot.FindControl(this.contentPlaceHolderID);
if (ctl != null)
@@ -120,7 +120,7 @@ namespace Spring.Web.UI.Controls
private static readonly PropertyInfo piRareFieldsEnsured =
typeof(Control).GetProperty("RareFieldsEnsured", BindingFlags.NonPublic | BindingFlags.Instance);
private static readonly FieldInfo fiRenderMethod =
private static readonly FieldInfo fiRenderMethod =
typeof(Control).GetNestedType("ControlRareFields",BindingFlags.NonPublic).GetField("RenderMethod");
private RenderMethod GetRenderMethod()

View File

@@ -22,7 +22,7 @@
<NUnitVersion>3.10.1</NUnitVersion>
<NUnitTestAdapterVersion>3.10.0</NUnitTestAdapterVersion>
<RhinoMocksVersion>3.6.1</RhinoMocksVersion>
<FakeItEasyVersion>4.8.1</FakeItEasyVersion>
<MicrosoftTestSDKVersion>15.7.2</MicrosoftTestSDKVersion>
<TreatWarningsAsErrors>True</TreatWarningsAsErrors>
@@ -36,6 +36,7 @@
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugType>Full</DebugType>
<DefineConstants>DEBUG;TRACE;$(DefineConstants)</DefineConstants>
</PropertyGroup>

View File

@@ -18,18 +18,16 @@
#endregion
#region Imports
using System;
using System.Collections;
using System.Globalization;
using System.Reflection;
using AopAlliance.Intercept;
using NUnit.Framework;
using Rhino.Mocks;
#endregion
using FakeItEasy;
using NUnit.Framework;
namespace Spring.Aop.Framework
{
@@ -41,16 +39,13 @@ namespace Spring.Aop.Framework
[TestFixture]
public abstract class AbstractMethodInvocationTests
{
private MockRepository mocks;
[SetUp]
public virtual void SetUp()
{
mocks = new MockRepository();
}
protected abstract AbstractMethodInvocation CreateMethodInvocation(
object proxy, object target, MethodInfo method, MethodInfo onProxyMethod,
object proxy, object target, MethodInfo method, MethodInfo onProxyMethod,
object[] arguments, Type targetType, IList interceptors);
[Test]
@@ -178,7 +173,7 @@ namespace Spring.Aop.Framework
IMethodInterceptor interceptor = (IMethodInterceptor) repository.CreateMock(typeof (IMethodInterceptor));
AbstractMethodInvocation join = CreateMethodInvocation(
null, target, target.GetTargetMethodNoArgs(), null, null, target.GetType(), new object[] { interceptor });
Expect.Call(interceptor.Invoke(join)).Return(target.BullseyeMethod().ToLower(CultureInfo.InvariantCulture));
Expect.Call(interceptor.Invoke(join)).Returns(target.BullseyeMethod().ToLower(CultureInfo.InvariantCulture));
repository.ReplayAll();
string score = (string) join.Proceed();
Assert.AreEqual(target.BullseyeMethod().ToLower(CultureInfo.InvariantCulture) + Target.Suffix, score);
@@ -186,18 +181,14 @@ namespace Spring.Aop.Framework
*/
Target target = new Target();
IMethodInterceptor mock = (IMethodInterceptor) mocks.CreateMock(typeof(IMethodInterceptor));
IMethodInterceptor mock = A.Fake<IMethodInterceptor>();
AbstractMethodInvocation join = CreateMethodInvocation(
null, target, target.GetTargetMethodNoArgs(), null, null, target.GetType(), new object[] { mock });
Expect.Call(mock.Invoke(null)).IgnoreArguments().Return(target.BullseyeMethod().ToLower(CultureInfo.InvariantCulture));
mocks.ReplayAll();
A.CallTo(() => mock.Invoke(null)).WithAnyArguments().Returns(target.BullseyeMethod().ToLower(CultureInfo.InvariantCulture));
string score = (string) join.Proceed();
Assert.AreEqual(Target.DefaultScore.ToLower(CultureInfo.InvariantCulture) + Target.Suffix, score);
mocks.VerifyAll();
}
[Test]
@@ -222,53 +213,30 @@ namespace Spring.Aop.Framework
[Test]
public void UnwrapsTargetInvocationException_WithInterceptor()
{
BadCommand target = new BadCommand();
IMethodInterceptor mock = (IMethodInterceptor) mocks.CreateMock(typeof(IMethodInterceptor));
AbstractMethodInvocation join = CreateMethodInvocation(
null, target, target.GetTargetMethod(), null, null, target.GetType(), new object[] { mock });
Expect.Call(mock.Invoke(null)).IgnoreArguments().Return(null);
mocks.ReplayAll();
{
BadCommand target = new BadCommand();
IMethodInterceptor mock = A.Fake<IMethodInterceptor>();
AbstractMethodInvocation join = CreateMethodInvocation(
null, target, target.GetTargetMethod(), null, null, target.GetType(), new object[] {mock});
try
{
join.Proceed();
}
catch (NotImplementedException)
{
// this is good, we want this exception to bubble up...
}
catch (TargetInvocationException)
{
Assert.Fail("Must have unwrapped this.");
}
mocks.VerifyAll();
}
A.CallTo(() => mock.Invoke(null)).WithAnyArguments().Throws<NotImplementedException>();
[Test]
// we want this exception to bubble up...
Assert.Throws<NotImplementedException>(() => join.Proceed());
}
[Test]
public void UnwrapsTargetInvocationException_WithInterceptorThatThrowsAnException()
{
BadCommand target = new BadCommand();
IMethodInterceptor mock = (IMethodInterceptor) mocks.CreateMock(typeof(IMethodInterceptor));
IMethodInterceptor mock = A.Fake<IMethodInterceptor>();
AbstractMethodInvocation join = CreateMethodInvocation(
null, target, target.GetTargetMethod(), null, null, target.GetType(), new object[] { mock });
Expect.Call(mock.Invoke(null)).IgnoreArguments().Throw(new NotImplementedException());
mocks.ReplayAll();
try
{
join.Proceed();
}
catch (NotImplementedException)
{
// this is good, we want this exception to bubble up...
}
catch (TargetInvocationException)
{
Assert.Fail("Must have unwrapped this.");
}
mocks.VerifyAll();
A.CallTo(() => mock.Invoke(null)).WithAnyArguments().Throws<NotImplementedException>();
// we want this exception to bubble up...
Assert.Throws<NotImplementedException>(() => join.Proceed());
}
}
}

View File

@@ -18,48 +18,41 @@
#endregion
#region Imports
using System;
using AopAlliance.Intercept;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Util;
#endregion
using AopAlliance.Intercept;
using FakeItEasy;
using NUnit.Framework;
using Spring.Util;
namespace Spring.Aop.Framework.Adapter
{
/// <summary>
/// Unit tests for the AfterReturningAdviceInterceptor class.
/// </summary>
/// <author>Rod Johnson</author>
/// <author>Simon White (.NET)</author>
[TestFixture]
public sealed class AfterReturningAdviceInterceptorTests
{
[Test]
public void PassNullAdviceToCtor()
{
/// <summary>
/// Unit tests for the AfterReturningAdviceInterceptor class.
/// </summary>
/// <author>Rod Johnson</author>
/// <author>Simon White (.NET)</author>
[TestFixture]
public sealed class AfterReturningAdviceInterceptorTests
{
[Test]
public void PassNullAdviceToCtor()
{
Assert.Throws<ArgumentNullException>(() => new AfterReturningAdviceInterceptor(null));
}
}
[Test]
public void IsNotInvokedIfServiceObjectThrowsException()
{
MockRepository repository = new MockRepository();
IMethodInvocation mockInvocation = (IMethodInvocation)repository.CreateMock(typeof(IMethodInvocation));
IAfterReturningAdvice mockAdvice = (IAfterReturningAdvice)repository.CreateMock(typeof(IAfterReturningAdvice));
mockAdvice.AfterReturning(null, null, null, null);
LastCall.IgnoreArguments();
LastCall.Throw(new FormatException());
[Test]
public void IsNotInvokedIfServiceObjectThrowsException()
{
IMethodInvocation mockInvocation = A.Fake<IMethodInvocation>();
IAfterReturningAdvice mockAdvice = A.Fake<IAfterReturningAdvice>();
Expect.Call(mockInvocation.Method).Return(ReflectionUtils.GetMethod(typeof(object), "HashCode", new Type[] { }));
Expect.Call(mockInvocation.Arguments).Return(null);
Expect.Call(mockInvocation.This).Return(new object());
Expect.Call(mockInvocation.Proceed()).Return(null);
repository.ReplayAll();
A.CallTo(() => mockAdvice.AfterReturning(null, null, null, null)).WithAnyArguments().Throws<FormatException>();
A.CallTo(() => mockInvocation.Method).Returns(ReflectionUtils.GetMethod(typeof(object), "HashCode", new Type[] { }));
A.CallTo(() => mockInvocation.Arguments).Returns(null);
A.CallTo(() => mockInvocation.This).Returns(new object());
A.CallTo(() => mockInvocation.Proceed()).Returns(null);
try
{
@@ -70,29 +63,19 @@ namespace Spring.Aop.Framework.Adapter
catch (FormatException)
{
}
}
repository.VerifyAll();
}
[Test]
public void JustPassesAfterReturningAdviceExceptionUpWithoutAnyWrapping()
{
MockRepository repository = new MockRepository();
IMethodInvocation mockInvocation = (IMethodInvocation)repository.CreateMock(typeof(IMethodInvocation));
IAfterReturningAdvice mockAdvice = (IAfterReturningAdvice) repository.CreateMock(typeof (IAfterReturningAdvice));
mockAdvice.AfterReturning(null,null,null,null);
LastCall.IgnoreArguments();
LastCall.Throw(new FormatException());
Expect.Call(mockInvocation.Method).Return(ReflectionUtils.GetMethod(typeof(object), "HashCode", new Type[] { }));
Expect.Call(mockInvocation.Arguments).Return(null);
Expect.Call(mockInvocation.This).Return(new object());
Expect.Call(mockInvocation.Proceed()).Return(null);
repository.ReplayAll();
[Test]
public void JustPassesAfterReturningAdviceExceptionUpWithoutAnyWrapping()
{
IMethodInvocation mockInvocation = A.Fake<IMethodInvocation>();
IAfterReturningAdvice mockAdvice = A.Fake<IAfterReturningAdvice>();
A.CallTo(() => mockAdvice.AfterReturning(null, null, null, null)).WithAnyArguments().Throws<FormatException>();
A.CallTo(() => mockInvocation.Method).Returns(ReflectionUtils.GetMethod(typeof(object), "HashCode", new Type[] { }));
A.CallTo(() => mockInvocation.Arguments).Returns(null);
A.CallTo(() => mockInvocation.This).Returns(new object());
A.CallTo(() => mockInvocation.Proceed()).Returns(null);
try
{
AfterReturningAdviceInterceptor interceptor = new AfterReturningAdviceInterceptor(mockAdvice);
@@ -102,12 +85,6 @@ namespace Spring.Aop.Framework.Adapter
catch (FormatException)
{
}
repository.VerifyAll();
}
}
}
}
}

View File

@@ -18,18 +18,18 @@
#endregion
#region Imports
using System;
using System.Reflection;
using System.Runtime.Remoting;
using System.Web;
using AopAlliance.Intercept;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Util;
#endregion
using AopAlliance.Intercept;
using FakeItEasy;
using NUnit.Framework;
using Spring.Util;
namespace Spring.Aop.Framework.Adapter
{
@@ -56,21 +56,16 @@ namespace Spring.Aop.Framework.Adapter
[Test]
public void NotInvoked()
{
MockRepository repository = new MockRepository();
IMethodInvocation mi = (IMethodInvocation) repository.CreateMock(typeof (IMethodInvocation));
IMethodInvocation mi = A.Fake<IMethodInvocation>();
MyThrowsHandler th = new MyThrowsHandler();
ThrowsAdviceInterceptor ti = new ThrowsAdviceInterceptor(th);
object ret = new object();
Expect.Call(mi.Proceed()).Return(ret);
repository.ReplayAll();
A.CallTo(() => mi.Proceed()).Returns(ret);
Assert.AreEqual(ret, ti.Invoke(mi));
Assert.AreEqual(0, th.GetCalls());
repository.VerifyAll();
}
[Test]
@@ -81,10 +76,9 @@ namespace Spring.Aop.Framework.Adapter
Assert.AreEqual(2, ti.HandlerMethodCount);
Exception ex = new Exception();
MockRepository repository = new MockRepository();
IMethodInvocation mi = (IMethodInvocation)repository.CreateMock(typeof(IMethodInvocation));
Expect.Call(mi.Proceed()).Throw(ex);
repository.ReplayAll();
IMethodInvocation mi = A.Fake<IMethodInvocation>();
A.CallTo(() => mi.Proceed()).Throws(ex);
try
{
ti.Invoke(mi);
@@ -95,8 +89,6 @@ namespace Spring.Aop.Framework.Adapter
Assert.AreEqual(ex, caught);
}
Assert.AreEqual(0, th.GetCalls());
repository.VerifyAll();
}
[Test]
@@ -107,14 +99,13 @@ namespace Spring.Aop.Framework.Adapter
ThrowsAdviceInterceptor ti = new ThrowsAdviceInterceptor(th);
HttpException ex = new HttpException();
MockRepository repository = new MockRepository();
IMethodInvocation mi = (IMethodInvocation)repository.CreateMock(typeof(IMethodInvocation));
IMethodInvocation mi = A.Fake<IMethodInvocation>();
A.CallTo(() => mi.Method).Returns(ReflectionUtils.GetMethod(typeof (object), "HashCode", new Type[] {}));
A.CallTo(() => mi.Arguments).Returns(null);
A.CallTo(() => mi.This).Returns(new object());
A.CallTo(() => mi.Proceed()).Throws(ex);
Expect.Call(mi.Method).Return(ReflectionUtils.GetMethod(typeof (object), "HashCode", new Type[] {}));
Expect.Call(mi.Arguments).Return(null);
Expect.Call(mi.This).Return(new object());
Expect.Call(mi.Proceed()).Throw(ex);
repository.ReplayAll();
try
{
ti.Invoke(mi);
@@ -126,9 +117,6 @@ namespace Spring.Aop.Framework.Adapter
}
Assert.AreEqual(1, th.GetCalls());
Assert.AreEqual(1, th.GetCalls("HttpException"));
repository.VerifyAll();
}
[Test]
@@ -138,10 +126,10 @@ namespace Spring.Aop.Framework.Adapter
ThrowsAdviceInterceptor throwsInterceptor = new ThrowsAdviceInterceptor(throwsHandler);
// nest the exceptions; make sure the advice gets applied because of the inner exception...
Exception exception = new FormatException("Parent", new HttpException("Inner"));
MockRepository repository = new MockRepository();
IMethodInvocation invocation = (IMethodInvocation)repository.CreateMock(typeof(IMethodInvocation));
Expect.Call(invocation.Proceed()).Throw(exception);
repository.ReplayAll();
IMethodInvocation invocation = A.Fake<IMethodInvocation>();
A.CallTo(() => invocation.Proceed()).Throws(exception);
try
{
throwsInterceptor.Invoke(invocation);
@@ -157,8 +145,7 @@ namespace Spring.Aop.Framework.Adapter
Assert.AreEqual(0, throwsHandler.GetCalls("HttpException"),
"Similarly, must NOT have been handled, 'cos the HttpException was wrapped by " +
"another Exception that did not have a handler.");
repository.VerifyAll();
}
}
[Test]
public void ChokesOnHandlerWhereMultipleMethodsAreApplicable()
@@ -175,10 +162,9 @@ namespace Spring.Aop.Framework.Adapter
// Extends RemotingException
RemotingTimeoutException ex = new RemotingTimeoutException();
MockRepository repository = new MockRepository();
IMethodInvocation mi = (IMethodInvocation)repository.CreateMock(typeof(IMethodInvocation));
Expect.Call(mi.Proceed()).Throw(ex);
repository.ReplayAll();
IMethodInvocation mi = A.Fake<IMethodInvocation>();
A.CallTo(() => mi.Proceed()).Throws(ex);
try
{
ti.Invoke(mi);
@@ -190,8 +176,6 @@ namespace Spring.Aop.Framework.Adapter
}
Assert.AreEqual(1, th.GetCalls());
Assert.AreEqual(1, th.GetCalls("RemotingException"));
repository.VerifyAll();
}
[Test]
@@ -200,13 +184,10 @@ namespace Spring.Aop.Framework.Adapter
Exception exception = new Exception();
MyThrowsHandler handler = new ThrowingMyHandler(exception);
ThrowsAdviceInterceptor interceptor = new ThrowsAdviceInterceptor(handler);
// extends RemotingException...
RemotingTimeoutException ex = new RemotingTimeoutException();
MockRepository repository = new MockRepository();
IMethodInvocation mi = (IMethodInvocation)repository.CreateMock(typeof(IMethodInvocation));
Expect.Call(mi.Proceed()).Throw(ex);
repository.ReplayAll();
IMethodInvocation mi = A.Fake<IMethodInvocation>();
A.CallTo(() => mi.Proceed()).Throws(new RemotingTimeoutException());
try
{
interceptor.Invoke(mi);
@@ -217,9 +198,7 @@ namespace Spring.Aop.Framework.Adapter
Assert.AreEqual(exception, caught);
}
Assert.AreEqual(1, handler.GetCalls());
Assert.AreEqual(1, handler.GetCalls("RemotingException"));
repository.VerifyAll();
Assert.AreEqual(1, handler.GetCalls("RemotingException"));
}
#region Helper Classes

View File

@@ -18,8 +18,6 @@
#endregion
#region Imports
using System;
using System.IO;
using System.Runtime.Serialization;
@@ -32,7 +30,9 @@ using System.Runtime.Remoting;
using AopAlliance.Aop;
using AopAlliance.Intercept;
using Rhino.Mocks;
using FakeItEasy;
using Spring.Aop.Framework.Adapter;
using Spring.Aop.Interceptor;
using Spring.Aop.Support;
@@ -44,8 +44,6 @@ using Spring.Util;
using NUnit.Framework;
#endregion
namespace Spring.Aop.Framework.DynamicProxy
{
/// <summary>
@@ -288,19 +286,19 @@ namespace Spring.Aop.Framework.DynamicProxy
[Test(Description = "http://jira.springframework.org/browse/SPRNET-1174")]
public void ImplementsInterfaceHierarchy()
{
IMethodInterceptor mi = MockRepository.GenerateMock<IMethodInterceptor>();
IMethodInterceptor mi = A.Fake<IMethodInterceptor>();
mi.Stub(x => x.Invoke(Arg<IMethodInvocation>.Is.NotNull)).Return((long)5).Repeat.Once();
mi.Stub(x => x.Invoke(Arg<IMethodInvocation>.Is.NotNull)).Return("Customer Name").Repeat.Once();
mi.Stub(x => x.Invoke(Arg<IMethodInvocation>.Is.NotNull)).Return("Customer Company").Repeat.Once();
A.CallTo(() => mi.Invoke(A<IMethodInvocation>.That.Matches(x => x.Method.Name == "get_Id"))).Returns((long) 5).Once();
A.CallTo(() => mi.Invoke(A<IMethodInvocation>.That.Matches(x => x.Method.Name == "get_Name"))).Returns("Customer Name").Once();
A.CallTo(() => mi.Invoke(A<IMethodInvocation>.That.Matches(x => x.Method.Name == "get_Company"))).Returns("Customer Company").Once();
AdvisedSupport advised = new AdvisedSupport();
advised.AddAdvice(mi);
advised.Interfaces = new Type[] { typeof(ITestCustomer) };
advised.Interfaces = new[] { typeof(ITestCustomer) };
ITestCustomer to = CreateProxy(advised) as ITestCustomer;
Assert.IsNotNull(to);
Assert.AreEqual((long)5, to.Id, "Incorrect Id");
Assert.AreEqual((long) 5, to.Id, "Incorrect Id");
Assert.AreEqual("Customer Name", to.Name, "Incorrect Name");
Assert.AreEqual("Customer Company", to.Company, "Incorrect Company");
}
@@ -407,8 +405,8 @@ namespace Spring.Aop.Framework.DynamicProxy
public void InterceptorHandledCallWithNoTarget()
{
int age = 26;
IMethodInterceptor mock = MockRepository.GenerateMock<IMethodInterceptor>();
mock.Stub(x => x.Invoke(Arg<IMethodInvocation>.Is.NotNull)).Return(age);
IMethodInterceptor mock = A.Fake<IMethodInterceptor>();
A.CallTo(() => mock.Invoke(A<IMethodInvocation>.That.Not.IsNull())).Returns(age);
AdvisedSupport advised = new AdvisedSupport();
advised.AddAdvice(mock);

View File

@@ -18,20 +18,18 @@
#endregion
#region Imports
using System;
using System.Collections;
using System.Reflection;
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Aop.Interceptor;
using Spring.Aop.Support;
using Spring.Collections;
using Spring.Objects;
#endregion
namespace Spring.Aop.Framework.DynamicProxy
{
/// <summary>
@@ -42,12 +40,9 @@ namespace Spring.Aop.Framework.DynamicProxy
[TestFixture]
public sealed class AopUtilsTests
{
private MockRepository mocks;
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
}
[Test]
@@ -80,17 +75,17 @@ namespace Spring.Aop.Framework.DynamicProxy
{
IPointcut pointcut = new OneInterfaceTestPointcut();
// Will return true if we're proxying interfaces including ITestObject
// Will return true if we're proxying interfaces including ITestObject
Assert.IsTrue(AopUtils.CanApply(pointcut, typeof (TestObject), new Type[] {typeof (ITestObject), typeof (IComparable)}));
// Will return true if we're proxying interfaces including ITestObject
// Will return true if we're proxying interfaces including ITestObject
Assert.IsFalse(AopUtils.CanApply(pointcut, typeof (TestObject), new Type[] {typeof (IComparable)}));
}
[Test]
public void CanApplyWithAdvisorYieldsTrueIfAdvisorIsNotKnownAdvisorType()
{
IAdvisor advisor = (IAdvisor) mocks.CreateMock(typeof (IAdvisor));
IAdvisor advisor = A.Fake<IAdvisor>();
Assert.IsTrue(AopUtils.CanApply(advisor, typeof (TestObject), null));
}
@@ -171,12 +166,10 @@ namespace Spring.Aop.Framework.DynamicProxy
[Test]
public void CanApplyWithTrueIntroductionAdvisor()
{
IIntroductionAdvisor mockIntroAdvisor = (IIntroductionAdvisor) mocks.CreateMock(typeof(IIntroductionAdvisor));
Expect.Call(mockIntroAdvisor.TypeFilter).Return(TrueTypeFilter.True);
mocks.ReplayAll();
IIntroductionAdvisor mockIntroAdvisor = A.Fake<IIntroductionAdvisor>();
A.CallTo(() => mockIntroAdvisor.TypeFilter).Returns(TrueTypeFilter.True);
Assert.IsTrue(AopUtils.CanApply(mockIntroAdvisor, typeof (TestObject), null));
mocks.VerifyAll();
}
#region Helper Classes

View File

@@ -31,8 +31,10 @@ using System.Web;
using AopAlliance.Aop;
using AopAlliance.Intercept;
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Aop.Advice;
using Spring.Aop.Framework.Adapter;
using Spring.Aop.Interceptor;
@@ -61,17 +63,14 @@ namespace Spring.Aop.Framework
[TestFixture]
public sealed class ProxyFactoryObjectTests
{
private MockRepository mocks;
private IObjectFactory factory;
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
factory = new XmlObjectFactory(new ReadOnlyXmlTestResource("proxyFactoryTests.xml", GetType()));
}
[Test]
public void TargetThrowsInvalidCastException()
{
@@ -477,9 +476,8 @@ namespace Spring.Aop.Framework
public void IsSingletonFalseReturnsNew_ProxyInstance_NotNewProxyTargetSource()
{
GoodCommand target = new GoodCommand();
IObjectFactory mock = (IObjectFactory) mocks.CreateMock(typeof(IObjectFactory));
Expect.Call(mock.GetObject("singleton")).Return(target).Repeat.Twice();
mocks.ReplayAll();
IObjectFactory mock = A.Fake<IObjectFactory>();
A.CallTo(() => mock.GetObject("singleton")).Returns(target).Twice();
ProxyFactoryObject fac = new ProxyFactoryObject();
fac.ProxyInterfaces = new string[] { typeof(ICommand).FullName };
@@ -491,17 +489,14 @@ namespace Spring.Aop.Framework
ICommand one = (ICommand)fac.GetObject();
ICommand two = (ICommand)fac.GetObject();
Assert.IsFalse(ReferenceEquals(one, two));
mocks.VerifyAll();
}
[Test]
public void IsSingletonTrueReturnsNew_ProxyInstance_NotNewProxyTargetSource()
{
GoodCommand target = new GoodCommand();
IObjectFactory mock = (IObjectFactory)mocks.CreateMock(typeof(IObjectFactory));
Expect.Call(mock.GetObject("singleton")).Return(target);
mocks.ReplayAll();
IObjectFactory mock = A.Fake<IObjectFactory>();
A.CallTo(() => mock.GetObject("singleton")).Returns(target);
ProxyFactoryObject fac = new ProxyFactoryObject();
fac.ProxyInterfaces = new string[] { typeof(ICommand).FullName };
@@ -513,8 +508,6 @@ namespace Spring.Aop.Framework
ICommand one = (ICommand)fac.GetObject();
ICommand two = (ICommand)fac.GetObject();
Assert.IsTrue(ReferenceEquals(one, two));
mocks.VerifyAll();
}
private ProxyFactoryObject CreateFrozenProxyFactory()
@@ -562,11 +555,10 @@ namespace Spring.Aop.Framework
GoodCommand target = new GoodCommand();
NopInterceptor advice = new NopInterceptor();
IObjectFactory mock = (IObjectFactory) mocks.CreateMock(typeof(IObjectFactory));
Expect.Call(mock.GetObject("advice")).Return(advice);
Expect.Call(mock.GetObject("singleton")).Return(target);
Expect.Call(mock.GetType("singleton")).Return(typeof(GoodCommand));
mocks.ReplayAll();
IObjectFactory mock = A.Fake<IObjectFactory>();
A.CallTo(() => mock.GetObject("advice")).Returns(advice);
A.CallTo(() => mock.GetObject("singleton")).Returns(target);
A.CallTo(() => mock.GetType("singleton")).Returns(typeof(GoodCommand));
ProxyFactoryObject fac = new ProxyFactoryObject();
fac.ProxyInterfaces = new string[] { typeof(ICommand).FullName };
@@ -581,8 +573,6 @@ namespace Spring.Aop.Framework
Assert.AreEqual(1, advice.Count);
two.Execute();
Assert.AreEqual(2, advice.Count);
mocks.VerifyAll();
}
[Test]
@@ -591,32 +581,20 @@ namespace Spring.Aop.Framework
GoodCommand target = new GoodCommand();
NopInterceptor advice = new NopInterceptor();
MockRepository mocks = new MockRepository();
IObjectFactory factory = (IObjectFactory) mocks.CreateMock(typeof(IObjectFactory));
IObjectFactory factory = A.Fake<IObjectFactory>();
ProxyFactoryObject fac = new ProxyFactoryObject();
fac.ProxyInterfaces = new string[] { typeof(ICommand).FullName };
fac.ProxyInterfaces = new[] {typeof(ICommand).FullName};
fac.IsSingleton = false;
fac.InterceptorNames = new string[] { "advice", "prototype" };
fac.InterceptorNames = new[] {"advice", "prototype"};
fac.ObjectFactory = factory;
// using (mocks.Record())
{
using (mocks.Unordered())
{
Expect.Call(factory.IsSingleton("advice")).Return(true);
Expect.Call(factory.GetObject("advice")).Return(advice);
Expect.Call(factory.GetType("prototype")).Return(target.GetType());
Expect.Call(factory.GetObject("prototype")).Return(target);
}
}
mocks.ReplayAll();
A.CallTo(() => factory.IsSingleton("advice")).Returns(true);
A.CallTo(() => factory.GetObject("advice")).Returns(advice);
A.CallTo(() => factory.GetType("prototype")).Returns(target.GetType());
A.CallTo(() => factory.GetObject("prototype")).Returns(target);
// using(mocks.Playback())
{
fac.GetObject();
}
mocks.VerifyAll();
fac.GetObject();
}
[Test]
@@ -706,26 +684,20 @@ namespace Spring.Aop.Framework
[Test]
public void NullNameInInterceptorNamesArrayThrowAopConfigException()
{
IObjectFactory factory = (IObjectFactory) mocks.CreateMock(typeof(IObjectFactory));
IObjectFactory factory = A.Fake<IObjectFactory>();
ProxyFactoryObject fac = new ProxyFactoryObject();
fac.ProxyInterfaces = new string[] { typeof(ICommand).FullName };
fac.IsSingleton = false;
fac.InterceptorNames = new string[] { null, null };
fac.ObjectFactory = factory;
try
{
fac.GetObject();
Assert.Fail();
}
catch (AopConfigException)
{}
Assert.Throws<AopConfigException>(() => fac.GetObject());
}
[Test]
public void PassEmptyInterceptorNamesArray_WithTargetThatImplementsAnInterfaceCanBeCastToSaidInterface()
{
IObjectFactory factory = (IObjectFactory) mocks.CreateMock(typeof(IObjectFactory));
IObjectFactory factory = A.Fake<IObjectFactory>();
ProxyFactoryObject fac = new ProxyFactoryObject();
fac.ProxyInterfaces = new string[] { };

View File

@@ -18,21 +18,19 @@
#endregion
#region Imports
using System;
using System.Runtime.Serialization;
using AopAlliance.Aop;
using AopAlliance.Intercept;
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Aop.Interceptor;
using Spring.Aop.Support;
using Spring.Objects;
using Spring.Util;
#endregion
namespace Spring.Aop.Framework
{
/// <summary>
@@ -44,15 +42,6 @@ namespace Spring.Aop.Framework
[TestFixture]
public sealed class ProxyFactoryTests
{
private MockRepository mocks;
[SetUp]
public void Setup()
{
mocks = new MockRepository();
}
public interface IDoubleClickable
{
event EventHandler DoubleClick;
@@ -132,7 +121,7 @@ namespace Spring.Aop.Framework
object proxy = pf.GetProxy();
}
// fails when running in resharper/testdriven.net
// fails when running in resharper/testdriven.net
// DynamicProxyManager.SaveAssembly();
}
@@ -523,24 +512,21 @@ namespace Spring.Aop.Framework
//MLP SPRNET-1367
//IDynamicMock mock = new DynamicMock(typeof(IAdvisedSupportListener));
//IAdvisedSupportListener listener = (IAdvisedSupportListener)mock.Object;
IAdvisedSupportListener listener =
(IAdvisedSupportListener) mocks.CreateMock(typeof (IAdvisedSupportListener));
listener.Activated(null);
LastCall.On(listener).IgnoreArguments();
IAdvisedSupportListener listener = A.Fake<IAdvisedSupportListener>();
//listener.Activated();
//mock.Expect("Activated");
mocks.ReplayAll();
ProxyFactory factory = new ProxyFactory(new TestObject());
factory.AddListener(listener);
factory.GetProxy();
mocks.VerifyAll();
A.CallTo(() => listener.Activated(A<AdvisedSupport>._)).MustHaveHappened();
}
[Test]
public void AdvisedSupportListenerMethodsAreCalledAppropriately()
{
IAdvisedSupportListener listener = MockRepository.GenerateMock<IAdvisedSupportListener>();
IAdvisedSupportListener listener = A.Fake<IAdvisedSupportListener>();
ProxyFactory factory = new ProxyFactory(new TestObject());
factory.AddListener(listener);
@@ -552,15 +538,15 @@ namespace Spring.Aop.Framework
// must fire the InterfacesChanged callback...
factory.AddInterface(typeof(ISerializable));
listener.AssertWasCalled(x => x.Activated(Arg<AdvisedSupport>.Is.NotNull));
listener.AssertWasCalled(x => x.AdviceChanged(Arg<AdvisedSupport>.Is.NotNull));
listener.AssertWasCalled(x => x.InterfacesChanged(Arg<AdvisedSupport>.Is.NotNull));
A.CallTo(() => listener.Activated(A<AdvisedSupport>.That.Not.IsNull())).MustHaveHappened();
A.CallTo(() => listener.AdviceChanged(A<AdvisedSupport>.That.Not.IsNull())).MustHaveHappened();
A.CallTo(() => listener.InterfacesChanged(A<AdvisedSupport>.That.Not.IsNull())).MustHaveHappened();
}
[Test]
public void AdvisedSupportListenerMethodsAre_NOT_CalledIfProxyHasNotBeenCreated()
{
IAdvisedSupportListener listener = MockRepository.GenerateMock<IAdvisedSupportListener>();
IAdvisedSupportListener listener = A.Fake<IAdvisedSupportListener>();
ProxyFactory factory = new ProxyFactory(new TestObject());
factory.AddListener(listener);
@@ -570,8 +556,8 @@ namespace Spring.Aop.Framework
// must not fire the InterfacesChanged callback...
factory.AddInterface(typeof(ISerializable));
listener.AssertWasNotCalled(x => x.AdviceChanged(Arg<AdvisedSupport>.Is.Anything));
listener.AssertWasNotCalled(x => x.InterfacesChanged(Arg<AdvisedSupport>.Is.Anything));
A.CallTo(() => listener.AdviceChanged(A<AdvisedSupport>._)).MustNotHaveHappened();
A.CallTo(() => listener.InterfacesChanged(A<AdvisedSupport>._)).MustNotHaveHappened();
}
[Test]
@@ -591,7 +577,7 @@ namespace Spring.Aop.Framework
[Test]
public void RemoveAdvisedSupportListener()
{
IAdvisedSupportListener listener = MockRepository.GenerateMock<IAdvisedSupportListener>();
IAdvisedSupportListener listener = A.Fake<IAdvisedSupportListener>();
ProxyFactory factory = new ProxyFactory(new TestObject());
factory.AddListener(listener);
@@ -600,9 +586,9 @@ namespace Spring.Aop.Framework
factory.GetProxy();
// check that no lifecycle callback methods were invoked on the listener...
listener.AssertWasNotCalled(x => x.Activated(Arg<AdvisedSupport>.Is.Anything));
listener.AssertWasNotCalled(x => x.AdviceChanged(Arg<AdvisedSupport>.Is.Anything));
listener.AssertWasNotCalled(x => x.InterfacesChanged(Arg<AdvisedSupport>.Is.Anything));
A.CallTo(() => listener.Activated(null)).WithAnyArguments().MustNotHaveHappened();
A.CallTo(() => listener.AdviceChanged(null)).WithAnyArguments().MustNotHaveHappened();
A.CallTo(() => listener.InterfacesChanged(null)).WithAnyArguments().MustNotHaveHappened();
}
[Test]
@@ -657,7 +643,7 @@ namespace Spring.Aop.Framework
NopInterceptor diUnused = new NopInterceptor(1); // // make instance unique (see SPRNET-847)
TestCountingIntroduction countingMixin = new TestCountingIntroduction();
pf1.AddAdvice(diUnused);
pf1.AddAdvice(diUnused);
pf1.AddAdvisor(new DefaultPointcutAdvisor(di));
pf1.AddIntroduction(new DefaultIntroductionAdvisor(countingMixin));

View File

@@ -1,13 +1,13 @@
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
*
* 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.
@@ -16,14 +16,14 @@
*/
#endregion
#region Imports
using System;
using NUnit.Framework;
using AopAlliance.Aop;
using Rhino.Mocks;
using FakeItEasy;
using Spring.Aop.Framework;
using Spring.Objects;
#endregion
namespace Spring.Aop.Support
{
@@ -58,9 +58,9 @@ namespace Spring.Aop.Support
TestObject raw = new TestObject();
Assert.IsTrue(! (raw is ITimeStamped));
ProxyFactory factory = new ProxyFactory(raw);
ITimeStampedIntroduction ts = MockRepository.GenerateMock<ITimeStampedIntroduction>();
ts.Stub(x => x.TimeStamp).Return(EXPECTED_TIMESTAMP);
ITimeStampedIntroduction ts = A.Fake<ITimeStampedIntroduction>();
A.CallTo(() => ts.TimeStamp).Returns(EXPECTED_TIMESTAMP);
DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor(ts);
factory.AddIntroduction(advisor);
@@ -74,17 +74,18 @@ namespace Spring.Aop.Support
public interface ISubTimeStampedIntroduction: ISubTimeStamped, IAdvice
{
}
public void TestIntroductionInterceptorWithInterfaceHierarchy()
[Test]
public void TestIntroductionInterceptorWithInterfaceHierarchy()
{
TestObject raw = new TestObject();
Assert.IsTrue(! (raw is ISubTimeStamped));
ProxyFactory factory = new ProxyFactory(raw);
ISubTimeStampedIntroduction ts = MockRepository.GenerateMock<ISubTimeStampedIntroduction>();
ts.Stub(x => x.TimeStamp).Return(EXPECTED_TIMESTAMP);
ISubTimeStampedIntroduction ts = A.Fake<ISubTimeStampedIntroduction>();
A.CallTo(() => ts.TimeStamp).Returns(EXPECTED_TIMESTAMP);
DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor(ts);
DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor(ts);
// we must add introduction, not an advisor
factory.AddIntroduction(advisor);
@@ -93,17 +94,18 @@ namespace Spring.Aop.Support
Assert.IsTrue(tsp.TimeStamp == EXPECTED_TIMESTAMP);
}
public void TestIntroductionInterceptorWithSuperInterface()
[Test]
public void TestIntroductionInterceptorWithSuperInterface()
{
TestObject raw = new TestObject();
Assert.IsTrue(! (raw is ITimeStamped));
ProxyFactory factory = new ProxyFactory(raw);
ISubTimeStamped ts = MockRepository.GenerateMock<ISubTimeStampedIntroduction>();
ts.Stub(x => x.TimeStamp).Return(EXPECTED_TIMESTAMP);
ISubTimeStampedIntroduction ts = A.Fake<ISubTimeStampedIntroduction>();
A.CallTo(() => ts.TimeStamp).Returns(EXPECTED_TIMESTAMP);
factory.AddIntroduction(0, new DefaultIntroductionAdvisor(
(ISubTimeStampedIntroduction)ts,
factory.AddIntroduction(0, new DefaultIntroductionAdvisor(
ts,
typeof(ITimeStamped))
);
@@ -121,42 +123,42 @@ namespace Spring.Aop.Support
{
private DateTime _timestamp;
public Test(DateTime timestamp)
public Test(DateTime timestamp)
{
_timestamp = timestamp;
}
public void Foo()
public void Foo()
{
}
public DateTime TimeStamp
public DateTime TimeStamp
{
get
get
{
return _timestamp;
}
}
}
public void TestAutomaticInterfaceRecognitionInDelegate()
public void TestAutomaticInterfaceRecognitionInDelegate()
{
IIntroductionAdvisor ia = new DefaultIntroductionAdvisor(new Test(EXPECTED_TIMESTAMP));
TestObject target = new TestObject();
ProxyFactory pf = new ProxyFactory(target);
pf.AddIntroduction(0, ia);
ITimeStamped ts = (ITimeStamped) pf.GetProxy();
Assert.IsTrue(ts.TimeStamp == EXPECTED_TIMESTAMP);
((ITest) ts).Foo();
int age = ((ITestObject) ts).Age;
}
/*
* The rest of the tests in the original tested subclassing the
* DelegatingIntroductionInterceptor.
*
*
* Since we don't need to subclass anything to make a delegating
* introduction, the rest of the tests are not necessary.
*/
@@ -164,12 +166,12 @@ namespace Spring.Aop.Support
// must be public to be used for AOP
// AOP creates a new assembly which must have access to the
// interfaces that it intends to expose.
public interface ITest
public interface ITest
{
void Foo();
}
public interface ISubTimeStamped : ITimeStamped
public interface ISubTimeStamped : ITimeStamped
{
}

View File

@@ -18,17 +18,17 @@
#endregion
#region Imports
using System;
using Common.Logging;
using Common.Logging.Simple;
using FakeItEasy;
using NUnit.Framework;
using Spring.Objects.Factory;
using Spring.Objects.Factory.Xml;
using Rhino.Mocks;
#endregion
namespace Spring.Aop.Target
{
@@ -79,24 +79,16 @@ namespace Spring.Aop.Target
[Test]
public void TargetType()
{
MockRepository mocks = new MockRepository();
SideEffectObject target = new SideEffectObject();
IObjectFactory factory = mocks.CreateMock<IObjectFactory>();
IObjectFactory factory = A.Fake<IObjectFactory>();
using (mocks.Record())
{
Expect.Call(factory.IsPrototype(null)).Return(true);
Expect.Call(factory.GetType(null)).Return(typeof(SideEffectObject));
}
using (mocks.Playback())
{
PrototypeTargetSource source = new PrototypeTargetSource();
source.ObjectFactory = factory;
Assert.AreEqual(target.GetType(), source.TargetType, "Wrong TargetType being returned.");
}
A.CallTo(() => factory.IsPrototype(null)).Returns(true);
A.CallTo(() => factory.GetType(null)).Returns(typeof(SideEffectObject));
PrototypeTargetSource source = new PrototypeTargetSource();
source.ObjectFactory = factory;
Assert.AreEqual(target.GetType(), source.TargetType, "Wrong TargetType being returned.");
}
[Test]
@@ -109,49 +101,30 @@ namespace Spring.Aop.Target
[Test]
public void WithNonSingletonTargetObject()
{
MockRepository mocks = new MockRepository();
IObjectFactory factory = mocks.CreateMock<IObjectFactory>();
IObjectFactory factory = A.Fake<IObjectFactory>();
const string objectName = "Foo";
using (mocks.Record())
{
Expect.Call(factory.IsPrototype(objectName)).Return(false);
}
A.CallTo(() => factory.IsPrototype(objectName)).Returns(false);
PrototypeTargetSource source = new PrototypeTargetSource();
source.TargetObjectName = objectName;
using (mocks.Playback())
{
PrototypeTargetSource source = new PrototypeTargetSource();
source.TargetObjectName = objectName;
Assert.Throws<ObjectDefinitionStoreException>(delegate { source.ObjectFactory = factory; });
}
Assert.Throws<ObjectDefinitionStoreException>(delegate { source.ObjectFactory = factory; });
}
[Test]
public void GetTarget()
{
MockRepository mocks = new MockRepository();
IObjectFactory factory = mocks.CreateMock<IObjectFactory>();
IObjectFactory factory = A.Fake<IObjectFactory>();
SideEffectObject target = new SideEffectObject();
A.CallTo(() => factory.IsPrototype("foo")).Returns(true);
A.CallTo(() => factory.GetObject("foo")).Returns(target);
A.CallTo(() => factory.GetType("foo")).Returns(typeof(string));
using (mocks.Record())
{
Expect.Call(factory.IsPrototype("foo")).Return(true);
Expect.Call(factory.GetObject("foo")).Return(target);
Expect.Call(factory.GetType("foo")).Return(typeof(string));
}
using (mocks.Playback())
{
PrototypeTargetSource source = new PrototypeTargetSource();
source.TargetObjectName = "foo";
source.ObjectFactory = factory;
Assert.IsTrue(object.ReferenceEquals(source.GetTarget(), target),
"Initial target source reference not being returned by GetTarget().");
}
PrototypeTargetSource source = new PrototypeTargetSource();
source.TargetObjectName = "foo";
source.ObjectFactory = factory;
Assert.IsTrue(object.ReferenceEquals(source.GetTarget(), target),
"Initial target source reference not being returned by GetTarget().");
}
[Test]

View File

@@ -18,17 +18,15 @@
#endregion
#region Imports
using System;
using System.Reflection;
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Caching;
using Spring.Context;
#endregion
namespace Spring.Aspects.Cache
{
/// <summary>
@@ -38,7 +36,6 @@ namespace Spring.Aspects.Cache
[TestFixture]
public sealed class CacheParameterAdviceTests
{
private MockRepository mocks;
private IApplicationContext mockContext;
private CacheParameterAdvice advice;
private ICache cache;
@@ -46,8 +43,7 @@ namespace Spring.Aspects.Cache
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
mockContext = (IApplicationContext) mocks.CreateMock(typeof (IApplicationContext));
mockContext = A.Fake<IApplicationContext>();
advice = new CacheParameterAdvice();
advice.ApplicationContext = mockContext;
@@ -62,14 +58,11 @@ namespace Spring.Aspects.Cache
object[] args = new object[] {new Inventor("Nikola Tesla", new DateTime(1856, 7, 9), "Serbian")};
ExpectCacheInstanceRetrieval("cache", cache);
mocks.ReplayAll();
// parameter value should be added to cache
advice.AfterReturning(null, method, args, null);
Assert.AreEqual(1, cache.Count);
Assert.AreEqual(args[0], cache.Get("Nikola Tesla"));
mocks.VerifyAll();
}
[Test]
@@ -79,14 +72,11 @@ namespace Spring.Aspects.Cache
object[] args = new object[] { new Inventor("Nikola Tesla", new DateTime(1856, 7, 9), "Serbian") };
ExpectCacheInstanceRetrieval("cache", cache);
mocks.ReplayAll();
// parameter value should be added to cache
advice.AfterReturning(null, method, args, null);
Assert.AreEqual(1, cache.Count);
Assert.AreEqual(args[0], cache.Get("Save-Nikola Tesla"));
mocks.VerifyAll();
}
[Test]
@@ -96,16 +86,13 @@ namespace Spring.Aspects.Cache
object[] args = new object[] { new Inventor("Nikola Tesla", new DateTime(1856, 7, 9), "Serbian") };
ExpectCacheInstanceRetrieval("cache", cache);
ExpectCacheInstanceRetrieval("cache", cache);
mocks.ReplayAll();
ExpectCacheInstanceRetrieval("cache", cache);
// parameter value should be added to both cache
advice.AfterReturning(null, method, args, null);
Assert.AreEqual(2, cache.Count);
Assert.AreEqual(args[0], cache.Get("Nikola Tesla"));
Assert.AreEqual(args[0], cache.Get("Serbian"));
mocks.VerifyAll();
}
[Test]
@@ -119,18 +106,12 @@ namespace Spring.Aspects.Cache
Assert.AreEqual(0, cache.Count);
}
#region Helper methods
private void ExpectCacheInstanceRetrieval(string cacheName, ICache cacheToReturn)
{
Expect.Call(mockContext.GetObject(cacheName)).Return(cacheToReturn);
A.CallTo(() => mockContext.GetObject(cacheName)).Returns(cacheToReturn).Once();
}
#endregion
}
#region Inner Class : CacheParameterTarget
public interface ICacheParameterTarget
{
void Save(Inventor inventor);
@@ -163,6 +144,4 @@ namespace Spring.Aspects.Cache
{
}
}
#endregion
}

View File

@@ -18,20 +18,18 @@
#endregion
#region Imports
using System.Collections;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using AopAlliance.Intercept;
using Rhino.Mocks;
using FakeItEasy;
using NUnit.Framework;
using Spring.Caching;
using Spring.Context;
#endregion
namespace Spring.Aspects.Cache
{
/// <summary>
@@ -50,14 +48,12 @@ namespace Spring.Aspects.Cache
private ICache itemCache;
private ICache binaryFormatterCache;
private CacheResultTarget cacheResultTarget = new CacheResultTarget();
private MockRepository mocks;
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
mockInvocation = mocks.CreateMock<IMethodInvocation>();
mockContext = mocks.CreateMock<IApplicationContext>();
mockInvocation = A.Fake<IMethodInvocation>();
mockContext = A.Fake<IApplicationContext>();
advice = new CacheResultAdvice();
advice.ApplicationContext = mockContext;
@@ -77,24 +73,16 @@ namespace Spring.Aspects.Cache
MethodInfo method = new VoidMethod(cacheResultTarget.ReturnsNothing).Method;
object expectedReturnValue = null;
using (mocks.Record())
{
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, null);
ExpectCacheInstanceRetrieval("results", resultCache);
ExpectCallToProceed(expectedReturnValue);
}
using (mocks.Playback())
{
// check that the null retVal is cached as well - it might be
// the result of an expensive webservice/database call etc.
object returnValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, returnValue);
Assert.AreEqual(1, resultCache.Count);
}
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, null);
ExpectCacheInstanceRetrieval("results", resultCache);
ExpectCallToProceed(expectedReturnValue);
// check that the null retVal is cached as well - it might be
// the result of an expensive webservice/database call etc.
object returnValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, returnValue);
Assert.AreEqual(1, resultCache.Count);
}
[Test]
@@ -103,26 +91,20 @@ namespace Spring.Aspects.Cache
MethodInfo method = new VoidMethod(cacheResultTarget.ReturnsNothing).Method;
object expectedReturnValue = null;
using (mocks.Record())
{
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, null);
ExpectCacheInstanceRetrieval("results", binaryFormatterCache);
ExpectCallToProceed(expectedReturnValue);
}
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, null);
ExpectCacheInstanceRetrieval("results", binaryFormatterCache);
ExpectCallToProceed(expectedReturnValue);
using (mocks.Playback())
{
// check that the null retVal is cached as well - it might be
// the result of an expensive webservice/database call etc.
object returnValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, returnValue);
Assert.AreEqual(1, binaryFormatterCache.Count);
// check that the null retVal is cached as well - it might be
// the result of an expensive webservice/database call etc.
object returnValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, returnValue);
Assert.AreEqual(1, binaryFormatterCache.Count);
// cached value should be returned
object cachedValue = advice.Invoke(mockInvocation);
Assert.IsNull(cachedValue, "Should recognize cached value as null-value marker.");
}
// cached value should be returned
object cachedValue = advice.Invoke(mockInvocation);
Assert.IsNull(cachedValue, "Should recognize cached value as null-value marker.");
}
[Test]
@@ -131,96 +113,76 @@ namespace Spring.Aspects.Cache
MethodInfo method = new IntMethod(cacheResultTarget.ReturnsScalar).Method;
object expectedReturnValue = CacheResultTarget.Scalar;
using (mocks.Record())
{
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, null);
ExpectCacheInstanceRetrieval("results", resultCache);
ExpectCallToProceed(expectedReturnValue);
}
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, null);
ExpectCacheInstanceRetrieval("results", resultCache);
ExpectCallToProceed(expectedReturnValue);
using (mocks.Playback())
{
// return value should be added to cache
object returnValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, returnValue);
Assert.AreEqual(1, resultCache.Count);
// return value should be added to cache
object returnValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, returnValue);
Assert.AreEqual(1, resultCache.Count);
// cached value should be returned
object cachedValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, cachedValue);
Assert.AreEqual(1, resultCache.Count);
Assert.AreSame(returnValue, cachedValue);
}
// cached value should be returned
object cachedValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, cachedValue);
Assert.AreEqual(1, resultCache.Count);
Assert.AreSame(returnValue, cachedValue);
}
[Test]
public void CacheResultOfMethodThatReturnsCollection()
{
MethodInfo method = new EnumerableResultMethod(cacheResultTarget.ReturnsCollection).Method;
object expectedReturnValue = new object[] { "one", "two", "three" };
object expectedReturnValue = new object[] {"one", "two", "three"};
using (mocks.Record())
{
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, 5, expectedReturnValue);
ExpectCacheInstanceRetrieval("results", resultCache);
ExpectCallToProceed(new object[] { "one", "two", "three" });
}
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, 5, expectedReturnValue);
ExpectCacheInstanceRetrieval("results", resultCache);
ExpectCallToProceed(new object[] {"one", "two", "three"});
using (mocks.Playback())
{
// return value should be added to cache
object returnValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, returnValue);
Assert.AreEqual(1, resultCache.Count);
// return value should be added to cache
object returnValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, returnValue);
Assert.AreEqual(1, resultCache.Count);
// cached value should be returned
object cachedValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, cachedValue);
Assert.AreNotSame(expectedReturnValue, cachedValue);
Assert.AreEqual(expectedReturnValue, resultCache.Get(5));
Assert.AreEqual(1, resultCache.Count);
Assert.AreSame(returnValue, cachedValue);
Assert.AreSame(cachedValue, resultCache.Get(5));
}
// cached value should be returned
object cachedValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, cachedValue);
Assert.AreNotSame(expectedReturnValue, cachedValue);
Assert.AreEqual(expectedReturnValue, resultCache.Get(5));
Assert.AreEqual(1, resultCache.Count);
Assert.AreSame(returnValue, cachedValue);
Assert.AreSame(cachedValue, resultCache.Get(5));
}
[Test]
public void CacheResultAndItemsOfMethodThatReturnsCollection()
{
MethodInfo method = new EnumerableResultMethod(cacheResultTarget.ReturnsCollectionAndItems).Method;
object expectedReturnValue = new object[] { "one", "two", "three" };
object expectedReturnValue = new object[] {"one", "two", "three"};
using (mocks.Record())
{
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, 5, expectedReturnValue);
ExpectCacheInstanceRetrieval("results", resultCache);
ExpectCallToProceed(new object[] { "one", "two", "three" });
ExpectCacheInstanceRetrieval("items", itemCache);
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, 5, expectedReturnValue);
ExpectCacheInstanceRetrieval("results", resultCache);
ExpectCallToProceed(new object[] {"one", "two", "three"});
ExpectCacheInstanceRetrieval("items", itemCache);
}
// return value should be added to result cache and each item to item cache
object returnValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, returnValue);
Assert.AreEqual(1, resultCache.Count);
Assert.AreEqual(3, itemCache.Count);
using (mocks.Playback())
{
// return value should be added to result cache and each item to item cache
object returnValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, returnValue);
Assert.AreEqual(1, resultCache.Count);
Assert.AreEqual(3, itemCache.Count);
// cached value should be returned
object cachedValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, cachedValue);
Assert.AreNotSame(expectedReturnValue, cachedValue);
Assert.AreEqual(expectedReturnValue, resultCache.Get(5));
Assert.AreEqual(1, resultCache.Count);
Assert.AreEqual(3, itemCache.Count);
Assert.AreSame(returnValue, cachedValue);
Assert.AreSame(cachedValue, resultCache.Get(5));
}
// cached value should be returned
object cachedValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, cachedValue);
Assert.AreNotSame(expectedReturnValue, cachedValue);
Assert.AreEqual(expectedReturnValue, resultCache.Get(5));
Assert.AreEqual(1, resultCache.Count);
Assert.AreEqual(3, itemCache.Count);
Assert.AreSame(returnValue, cachedValue);
Assert.AreSame(cachedValue, resultCache.Get(5));
}
[Test]
@@ -229,74 +191,51 @@ namespace Spring.Aspects.Cache
MethodInfo method = new EnumerableResultMethod(cacheResultTarget.ReturnsItems).Method;
object expectedReturnValue = new object[] { "one", "two", "three" };
mocks.Record();
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, 5, expectedReturnValue);
ExpectCallToProceed(new object[] { "one", "two", "three" });
ExpectCacheInstanceRetrieval("items", itemCache);
mocks.ReplayAll();
// return value should be added to result cache and each item to item cache
object returnValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, returnValue);
Assert.AreEqual(0, resultCache.Count);
Assert.AreEqual(3, itemCache.Count);
mocks.Verify(mockInvocation);
mocks.BackToRecord(mockInvocation);
ExpectAttributeRetrieval(method);
ExpectCallToProceed(new object[] { "one", "two", "three" });
ExpectCacheKeyGeneration(method, 5, expectedReturnValue);
mocks.Replay(mockInvocation);
object newReturnValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, newReturnValue);
Assert.AreEqual(0, resultCache.Count);
Assert.AreEqual(3, itemCache.Count);
Assert.AreEqual("two", itemCache.Get("two"));
Assert.AreNotSame(returnValue, newReturnValue);
mocks.VerifyAll();
}
[Test]
public void CacheOnlyItemsOfMethodThatReturnsCollectionWithinTwoDifferentCaches()
{
MethodInfo method = new EnumerableResultMethod(cacheResultTarget.MultipleCacheResultItems).Method;
object expectedReturnValue = new object[] { "one", "two", "three" };
mocks.Record();
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, 5, expectedReturnValue);
ExpectCallToProceed(new object[] { "one", "two", "three" });
ExpectCacheInstanceRetrieval("items", itemCache);
mocks.ReplayAll();
// return value should be added to result cache and each item to item cache
object returnValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, returnValue);
Assert.AreEqual(0, resultCache.Count);
Assert.AreEqual(6, itemCache.Count);
mocks.Verify(mockInvocation);
mocks.BackToRecord(mockInvocation);
// and again, but without Proceed() and item cache access...
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, 5, expectedReturnValue);
ExpectCallToProceed(new object[] { "one", "two", "three" });
mocks.Replay(mockInvocation);
// new return value should be returned
object newReturnValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, newReturnValue);
@@ -305,57 +244,42 @@ namespace Spring.Aspects.Cache
Assert.AreEqual("two", itemCache.Get("two"));
Assert.AreEqual("two", itemCache.Get("TWO"));
Assert.AreNotSame(returnValue, newReturnValue);
mocks.VerifyAll();
}
[Test]
public void CacheOnlyItemsOfMethodThatReturnsCollectionOnCondition()
{
MethodInfo method = new EnumerableResultMethod(cacheResultTarget.CacheResultItemsWithCondition).Method;
object expectedReturnValue = new object[] { "one", "two", "three" };
object expectedReturnValue = new object[] {"one", "two", "three"};
using (mocks.Record())
{
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, 5, expectedReturnValue);
ExpectCallToProceed(new object[] { "one", "two", "three" });
ExpectCacheInstanceRetrieval("items", itemCache);
}
using (mocks.Playback())
{
// return value should be added to result cache and each item to item cache
object returnValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, returnValue);
Assert.AreEqual(2, itemCache.Count);
Assert.AreEqual("two", itemCache.Get("two"));
Assert.AreEqual("three", itemCache.Get("three"));
}
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, 5, expectedReturnValue);
ExpectCallToProceed(new object[] {"one", "two", "three"});
ExpectCacheInstanceRetrieval("items", itemCache);
// return value should be added to result cache and each item to item cache
object returnValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, returnValue);
Assert.AreEqual(2, itemCache.Count);
Assert.AreEqual("two", itemCache.Get("two"));
Assert.AreEqual("three", itemCache.Get("three"));
}
[Test]
public void CacheResultOfMethodThatReturnsCollectionOnCondition()
{
MethodInfo method = new EnumerableResultMethod(cacheResultTarget.CacheResultWithCondition).Method;
object expectedReturnValue = new object[] { };
object expectedReturnValue = new object[] {};
using (mocks.Record())
{
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, 5, expectedReturnValue);
ExpectCacheInstanceRetrieval("results", resultCache);
ExpectCallToProceed(new object[] { });
}
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, 5, expectedReturnValue);
ExpectCacheInstanceRetrieval("results", resultCache);
ExpectCallToProceed(new object[] {});
using (mocks.Playback())
{
// return value should not be added to cache
object returnValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, returnValue);
Assert.AreEqual(0, resultCache.Count);
}
// return value should not be added to cache
object returnValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, returnValue);
Assert.AreEqual(0, resultCache.Count);
}
[Test]
@@ -365,16 +289,12 @@ namespace Spring.Aspects.Cache
object[] args = new object[] { "one", "two", "three" };
EnumerableOnlyResult expectedReturnValue = new EnumerableOnlyResult(args);
mocks.Record();
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, 5, expectedReturnValue.InnerArray);
ExpectCacheInstanceRetrieval("results", resultCache);
ExpectCallToProceed(expectedReturnValue);
ExpectCacheInstanceRetrieval("items", itemCache);
mocks.ReplayAll();
// return value should be added to result cache and each item to item cache
object returnValue = advice.Invoke(mockInvocation);
Assert.AreEqual(1, resultCache.Count);
@@ -382,16 +302,10 @@ namespace Spring.Aspects.Cache
Assert.AreSame(expectedReturnValue, returnValue);
Assert.AreSame(expectedReturnValue, resultCache.Get(5));
mocks.Verify(mockInvocation);
mocks.BackToRecord(mockInvocation);
// and again, but without Proceed() and item cache access...
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, 5, IGNORED_ARGS);
mocks.Replay(mockInvocation);
// cached value should be returned, cache remains unchanged
object cachedValue = advice.Invoke(mockInvocation);
Assert.AreSame(expectedReturnValue, cachedValue);
@@ -399,42 +313,30 @@ namespace Spring.Aspects.Cache
Assert.AreSame(expectedReturnValue, resultCache.Get(5));
Assert.AreEqual(1, resultCache.Count);
Assert.AreEqual(3, itemCache.Count);
mocks.VerifyAll();
}
[Test]
public void CacheResultOfMethodThatReturnsCollectionContainingNullItems()
{
MethodInfo method = new EnumerableResultMethod(cacheResultTarget.ReturnsEnumerableOnlyAndItems).Method;
object expectedReturnValue = new object[] { null, "two", null };
mocks.Record();
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, 5, expectedReturnValue);
ExpectCacheInstanceRetrieval("results", resultCache);
ExpectCallToProceed(expectedReturnValue);
ExpectCacheInstanceRetrieval("items", itemCache);
mocks.ReplayAll();
// return value should be added to result cache and each item to item cache
object returnValue = advice.Invoke(mockInvocation);
Assert.AreSame(expectedReturnValue, returnValue);
Assert.AreEqual(1, resultCache.Count);
Assert.AreEqual(2, itemCache.Count); // 2 null items result into 1 cached item
mocks.Verify(mockInvocation);
mocks.BackToRecord(mockInvocation);
// and again, but without Proceed() and item cache access...
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, 5, IGNORED_ARGS);
mocks.Replay(mockInvocation);
// cached value should be returned
object cachedValue = advice.Invoke(mockInvocation);
Assert.AreSame(expectedReturnValue, cachedValue);
@@ -442,95 +344,74 @@ namespace Spring.Aspects.Cache
Assert.AreSame(expectedReturnValue, resultCache.Get(5));
Assert.AreEqual(1, resultCache.Count);
Assert.AreEqual(2, itemCache.Count);
mocks.VerifyAll();
}
[Test]
public void CacheResultWithMethodInfo()
{
MethodInfo method = new EnumerableResultMethod(cacheResultTarget.CacheResultWithMethodInfo).Method;
object expectedReturnValue = new object[] { "one", "two", "three" };
object expectedReturnValue = new object[] {"one", "two", "three"};
using (mocks.Record())
{
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, 5, expectedReturnValue);
ExpectCacheInstanceRetrieval("results", resultCache);
ExpectCallToProceed(new object[] { "one", "two", "three" });
}
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, 5, expectedReturnValue);
ExpectCacheInstanceRetrieval("results", resultCache);
ExpectCallToProceed(new object[] {"one", "two", "three"});
using (mocks.Playback())
{
// return value should be added to cache
object returnValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, returnValue);
Assert.AreEqual(1, resultCache.Count);
Assert.AreEqual(returnValue, resultCache.Get("CacheResultWithMethodInfo-5"));
}
// return value should be added to cache
object returnValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, returnValue);
Assert.AreEqual(1, resultCache.Count);
Assert.AreEqual(returnValue, resultCache.Get("CacheResultWithMethodInfo-5"));
}
[Test]
public void CacheResultItemsWithMethodInfo()
{
MethodInfo method = new EnumerableResultMethod(cacheResultTarget.CacheResultItemsWithMethodInfo).Method;
object expectedReturnValue = new object[] { "one", "two", "three" };
object expectedReturnValue = new object[] {"one", "two", "three"};
using (mocks.Record())
{
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, 5, expectedReturnValue);
ExpectCallToProceed(new object[] { "one", "two", "three" });
ExpectCacheInstanceRetrieval("items", itemCache);
}
using (mocks.Playback())
{
// return value should be added to result cache and each item to item cache
object returnValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, returnValue);
Assert.AreEqual(0, resultCache.Count);
Assert.AreEqual(3, itemCache.Count);
Assert.AreEqual("two", itemCache.Get("CacheResultItemsWithMethodInfo-two"));
}
ExpectAttributeRetrieval(method);
ExpectCacheKeyGeneration(method, 5, expectedReturnValue);
ExpectCallToProceed(new object[] {"one", "two", "three"});
ExpectCacheInstanceRetrieval("items", itemCache);
// return value should be added to result cache and each item to item cache
object returnValue = advice.Invoke(mockInvocation);
Assert.AreEqual(expectedReturnValue, returnValue);
Assert.AreEqual(0, resultCache.Count);
Assert.AreEqual(3, itemCache.Count);
Assert.AreEqual("two", itemCache.Get("CacheResultItemsWithMethodInfo-two"));
}
#region Helper methods
private void ExpectAttributeRetrieval(MethodInfo method)
{
Expect.Call(mockInvocation.Method).Return(method).Repeat.AtLeastOnce();
A.CallTo(() => mockInvocation.Method).Returns(method);
}
private void ExpectCacheKeyGeneration(MethodInfo method, params object[] arguments)
{
Expect.Call(mockInvocation.Arguments).Return(arguments).Repeat.AtLeastOnce();
A.CallTo(() => mockInvocation.Arguments).Returns(arguments);
}
private void ExpectCacheInstanceRetrieval(string cacheName, ICache cache)
{
Expect.Call(mockContext.GetObject(cacheName)).Return(cache).Repeat.AtLeastOnce();
A.CallTo(() => mockContext.GetObject(cacheName)).Returns(cache);
}
private void ExpectCacheInstanceRetrieval(string cacheName, ICache cache, int repeatTimes)
{
Expect.Call(mockContext.GetObject(cacheName)).Return(cache).Repeat.Times(repeatTimes);
A.CallTo(() => mockContext.GetObject(cacheName)).Returns(cache).NumberOfTimes(repeatTimes);
}
private void ExpectCallToProceed(object expectedReturnValue, int repeatTimes)
{
Expect.Call(mockInvocation.Proceed()).Return(expectedReturnValue).Repeat.Times(repeatTimes);
A.CallTo(() => mockInvocation.Proceed()).Returns(expectedReturnValue).NumberOfTimes(repeatTimes);
}
private void ExpectCallToProceed(object expectedReturnValue)
{
Expect.Call(mockInvocation.Proceed()).Return(expectedReturnValue);
A.CallTo(() => mockInvocation.Proceed()).Returns(expectedReturnValue);
}
#endregion
}
#region Inner Class : CacheResultTarget

View File

@@ -18,18 +18,15 @@
#endregion
#region Imports
using System.Reflection;
using NUnit.Framework;
using Rhino.Mocks;
using FakeItEasy;
using NUnit.Framework;
using Spring.Caching;
using Spring.Context;
#endregion
namespace Spring.Aspects.Cache
{
/// <summary>
@@ -42,13 +39,11 @@ namespace Spring.Aspects.Cache
private IApplicationContext mockContext;
private InvalidateCacheAdvice advice;
private ICache cache;
private MockRepository mocks;
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
mockContext = (IApplicationContext) mocks.CreateMock(typeof (IApplicationContext));
mockContext = A.Fake<IApplicationContext>();
advice = new InvalidateCacheAdvice();
advice.ApplicationContext = mockContext;
@@ -66,7 +61,6 @@ namespace Spring.Aspects.Cache
object[] args = new object[] { 2 };
ExpectCacheInstanceRetrieval("cache", cache);
mocks.ReplayAll();
Assert.AreEqual(3, cache.Count);
@@ -74,8 +68,6 @@ namespace Spring.Aspects.Cache
advice.AfterReturning(null, method, args, null);
Assert.AreEqual(2, cache.Count);
Assert.IsNull(cache.Get(2));
mocks.VerifyAll();
}
[Test]
@@ -85,7 +77,6 @@ namespace Spring.Aspects.Cache
object[] args = new object[] { 2 };
ExpectCacheInstanceRetrieval("cache", cache);
mocks.ReplayAll();
Assert.AreEqual(3, cache.Count);
@@ -93,8 +84,6 @@ namespace Spring.Aspects.Cache
advice.AfterReturning(null, method, args, null);
Assert.AreEqual(1, cache.Count);
Assert.AreEqual("two", cache.Get(2));
mocks.VerifyAll();
}
[Test]
@@ -103,15 +92,12 @@ namespace Spring.Aspects.Cache
MethodInfo method = typeof(InvalidateCacheTarget).GetMethod("InvalidateAll");
ExpectCacheInstanceRetrieval("cache", cache);
mocks.ReplayAll();
Assert.AreEqual(3, cache.Count);
// all items should be removed from cache
advice.AfterReturning(null, method, null, null);
Assert.AreEqual(0, cache.Count);
mocks.VerifyAll();
}
[Test]
@@ -122,7 +108,6 @@ namespace Spring.Aspects.Cache
ExpectCacheInstanceRetrieval("cache", cache);
ExpectCacheInstanceRetrieval("cache", cache);
mocks.ReplayAll();
Assert.AreEqual(3, cache.Count);
@@ -130,8 +115,6 @@ namespace Spring.Aspects.Cache
// all items except item "two" should be removed from cache
advice.AfterReturning(null, method, args, null);
Assert.AreEqual(0, cache.Count);
mocks.VerifyAll();
}
[Test]
@@ -148,14 +131,10 @@ namespace Spring.Aspects.Cache
Assert.AreEqual("three", cache.Get(3));
}
#region Helper methods
private void ExpectCacheInstanceRetrieval(string cacheName, ICache cacheToReturn)
{
Expect.Call(mockContext.GetObject(cacheName)).Return(cacheToReturn);
A.CallTo(() => mockContext.GetObject(cacheName)).Returns(cacheToReturn).Once();
}
#endregion
}
#region Inner Class : InvalidateCacheTarget

View File

@@ -18,18 +18,16 @@
#endregion
#region Imports
using System;
using System.Reflection;
using AopAlliance.Intercept;
using Common.Logging;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Aop.Framework;
#endregion
using FakeItEasy;
using NUnit.Framework;
using Spring.Aop.Framework;
namespace Spring.Aspects.Logging
{
@@ -51,12 +49,9 @@ namespace Spring.Aspects.Logging
{ }
}
private MockRepository mocks;
[SetUp]
public void Setup()
{
mocks = new MockRepository();
}
[Test]
@@ -64,101 +59,76 @@ namespace Spring.Aspects.Logging
{
ProxyFactory pf = new ProxyFactory(new TestTarget());
ILog log = (ILog)mocks.CreateMock(typeof(ILog));
ILog log = A.Fake<ILog>();
SimpleLoggingAdvice loggingAdvice = new SimpleLoggingAdvice(log);
pf.AddAdvice(loggingAdvice);
Expect.Call(log.IsTraceEnabled).Return(true).Repeat.Any();
log.Trace("Entering DoSomething");
log.Trace("Exiting DoSomething");
mocks.ReplayAll();
A.CallTo(() => log.IsTraceEnabled).Returns(true);
object proxy = pf.GetProxy();
ITestTarget ptt = (ITestTarget)proxy;
ptt.DoSomething();
mocks.VerifyAll();
A.CallTo(() => log.Trace("Entering DoSomething")).MustHaveHappened();
A.CallTo(() => log.Trace("Exiting DoSomething")).MustHaveHappened();
}
[Test]
public void SunnyDayLoggingCorrectly()
{
ILog log = (ILog)mocks.CreateMock(typeof(ILog));
IMethodInvocation methodInvocation = (IMethodInvocation)mocks.CreateMock(typeof(IMethodInvocation));
ILog log = A.Fake<ILog>();
IMethodInvocation methodInvocation = A.Fake<IMethodInvocation>();
MethodInfo mi = typeof(string).GetMethod("ToString", Type.EmptyTypes);
//two additional calls the method are to retrieve the method name on entry/exit...
Expect.Call(methodInvocation.Method).Return(mi).Repeat.Any();
Expect.Call(log.IsTraceEnabled).Return(true).Repeat.Any();
log.Trace("Entering ToString");
Expect.Call(methodInvocation.Proceed()).Return(null);
log.Trace("Exiting ToString");
mocks.ReplayAll();
A.CallTo(() => methodInvocation.Method).Returns(mi);
A.CallTo(() => log.IsTraceEnabled).Returns(true);
A.CallTo(() => methodInvocation.Proceed()).Returns(null);
TestableSimpleLoggingAdvice loggingAdvice = new TestableSimpleLoggingAdvice(true);
loggingAdvice.CallInvokeUnderLog(methodInvocation, log);
mocks.VerifyAll();
A.CallTo(() => log.Trace("Entering ToString")).MustHaveHappened();
A.CallTo(() => log.Trace("Exiting ToString")).MustHaveHappened();
}
[Test]
public void SunnyDayLoggingCorrectlyDebugLevel()
{
ILog log = (ILog)mocks.CreateMock(typeof(ILog));
IMethodInvocation methodInvocation = (IMethodInvocation)mocks.CreateMock(typeof(IMethodInvocation));
ILog log = A.Fake<ILog>();
IMethodInvocation methodInvocation = A.Fake<IMethodInvocation>();
MethodInfo mi = typeof(string).GetMethod("ToString", Type.EmptyTypes);
//two additional calls the method are to retrieve the method name on entry/exit...
Expect.Call(methodInvocation.Method).Return(mi).Repeat.Any();
A.CallTo(() => methodInvocation.Method).Returns(mi);
Expect.Call(log.IsTraceEnabled).Return(false).Repeat.Any();
Expect.Call(log.IsDebugEnabled).Return(true).Repeat.Any();
log.Debug("Entering ToString");
A.CallTo(() => log.IsTraceEnabled).Returns(false);
A.CallTo(() => log.IsDebugEnabled).Returns(true);
Expect.Call(methodInvocation.Proceed()).Return(null);
log.Debug("Exiting ToString");
mocks.ReplayAll();
A.CallTo(() => methodInvocation.Proceed()).Returns(null);
TestableSimpleLoggingAdvice loggingAdvice = new TestableSimpleLoggingAdvice(true);
loggingAdvice.LogLevel = LogLevel.Debug;
Assert.IsTrue(loggingAdvice.CallIsInterceptorEnabled(methodInvocation, log));
loggingAdvice.CallInvokeUnderLog(methodInvocation, log);
mocks.VerifyAll();
A.CallTo(() => log.Debug("Entering ToString")).MustHaveHappened();
A.CallTo(() => log.Debug("Exiting ToString")).MustHaveHappened();
}
[Test]
public void ExceptionPathStillLogsCorrectly()
{
ILog log = (ILog)mocks.CreateMock(typeof(ILog));
IMethodInvocation methodInvocation = (IMethodInvocation)mocks.CreateMock(typeof(IMethodInvocation));
ILog log = A.Fake<ILog>();
IMethodInvocation methodInvocation = A.Fake<IMethodInvocation>();
MethodInfo mi = typeof(string).GetMethod("ToString", Type.EmptyTypes);
//two additional calls the method are to retrieve the method name on entry/exit...
Expect.Call(methodInvocation.Method).Return(mi).Repeat.Any();
Expect.Call(log.IsTraceEnabled).Return(true).Repeat.Any();
log.Trace("Entering...");
LastCall.On(log).IgnoreArguments();
A.CallTo(() => methodInvocation.Method).Returns(mi);
A.CallTo(() => log.IsTraceEnabled).Returns(true);
Exception e = new ArgumentException("bad value");
Expect.Call(methodInvocation.Proceed()).Throw(e);
log.Trace("Exception...", e);
LastCall.On(log).IgnoreArguments();
mocks.ReplayAll();
A.CallTo(() => methodInvocation.Proceed()).Throws(e);
TestableSimpleLoggingAdvice loggingAdvice = new TestableSimpleLoggingAdvice(true);
try
@@ -168,39 +138,27 @@ namespace Spring.Aspects.Logging
}
catch (ArgumentException)
{
}
mocks.VerifyAll();
A.CallTo(() => log.Trace("Entering ToString")).MustHaveHappened();
A.CallTo(() => log.Trace("Exception thrown in ToString, ToString", e)).MustHaveHappened();
}
[Test]
public void SunnyDayLoggingAllOptionalInformationCorrectly()
{
ILog log = (ILog)mocks.CreateMock(typeof(ILog));
IMethodInvocation methodInvocation = (IMethodInvocation)mocks.CreateMock(typeof(IMethodInvocation));
ILog log = A.Fake<ILog>();
IMethodInvocation methodInvocation = A.Fake<IMethodInvocation>();
MethodInfo mi = typeof(Dog).GetMethod("Bark");
//two additional calls the method are to retrieve the method name on entry/exit...
Expect.Call(methodInvocation.Method).Return(mi).Repeat.Any();
A.CallTo(() => methodInvocation.Method).Returns(mi);
int[] luckyNumbers = new int[] { 1, 2, 3 };
object[] args = new object[] { "hello", luckyNumbers };
Expect.Call(methodInvocation.Arguments).Return(args);
Expect.Call(log.IsTraceEnabled).Return(true).Repeat.Any();
log.Trace("Entering...");
LastCall.IgnoreArguments();
Expect.Call(methodInvocation.Proceed()).Return(4);
log.Trace("Exiting...");
LastCall.IgnoreArguments();
mocks.ReplayAll();
A.CallTo(() => methodInvocation.Arguments).Returns(args);
A.CallTo(() => log.IsTraceEnabled).Returns(true);
A.CallTo(() => methodInvocation.Proceed()).Returns(4);
TestableSimpleLoggingAdvice loggingAdvice = new TestableSimpleLoggingAdvice(true);
loggingAdvice.LogExecutionTime = true;
@@ -209,7 +167,8 @@ namespace Spring.Aspects.Logging
loggingAdvice.CallInvokeUnderLog(methodInvocation, log);
mocks.VerifyAll();
A.CallTo(() => log.Trace(A<string>.That.StartsWith("Entering Bark"))).MustHaveHappened();
A.CallTo(() => log.Trace(A<string>.That.StartsWith("Exiting Bark"))).MustHaveHappened();
}
}

View File

@@ -18,18 +18,16 @@
#endregion
#region Imports
using System;
using System.Reflection;
using Rhino.Mocks;
using FakeItEasy;
using NUnit.Framework;
using Spring.Context;
using Spring.Validation;
using Spring.Validation.Actions;
#endregion
namespace Spring.Aspects.Validation
{
/// <summary>
@@ -42,13 +40,11 @@ namespace Spring.Aspects.Validation
private IApplicationContext mockContext;
private ParameterValidationAdvice advice;
private RequiredValidator requiredValidator;
private MockRepository mocks;
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
mockContext = mocks.CreateMock<IApplicationContext>();
mockContext = A.Fake<IApplicationContext>();
advice = new ParameterValidationAdvice();
advice.ApplicationContext = mockContext;
@@ -65,18 +61,11 @@ namespace Spring.Aspects.Validation
ValidationTarget target = new ValidationTarget();
object[] args = new object[] {inventor};
using (mocks.Record())
{
ExpectValidatorRetrieval("required", requiredValidator);
}
using (mocks.Playback())
{
advice.Before(method, args, target);
method.Invoke(target, args);
Assert.AreEqual("NIKOLA TESLA", inventor.Name);
}
ExpectValidatorRetrieval("required", requiredValidator);
advice.Before(method, args, target);
method.Invoke(target, args);
Assert.AreEqual("NIKOLA TESLA", inventor.Name);
}
[Test]
@@ -84,25 +73,15 @@ namespace Spring.Aspects.Validation
{
MethodInfo method = typeof(ValidationTarget).GetMethod("Save");
using (mocks.Record())
{
ExpectValidatorRetrieval("required", requiredValidator);
}
ExpectValidatorRetrieval("required", requiredValidator);
using (mocks.Playback())
{
Assert.Throws<ValidationException>(() => advice.Before(method, new object[] { null }, new ValidationTarget()));
}
Assert.Throws<ValidationException>(() => advice.Before(method, new object[] {null}, new ValidationTarget()));
}
#region Helper methods
private void ExpectValidatorRetrieval(string validatorName, IValidator validator)
{
Expect.Call(mockContext.GetObject(validatorName)).Return(validator);
A.CallTo(() => mockContext.GetObject(validatorName)).Returns(validator).Once();
}
#endregion
}
#region Inner Class : ValidationTarget

View File

@@ -7,10 +7,11 @@
<ProjectReference Include="..\Spring.Core.Tests\Spring.Core.Tests.2010.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="FakeItEasy" Version="$(FakeItEasyVersion)" />
<PackageReference Include="FakeItEasy.Analyzer" Version="$(FakeItEasyVersion)" PrivateAssets="All" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="$(MicrosoftTestSDKVersion)" />
<PackageReference Include="NUnit" Version="$(NUnitVersion)" />
<PackageReference Include="NUnit3TestAdapter" Version="$(NUnitTestAdapterVersion)" />
<PackageReference Include="RhinoMocks" Version="$(RhinoMocksVersion)" />
</ItemGroup>
<ItemGroup>
<Reference Include="System.Web" />

View File

@@ -18,19 +18,17 @@
#endregion
#region Imports
using System;
using System.Threading;
using NUnit.Framework;
using Rhino.Mocks;
#endregion
using FakeItEasy;
using NUnit.Framework;
namespace Spring.Caching
{
/// <summary>
/// Tests <see cref="AbstractCache"/> behaviour to ensure,
/// Tests <see cref="AbstractCache"/> behaviour to ensure,
/// that derived classes maybe rely on this default behaviour
/// </summary>
/// <author>Erich Eichinger</author>
@@ -56,15 +54,13 @@ namespace Spring.Caching
TimeSpan expectedPerItemTTL;
TimeSpan expectedPerCacheTTL;
MockRepository mocks;
ExposingAbstractCache cache;
string[] KEYS = new string[] { "keyA", "keyB" };
string[] KEYS = new string[] {"keyA", "keyB"};
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
cache = (ExposingAbstractCache)mocks.PartialMock(typeof(ExposingAbstractCache));
cache = A.Fake<ExposingAbstractCache>(options => options.CallsBaseMethods());
expectedPerItemTTL = new TimeSpan(0, 0, 10);
expectedPerCacheTTL = new TimeSpan(0, 0, 20);
@@ -75,7 +71,7 @@ namespace Spring.Caching
[Test]
public void TestDefaults()
{
ExposingAbstractCache localCache = (ExposingAbstractCache)mocks.PartialMock(typeof(ExposingAbstractCache));
ExposingAbstractCache localCache = A.Fake<ExposingAbstractCache>();
Assert.AreEqual(TimeSpan.Zero, localCache.TimeToLive);
Assert.AreEqual(false, localCache.EnforceTimeToLive);
}
@@ -85,96 +81,78 @@ namespace Spring.Caching
{
// set expectations
cache.DoInsertExposed("key", "value", expectedPerCacheTTL);
mocks.ReplayAll();
// verify
cache.Insert("key", "value", expectedPerCacheTTL);
mocks.VerifyAll();
A.CallTo(() => cache.DoInsertExposed("key", "value", expectedPerCacheTTL)).MustHaveHappened();
}
[Test]
public void AppliesPerCacheDefaultsIfTTLLessThanZero()
{
// set expectations
cache.DoInsertExposed("key", "value", expectedPerCacheTTL);
cache.DoInsertExposed("key", "value", expectedPerCacheTTL);
cache.DoInsertExposed("key", "value", expectedPerCacheTTL);
cache.DoInsertExposed("key", "value", expectedPerCacheTTL);
mocks.ReplayAll();
// verify
cache.Insert("key", "value", new TimeSpan(Timeout.Infinite));
A.CallTo(() => cache.DoInsertExposed("key", "value", expectedPerCacheTTL)).MustHaveHappened();
cache.Insert("key", "value", new TimeSpan(-1));
cache.Insert("key", "value", new TimeSpan(Int64.MinValue));
A.CallTo(() => cache.DoInsertExposed("key", "value", expectedPerCacheTTL)).MustHaveHappened();
cache.Insert("key", "value", new TimeSpan(long.MinValue));
A.CallTo(() => cache.DoInsertExposed("key", "value", expectedPerCacheTTL)).MustHaveHappened();
cache.Insert("key", "value", TimeSpan.MinValue);
mocks.VerifyAll();
A.CallTo(() => cache.DoInsertExposed("key", "value", expectedPerCacheTTL)).MustHaveHappened();
}
[Test]
public void AppliesPerCacheDefaultsIfEnfored()
{
// set expectations
cache.DoInsertExposed("key", "value", expectedPerCacheTTL);
mocks.ReplayAll();
// verify
cache.EnforceTimeToLive = true;
cache.Insert("key", "value", expectedPerItemTTL);
mocks.VerifyAll();
A.CallTo(() => cache.DoInsertExposed("key", "value", expectedPerCacheTTL)).MustHaveHappened();
}
[Test]
public void AppliesZeroTTLIfTTLIsZero()
{
// set expectations
cache.DoInsertExposed("key", "value", TimeSpan.Zero);
mocks.ReplayAll();
// verify
cache.Insert("key", "value", TimeSpan.Zero);
mocks.VerifyAll();
A.CallTo(() => cache.DoInsertExposed("key", "value", TimeSpan.Zero)).MustHaveHappened();
}
[Test]
public void AppliesPerItemTTLIfTTLGreaterZero()
{
// set expectations
cache.DoInsertExposed("key", "value", expectedPerItemTTL);
mocks.ReplayAll();
// verify
cache.Insert("key", "value", expectedPerItemTTL);
mocks.VerifyAll();
A.CallTo(() => cache.DoInsertExposed("key", "value", expectedPerItemTTL)).MustHaveHappened();
}
[Test]
public void RemoveAllCausesCallsToRemove()
{
// set expectations
cache.Remove(KEYS[0]);
cache.Remove(KEYS[1]);
mocks.ReplayAll();
// verify
cache.RemoveAll(KEYS);
mocks.VerifyAll();
A.CallTo(() => cache.Remove(KEYS[0])).MustHaveHappened();
A.CallTo(() => cache.Remove(KEYS[1])).MustHaveHappened();
}
[Test]
public void ClearCausesCallToRemoveAllUsingKeys()
{
// set expectations
Expect.Call(cache.Keys).Return(KEYS);
cache.RemoveAll(KEYS);
mocks.ReplayAll();
// verify
A.CallTo(() => cache.Keys).Returns(this.KEYS);
cache.Clear();
mocks.VerifyAll();
A.CallTo(() => cache.Keys).MustHaveHappened();
A.CallTo(() => cache.RemoveAll(KEYS)).MustHaveHappened();
}
[Test]
public void CountUsingKeys()
{
// set expectations
Expect.Call(cache.Keys).Return(this.KEYS);
mocks.ReplayAll();
// verify
Assert.AreEqual( this.KEYS.Length, cache.Count );
mocks.VerifyAll();
A.CallTo(() => cache.Keys).Returns(this.KEYS);
Assert.AreEqual(this.KEYS.Length, cache.Count);
}
}
}

View File

@@ -70,7 +70,7 @@ namespace Spring.Collections
[Test]
public void ThrowsArgumentNullExceptionForNullCollection()
{
Assert.Throws<ArgumentNullException>(() => new PriorityQueue((ICollection) null));
Assert.Throws<ArgumentNullException>(() => new PriorityQueue(null));
}
[Test]

View File

@@ -18,11 +18,11 @@
#endregion
#region Imports
using System;
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Core;
using Spring.Core.IO;
using Spring.Objects;
@@ -32,8 +32,6 @@ using Spring.Objects.Factory.Config;
using Spring.Objects.Factory.Support;
using Spring.Objects.Factory.Xml;
#endregion
namespace Spring.Context.Support
{
[TestFixture]
@@ -60,7 +58,7 @@ namespace Spring.Context.Support
public void ContextAwareDisplayName()
{
}
[Test]
@@ -96,8 +94,7 @@ namespace Spring.Context.Support
[Test]
public void DoesNotSearchParentContextForMessageSource()
{
MockRepository mocks = new MockRepository();
IMessageSource msgSource = (IMessageSource) mocks.DynamicMock(typeof (IMessageSource));
IMessageSource msgSource = A.Fake<IMessageSource>();
MockApplicationContext parentCtx = new MockApplicationContext("parentContext");
parentCtx.ObjectFactory.RegisterSingleton(AbstractApplicationContext.MessageSourceObjectName, msgSource);
MockApplicationContext childContext = new MockApplicationContext("childContext", parentCtx);
@@ -112,8 +109,7 @@ namespace Spring.Context.Support
[Test]
public void DoesNotSearchParentContextForEventRegistry()
{
MockRepository mocks = new MockRepository();
IEventRegistry eventRegistry = (IEventRegistry)mocks.DynamicMock(typeof(IEventRegistry));
IEventRegistry eventRegistry = A.Fake<IEventRegistry>();
MockApplicationContext parentCtx = new MockApplicationContext("parentContext");
parentCtx.ObjectFactory.RegisterSingleton(AbstractApplicationContext.EventRegistryObjectName, eventRegistry);
MockApplicationContext childContext = new MockApplicationContext("childContext", parentCtx);
@@ -398,7 +394,7 @@ namespace Spring.Context.Support
<objects xmlns='http://www.springframework.net'>
<object id='test2' type='DOESNOTEXIST' />
</objects>
"));
"));
myContext.Refresh();
}
catch (Exception e)

View File

@@ -18,36 +18,30 @@
#endregion
#region Imports
using System.Globalization;
using NUnit.Framework;
using Rhino.Mocks;
#endregion
using FakeItEasy;
using NUnit.Framework;
namespace Spring.Context.Support
{
[TestFixture]
public sealed class AbstractMessageSourceTests : AbstractMessageSource
{
private MockRepository mocks;
[SetUp]
public void Init()
{
mocks = new MockRepository();
resetMe();
ResetMe();
}
[Test]
public void GetResolvableNullCodes()
{
IMessageSourceResolvable res = mocks.StrictMock<IMessageSourceResolvable>();
Expect.Call(res.GetCodes()).Return(null);
Expect.Call(res.DefaultMessage).Return(null);
mocks.ReplayAll();
{
var res = A.Fake<IMessageSourceResolvable>();
A.CallTo(() => res.DefaultMessage).Returns(null);
Assert.Throws<NoSuchMessageException>(() => GetMessage(res, CultureInfo.CurrentCulture));
mocks.VerifyAll();
}
[Test]
@@ -56,92 +50,79 @@ namespace Spring.Context.Support
string MSGCODE = "nullCode";
object[] MSGARGS = new object[] { "arg1", "arg2" };
IMessageSourceResolvable res = mocks.StrictMock<IMessageSourceResolvable>();
Expect.Call(res.GetArguments()).Return(MSGARGS);
Expect.Call(res.GetCodes()).Return(new string[] {MSGCODE}).Repeat.Once();
IMessageSource parentSource = mocks.StrictMock<IMessageSource>();
Expect.Call(parentSource.GetMessage(MSGCODE, null, CultureInfo.CurrentCulture, MSGARGS)).Return(
"MockMessageSource");
IMessageSourceResolvable res = A.Fake<IMessageSourceResolvable>();
A.CallTo(() => res.GetArguments()).Returns(MSGARGS);
A.CallTo(() => res.GetCodes()).Returns(new string[] {MSGCODE}).Once();
IMessageSource parentSource = A.Fake<IMessageSource>();
A.CallTo(() => parentSource.GetMessage(MSGCODE, null, CultureInfo.CurrentCulture, A<object[]>._)).Returns("MockMessageSource");
ParentMessageSource = parentSource;
mocks.ReplayAll();
Assert.AreEqual("MockMessageSource", GetMessage(res, CultureInfo.CurrentCulture), "My Message");
mocks.VerifyAll();
}
[Test]
public void GetMessageParentMessageSource()
{
object[] args = new object[] {"arguments"};
IMessageSource parentSource = mocks.StrictMock<IMessageSource>();
Expect.Call(parentSource.GetMessage("null", null, CultureInfo.CurrentCulture, args)).Return(
"my parent message");
IMessageSource parentSource = A.Fake<IMessageSource>();
A.CallTo(() => parentSource.GetMessage("null", null, CultureInfo.CurrentCulture, A<object[]>._)).Returns("my parent message");
ParentMessageSource = parentSource;
mocks.ReplayAll();
Assert.AreEqual("my parent message", GetMessage("null", "message", CultureInfo.CurrentCulture, args[0]));
mocks.VerifyAll();
}
[Test]
public void GetMessageResolvableDefaultMessage()
{
IMessageSourceResolvable res = mocks.StrictMock<IMessageSourceResolvable>();
Expect.Call(res.DefaultMessage).Return("MyDefaultMessage").Repeat.AtLeastOnce();
Expect.Call(res.GetCodes()).Return(null);
Expect.Call(res.GetArguments()).Return(null);
mocks.ReplayAll();
IMessageSourceResolvable res = A.Fake<IMessageSourceResolvable>();
A.CallTo(() => res.DefaultMessage).Returns("MyDefaultMessage");
A.CallTo(() => res.GetCodes()).Returns(null);
A.CallTo(() => res.GetArguments()).Returns(null);
Assert.AreEqual("MyDefaultMessage", GetMessage(res, CultureInfo.CurrentCulture), "Default");
mocks.VerifyAll();
}
[Test]
public void GetMessageResolvableReturnsFirstCode()
{
IMessageSourceResolvable res = A.Fake<IMessageSourceResolvable>();
A.CallTo(() => res.DefaultMessage).Returns(null);
A.CallTo(() => res.GetCodes()).Returns(new string[] {"null"});
A.CallTo(() => res.GetArguments()).Returns(null);
IMessageSourceResolvable res = mocks.StrictMock<IMessageSourceResolvable>();
Expect.Call(res.DefaultMessage).Return(null).Repeat.AtLeastOnce();
Expect.Call(res.GetCodes()).Return(new string[] {"null"});
Expect.Call(res.GetArguments()).Return(null).Repeat.AtLeastOnce();
mocks.ReplayAll();
UseCodeAsDefaultMessage = true;
Assert.AreEqual("null", GetMessage(res, CultureInfo.CurrentCulture), "Code");
mocks.VerifyAll();
Assert.AreEqual("null", GetMessage(res, CultureInfo.CurrentCulture), "Code");
}
[Test]
public void GetMessageResolvableNoValidMessage()
{
IMessageSourceResolvable res = mocks.StrictMock<IMessageSourceResolvable>();
Expect.Call(res.DefaultMessage).Return(null).Repeat.AtLeastOnce();
Expect.Call(res.GetCodes()).Return(null);
Expect.Call(res.GetArguments()).Return(null).Repeat.AtLeastOnce();
mocks.ReplayAll();
IMessageSourceResolvable res = A.Fake<IMessageSourceResolvable>();
A.CallTo(() => res.DefaultMessage).Returns(null);
A.CallTo(() => res.GetCodes()).Returns(null);
A.CallTo(() => res.GetArguments()).Returns(null);
Assert.Throws<NoSuchMessageException>(() => GetMessage(res, CultureInfo.CurrentCulture));
}
[Test]
public void GetMessageResolvableValidMessageAndCode()
{
IMessageSourceResolvable res = mocks.StrictMock<IMessageSourceResolvable>();
Expect.Call(res.GetCodes()).Return(new string[] {"code1"});
Expect.Call(res.GetArguments()).Return(new object[] { "my", "arguments" }).Repeat.AtLeastOnce();
mocks.ReplayAll();
IMessageSourceResolvable res = A.Fake<IMessageSourceResolvable>();
A.CallTo(() => res.GetCodes()).Returns(new string[] {"code1"});
A.CallTo(() => res.GetArguments()).Returns(new object[] { "my", "arguments" });
Assert.AreEqual("my arguments", GetMessage(res, CultureInfo.CurrentCulture), "Resolve");
mocks.VerifyAll();
}
[Test]
public void GetMessageResolvableValidMessageAndCodeNullCulture()
{
IMessageSourceResolvable res = mocks.StrictMock<IMessageSourceResolvable>();
Expect.Call(res.GetCodes()).Return(new string[] { "code1" });
Expect.Call(res.GetArguments()).Return(new object[] { "my", "arguments" }).Repeat.AtLeastOnce();
mocks.ReplayAll();
Assert.AreEqual("my arguments", GetMessage(res, null), "Resolve");
mocks.VerifyAll();
IMessageSourceResolvable res = A.Fake<IMessageSourceResolvable>();
A.CallTo(() => res.GetCodes()).Returns(new string[] { "code1" });
A.CallTo(() => res.GetArguments()).Returns(new object[] { "my", "arguments" });
Assert.AreEqual("my arguments", GetMessage(res, null), "Resolve");
}
[Test]
@@ -179,28 +160,25 @@ namespace Spring.Context.Support
[Test]
public void GetMessageWithResolvableArguments()
{
IMessageSourceResolvable res = mocks.StrictMock<IMessageSourceResolvable>();
Expect.Call(res.GetCodes()).Return(new string[] { "code1" });
Expect.Call(res.GetArguments()).Return(new object[] { "my", "resolvable" }).Repeat.AtLeastOnce();
mocks.ReplayAll();
IMessageSourceResolvable res = A.Fake<IMessageSourceResolvable>();
A.CallTo(() => res.GetCodes()).Returns(new string[] { "code1" });
A.CallTo(() => res.GetArguments()).Returns(new object[] { "my", "resolvable" });
Assert.AreEqual("spring my resolvable", GetMessage("code2", CultureInfo.CurrentCulture, new object[] {"spring", res}), "Resolve");
mocks.VerifyAll();
}
[Test]
public void GetMessageResolvableValidMessageAndCodNullMessageFormat()
{
IMessageSourceResolvable res = mocks.StrictMock<IMessageSourceResolvable>();
Expect.Call(res.DefaultMessage).Return("myDefaultMessage").Repeat.AtLeastOnce();
Expect.Call(res.GetCodes()).Return(new string[] { "nullCode" });
Expect.Call(res.GetArguments()).Return(null).Repeat.AtLeastOnce();
mocks.ReplayAll();
IMessageSourceResolvable res = A.Fake<IMessageSourceResolvable>();
A.CallTo(() => res.DefaultMessage).Returns("myDefaultMessage");
A.CallTo(() => res.GetCodes()).Returns(new string[] { "nullCode" });
A.CallTo(() => res.GetArguments()).Returns(null);
Assert.AreEqual("myDefaultMessage", GetMessage(res, null), "Resolve");
mocks.VerifyAll();
}
private void resetMe()
private void ResetMe()
{
ParentMessageSource = null;
UseCodeAsDefaultMessage = false;
@@ -215,7 +193,7 @@ namespace Spring.Context.Support
else if (code.Equals("nullCode"))
{
return null;
}
}
else
{
return "{0} {1}";

View File

@@ -18,13 +18,11 @@
#endregion
#region Imports
using System.Text;
using NUnit.Framework;
using Rhino.Mocks;
#endregion
using FakeItEasy;
using NUnit.Framework;
namespace Spring.Context.Support
{
@@ -34,14 +32,11 @@ namespace Spring.Context.Support
[TestFixture]
public sealed class DefaultMessageSourceResolvableTests
{
private MockRepository mocks;
[SetUp]
public void Init()
{
mocks = new MockRepository();
}
[Test]
public void InstantiationWithASingleCodeDefaultsToEmptyDefaultMessage()
{
@@ -49,7 +44,7 @@ namespace Spring.Context.Support
Assert.AreEqual(string.Empty, dmr.DefaultMessage,
"Not defaulting to non null empty string value (it must).");
}
[Test]
public void NullLastCode()
{
@@ -86,16 +81,15 @@ namespace Spring.Context.Support
[Test]
public void DefaultResolvableFromExistingResolvable()
{
IMessageSourceResolvable res = mocks.StrictMock<IMessageSourceResolvable>();
Expect.Call(res.DefaultMessage).Return("defaultMessageFromMock").Repeat.AtLeastOnce();
Expect.Call(res.GetCodes()).Return(new string[] { "code1FromMock" });
Expect.Call(res.GetArguments()).Return(new object[] { "ArgumentFromMock" }).Repeat.AtLeastOnce();
mocks.ReplayAll();
DefaultMessageSourceResolvable dmr = new DefaultMessageSourceResolvable(res);
IMessageSourceResolvable res = A.Fake<IMessageSourceResolvable>();
A.CallTo(() => res.DefaultMessage).Returns("defaultMessageFromMock");
A.CallTo(() => res.GetCodes()).Returns(new string[] { "code1FromMock" });
A.CallTo(() => res.GetArguments()).Returns(new object[] { "ArgumentFromMock" });
DefaultMessageSourceResolvable dmr = new DefaultMessageSourceResolvable(res);
Assert.AreEqual("defaultMessageFromMock", dmr.DefaultMessage, "default");
Assert.AreEqual("code1FromMock", dmr.LastCode, "codes");
Assert.AreEqual("ArgumentFromMock", (dmr.GetArguments())[0], "arguments");
mocks.VerifyAll();
}
private string getResolvableString()

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
* Copyright © 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,14 +18,12 @@
#endregion
#region Imports
using System;
using System.Globalization;
using NUnit.Framework;
using Rhino.Mocks;
#endregion
using FakeItEasy;
using NUnit.Framework;
namespace Spring.Context.Support
{
@@ -36,16 +34,14 @@ namespace Spring.Context.Support
[TestFixture]
public sealed class DelegatingMessageSourceTests
{
private MockRepository mocks;
private const string LookupKey = "rick";
private const string LookupKey = "rick";
private IMessageSource _messageSource;
private IMessageSource MockMessageSource
{
get
{
return _messageSource;
return _messageSource;
}
}
@@ -55,16 +51,14 @@ namespace Spring.Context.Support
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
_messageSource = mocks.StrictMock<IMessageSource>();
_messageSource = A.Fake<IMessageSource>();
}
[Test]
public void Instantiation()
{
DelegatingMessageSource source = new DelegatingMessageSource();
Assert.IsNotNull(source.ParentMessageSource,
"ParentMessageSource property must *never* be null.");
Assert.IsNotNull(source.ParentMessageSource, "ParentMessageSource property must *never* be null.");
}
[Test]
@@ -80,14 +74,11 @@ namespace Spring.Context.Support
[Test]
public void GetMessage()
{
const string expectedName = "Rick Evans";
Expect.Call(MockMessageSource.GetMessage(LookupKey)).Return(expectedName);
DelegatingMessageSource source
= new DelegatingMessageSource(MockMessageSource);
mocks.ReplayAll();
const string expectedName = "Rick Evans";
A.CallTo(() => MockMessageSource.GetMessage(LookupKey)).Returns(expectedName);
DelegatingMessageSource source = new DelegatingMessageSource(MockMessageSource);
string name = source.GetMessage(LookupKey);
Assert.AreEqual(expectedName, name);
mocks.VerifyAll();
}
[Test]
@@ -101,13 +92,10 @@ namespace Spring.Context.Support
public void GetMessageWithCulture()
{
const string expectedName = "Rick Evans";
Expect.Call(MockMessageSource.GetMessage(LookupKey, CultureInfo.InvariantCulture)).Return(expectedName);
DelegatingMessageSource source
= new DelegatingMessageSource(MockMessageSource);
mocks.ReplayAll();
A.CallTo(() => MockMessageSource.GetMessage(LookupKey, CultureInfo.InvariantCulture)).Returns(expectedName);
DelegatingMessageSource source = new DelegatingMessageSource(MockMessageSource);
string name = source.GetMessage(LookupKey, CultureInfo.InvariantCulture);
Assert.AreEqual(expectedName, name);
mocks.VerifyAll();
}
[Test]
@@ -121,13 +109,10 @@ namespace Spring.Context.Support
public void GetMessageWithParams()
{
const string expectedName = "Rick Evans";
Expect.Call(MockMessageSource.GetMessage(LookupKey, new string[] {"Rick", "Evans"})).Return(expectedName);
DelegatingMessageSource source
= new DelegatingMessageSource(MockMessageSource);
mocks.ReplayAll();
string name = source.GetMessage(LookupKey, "Rick", "Evans");
A.CallTo(() => MockMessageSource.GetMessage(LookupKey, new string[] {"Rick", "Evans"})).Returns(expectedName);
DelegatingMessageSource source = new DelegatingMessageSource(MockMessageSource);
string name = source.GetMessage(LookupKey, "Rick", "Evans");
Assert.AreEqual(expectedName, name);
mocks.VerifyAll();
}
[Test]
@@ -141,14 +126,10 @@ namespace Spring.Context.Support
public void GetMessageWithCultureAndParams()
{
const string expectedName = "Rick Evans";
Expect.Call(MockMessageSource.GetMessage(LookupKey, CultureInfo.InvariantCulture, new string[] {"Rick", "Evans"}))
.Return(expectedName);
DelegatingMessageSource source
= new DelegatingMessageSource(MockMessageSource);
mocks.ReplayAll();
A.CallTo(() => MockMessageSource.GetMessage(LookupKey, CultureInfo.InvariantCulture, new string[] {"Rick", "Evans"})).Returns(expectedName);
DelegatingMessageSource source = new DelegatingMessageSource(MockMessageSource);
string name = source.GetMessage(LookupKey, CultureInfo.InvariantCulture, "Rick", "Evans");
Assert.AreEqual(expectedName, name);
mocks.VerifyAll();
}
[Test]
@@ -162,14 +143,11 @@ namespace Spring.Context.Support
public void GetMessageWithMessageSourceResolvableAndCulture()
{
const string expectedName = "Rick Evans";
DelegatingMessageSource source
= new DelegatingMessageSource(MockMessageSource);
Expect.Call(MockMessageSource.GetMessage((IMessageSourceResolvable)null, CultureInfo.InvariantCulture)).Return(expectedName);
mocks.ReplayAll();
string name = source.GetMessage(
(IMessageSourceResolvable) null, CultureInfo.InvariantCulture);
DelegatingMessageSource source = new DelegatingMessageSource(MockMessageSource);
A.CallTo(() => MockMessageSource.GetMessage((IMessageSourceResolvable)null, CultureInfo.InvariantCulture)).Returns(expectedName);
string name = source.GetMessage((IMessageSourceResolvable) null, CultureInfo.InvariantCulture);
Assert.AreEqual(expectedName, name);
mocks.VerifyAll();
}
[Test]
@@ -177,16 +155,12 @@ namespace Spring.Context.Support
{
const string expectedName = "Rick Evans";
IMessageSourceResolvable resolvable = mocks.StrictMock<IMessageSourceResolvable>();
Expect.Call(resolvable.DefaultMessage).Return(expectedName);
Expect.Call(resolvable.DefaultMessage).Return(expectedName);
IMessageSourceResolvable resolvable = A.Fake<IMessageSourceResolvable>();
A.CallTo(() => resolvable.DefaultMessage).Returns(expectedName);
DelegatingMessageSource source = new DelegatingMessageSource();
mocks.ReplayAll();
string name = source.GetMessage(resolvable, CultureInfo.InvariantCulture);
Assert.AreEqual(expectedName, name);
//mock.Verify();
mocks.VerifyAll();
}
[Test]
@@ -211,13 +185,10 @@ namespace Spring.Context.Support
public void GetResourceObject()
{
const string expectedName = "Rick Evans";
Expect.Call(MockMessageSource.GetResourceObject(LookupKey)).Return(expectedName);
DelegatingMessageSource source
= new DelegatingMessageSource(MockMessageSource);
mocks.ReplayAll();
A.CallTo(() => MockMessageSource.GetResourceObject(LookupKey)).Returns(expectedName);
DelegatingMessageSource source = new DelegatingMessageSource(MockMessageSource);
string name = (string) source.GetResourceObject(LookupKey);
Assert.AreEqual(expectedName, name);
mocks.VerifyAll();
}
[Test]
@@ -231,13 +202,10 @@ namespace Spring.Context.Support
public void GetResourceObjectWithCulture()
{
const string expectedName = "Rick Evans";
Expect.Call(MockMessageSource.GetResourceObject(LookupKey, CultureInfo.InvariantCulture)).Return(expectedName);
DelegatingMessageSource source
= new DelegatingMessageSource(MockMessageSource);
mocks.ReplayAll();
A.CallTo(() => MockMessageSource.GetResourceObject(LookupKey, CultureInfo.InvariantCulture)).Returns(expectedName);
DelegatingMessageSource source = new DelegatingMessageSource(MockMessageSource);
string name = (string) source.GetResourceObject(LookupKey, CultureInfo.InvariantCulture);
Assert.AreEqual(expectedName, name);
mocks.VerifyAll();
}
[Test]
@@ -250,12 +218,9 @@ namespace Spring.Context.Support
[Test]
public void ApplyResources()
{
MockMessageSource.ApplyResources((object) 12, "rick", CultureInfo.InvariantCulture);
DelegatingMessageSource source
= new DelegatingMessageSource(MockMessageSource);
mocks.ReplayAll();
MockMessageSource.ApplyResources(12, "rick", CultureInfo.InvariantCulture);
DelegatingMessageSource source = new DelegatingMessageSource(MockMessageSource);
source.ApplyResources(12, "rick", CultureInfo.InvariantCulture);
mocks.VerifyAll();
}
[Test]

View File

@@ -20,8 +20,9 @@
using System.Globalization;
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Globalization;
namespace Spring.Context.Support
@@ -47,29 +48,25 @@ namespace Spring.Context.Support
private readonly string MSGRESULT = "my message";
private MockRepository mocks;
private IMessageSource mockMsgSource;
private IMessageSourceResolvable mockMsgSourceResolvable;
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
mockMsgSource = mocks.StrictMock<IMessageSource>();
mockMsgSourceResolvable = mocks.StrictMock<IMessageSourceResolvable>();
mockMsgSource = A.Fake<IMessageSource>();
mockMsgSourceResolvable = A.Fake<IMessageSourceResolvable>();
}
[TearDown]
public void TearDown()
{
mocks.VerifyAll();
}
[Test]
public void GetMessageCodeCultureArgs()
{
Expect.Call(mockMsgSource.GetMessage(MSGCODE, MSGCULTURE, MSGARGS)).Return(MSGRESULT);
mocks.ReplayAll();
A.CallTo(() => mockMsgSource.GetMessage(MSGCODE, MSGCULTURE, MSGARGS)).Returns(MSGRESULT);
MessageSourceAccessor msgSourceAccessor = new MessageSourceAccessor(mockMsgSource);
Assert.AreEqual(MSGRESULT, msgSourceAccessor.GetMessage(MSGCODE, MSGCULTURE, MSGARGS));
@@ -78,8 +75,7 @@ namespace Spring.Context.Support
[Test]
public void GetMessageCodeArgs()
{
Expect.Call(mockMsgSource.GetMessage(MSGCODE, MSGCULTURE, MSGARGS)).Return(MSGRESULT);
mocks.ReplayAll();
A.CallTo(() => mockMsgSource.GetMessage(MSGCODE, MSGCULTURE, MSGARGS)).Returns(MSGRESULT);
MessageSourceAccessor msgSourceAccessor = new MessageSourceAccessor(mockMsgSource, MSGCULTURE);
Assert.AreEqual(MSGRESULT, msgSourceAccessor.GetMessage(MSGCODE, MSGARGS));
@@ -88,8 +84,7 @@ namespace Spring.Context.Support
[Test]
public void GetMessageCodeArgsDefaultsToCurrentUICulture()
{
Expect.Call(mockMsgSource.GetMessage(MSGCODE, CultureInfo.CurrentUICulture, MSGARGS)).Return(MSGRESULT);
mocks.ReplayAll();
A.CallTo(() => mockMsgSource.GetMessage(MSGCODE, CultureInfo.CurrentUICulture, MSGARGS)).Returns(MSGRESULT);
MessageSourceAccessor msgSourceAccessor = new MessageSourceAccessor(mockMsgSource);
Assert.AreEqual(MSGRESULT, msgSourceAccessor.GetMessage(MSGCODE, MSGARGS));
@@ -98,8 +93,7 @@ namespace Spring.Context.Support
[Test]
public void GetMessageCodeCulture()
{
Expect.Call(mockMsgSource.GetMessage(MSGCODE, MSGCULTURE)).Return(MSGRESULT);
mocks.ReplayAll();
A.CallTo(() => mockMsgSource.GetMessage(MSGCODE, MSGCULTURE)).Returns(MSGRESULT);
MessageSourceAccessor msgSourceAccessor = new MessageSourceAccessor(mockMsgSource);
Assert.AreEqual(MSGRESULT, msgSourceAccessor.GetMessage(MSGCODE, MSGCULTURE));
@@ -108,8 +102,7 @@ namespace Spring.Context.Support
[Test]
public void GetMessageCodeDefaultsToCurrentUICulture()
{
Expect.Call(mockMsgSource.GetMessage(MSGCODE, CultureInfo.CurrentUICulture)).Return(MSGRESULT);
mocks.ReplayAll();
A.CallTo(() => mockMsgSource.GetMessage(MSGCODE, CultureInfo.CurrentUICulture)).Returns(MSGRESULT);
MessageSourceAccessor msgSourceAccessor = new MessageSourceAccessor(mockMsgSource);
Assert.AreEqual(MSGRESULT, msgSourceAccessor.GetMessage(MSGCODE));
@@ -118,8 +111,7 @@ namespace Spring.Context.Support
[Test]
public void GetMessageResolvableCulture()
{
Expect.Call(mockMsgSource.GetMessage(mockMsgSourceResolvable, MSGCULTURE)).Return(MSGRESULT);
mocks.ReplayAll();
A.CallTo(() => mockMsgSource.GetMessage(mockMsgSourceResolvable, MSGCULTURE)).Returns(MSGRESULT);
MessageSourceAccessor msgSourceAccessor = new MessageSourceAccessor(mockMsgSource);
Assert.AreEqual(MSGRESULT, msgSourceAccessor.GetMessage(mockMsgSourceResolvable, MSGCULTURE));
@@ -128,8 +120,7 @@ namespace Spring.Context.Support
[Test]
public void GetMessageResolvableDefaultsToCurrentUICulture()
{
Expect.Call(mockMsgSource.GetMessage(mockMsgSourceResolvable, CultureInfo.CurrentUICulture)).Return(MSGRESULT);
mocks.ReplayAll();
A.CallTo(() => mockMsgSource.GetMessage(mockMsgSourceResolvable, CultureInfo.CurrentUICulture)).Returns(MSGRESULT);
MessageSourceAccessor msgSourceAccessor = new MessageSourceAccessor(mockMsgSource);
Assert.AreEqual(MSGRESULT, msgSourceAccessor.GetMessage(mockMsgSourceResolvable));

View File

@@ -108,17 +108,17 @@ namespace Spring.Context.Support
// MessageSourceAccessor functionality
MessageSourceAccessor accessor = new MessageSourceAccessor(ac);
Assert.AreEqual("message3", accessor.GetMessage("code3", CultureInfo.CurrentUICulture, (object[])null));
Assert.AreEqual("message3", accessor.GetMessage("code3", CultureInfo.CurrentUICulture, null));
// IMessageSourceResolveable
Assert.AreEqual("message3", ac.GetMessage("code3", CultureInfo.CurrentUICulture, (object[])null));
Assert.AreEqual("message3", ac.GetMessage("code3", CultureInfo.CurrentUICulture, null));
IMessageSourceResolvable resolvable = new DefaultMessageSourceResolvable("code3");
Assert.AreEqual("message3", ac.GetMessage(resolvable, CultureInfo.CurrentUICulture));
resolvable = new DefaultMessageSourceResolvable(new string[] { "code4", "code3" });
Assert.AreEqual("message3", ac.GetMessage(resolvable, CultureInfo.CurrentUICulture));
Assert.AreEqual("message3", ac.GetMessage("code3", CultureInfo.CurrentUICulture, (object[])null));
Assert.AreEqual("message3", ac.GetMessage("code3", CultureInfo.CurrentUICulture, null));
resolvable = new DefaultMessageSourceResolvable(new string[] { "code4", "code3" });
Assert.AreEqual("message3", ac.GetMessage(resolvable, CultureInfo.CurrentUICulture));
@@ -130,7 +130,7 @@ namespace Spring.Context.Support
Assert.AreEqual("default", ac.GetMessage(null, "default", CultureInfo.CurrentUICulture, null));
Assert.AreEqual("default", ac.GetMessage(null, "default", CultureInfo.CurrentUICulture, arguments));
/* not supported
/* not supported
Assert.AreEqual("{0}, default", ac.GetMessage(null, "{0}, default", CultureInfo.CurrentUICulture, null));
*/
@@ -142,7 +142,7 @@ namespace Spring.Context.Support
resolvable = new DefaultMessageSourceResolvable(null, arguments, "default");
Assert.AreEqual("default", ac.GetMessage(resolvable, CultureInfo.CurrentUICulture));
/* not supported
/* not supported
resolvable = new DefaultMessageSourceResolvable(null, null, "{0}, default");
Assert.AreEqual("{0}, default", ac.GetMessage(resolvable, CultureInfo.CurrentUICulture));
*/
@@ -154,12 +154,12 @@ namespace Spring.Context.Support
// test message args
Assert.AreEqual("Arg1, Arg2", ac.GetMessage("hello", CultureInfo.CurrentUICulture, new object[] { "Arg1", "Arg2" }));
/* not supported
/* not supported
Assert.AreEqual("{0}, {1}", ac.GetMessage("hello", CultureInfo.CurrentUICulture, null));
*/
/* not supported
/* not supported
Assert.AreEqual("Hello\nWorld", ac.GetMessage("escaped"));
}
else
@@ -277,7 +277,7 @@ namespace Spring.Context.Support
Assert.AreEqual("Ово је Spring.NET",
msgSource.GetMessage("MyMessage", new CultureInfo(CultureInfoUtils.SerbianCyrillicCultureName),
new object[] { "Spring", ".NET" }), "message not as expected");
Assert.AreEqual("Visual Studio voli Spring.NET",
msgSource.GetMessage("MyNewMessage", new CultureInfo(CultureInfoUtils.SerbianCyrillicCultureName), new object[] { "Spring", ".NET" }), "message not as expected");

View File

@@ -18,45 +18,39 @@
#endregion
#region Imports
using System;
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
#endregion
namespace Spring.Core.TypeResolution
{
/// <summary>
/// Unit tests for the CachedTypeResolver class.
/// <summary>
/// Unit tests for the CachedTypeResolver class.
/// </summary>
/// <author>Rick Evans</author>
[TestFixture]
[TestFixture]
public sealed class CachedTypeResolverTests
{
private MockRepository mocks;
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
}
[Test]
public void ResolveWithNullTypeName() {
ITypeResolver mockResolver = (ITypeResolver) mocks.DynamicMock(typeof(ITypeResolver));
public void ResolveWithNullTypeName()
{
ITypeResolver mockResolver = A.Fake<ITypeResolver>();
CachedTypeResolver resolver = new CachedTypeResolver(mockResolver);
Assert.Throws<TypeLoadException>(() => resolver.Resolve(null));
}
[Test]
public void InstantiateWithNullTypeResolver()
{
[Test]
public void InstantiateWithNullTypeResolver()
{
Assert.Throws<ArgumentNullException>(() => new CachedTypeResolver(null));
}
}
}
}
}

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
* Copyright © 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -324,7 +324,7 @@ namespace Spring.Expressions
[Test(Description = "SPRNET-944")]
public void DateTests()
{
string dateLiteral = (string)ExpressionEvaluator.GetValue(null, "'date'");
string dateLiteral = (string)ExpressionEvaluator.GetValue(null, "'date'");
Assert.AreEqual("date", dateLiteral);
}
@@ -1739,11 +1739,11 @@ namespace Spring.Expressions
result = (double) ExpressionEvaluator.GetValue(null, "#max(5,25)", vars);
Assert.AreEqual(25, result);
}
private delegate double DoubleFunction(double arg);
private double Sqrt(double arg)
{
return Math.Sqrt(arg);
@@ -1820,7 +1820,7 @@ namespace Spring.Expressions
[Test]
public void TestCustomCollectionProcessor()
{
// Test for the purposes of creating documentation example.
// Test for the purposes of creating documentation example.
Dictionary<string, object> vars = new Dictionary<string, object>();
vars["EvenSum"] = new IntEvenSumCollectionProcessor();
Assert.AreEqual(6, ExpressionEvaluator.GetValue(null, "{1, 2, 3, 4}.EvenSum()", vars));
@@ -1841,7 +1841,7 @@ namespace Spring.Expressions
if ((int)item % 2 == 0)
{
total = NumberUtils.Add(total, item);
}
}
}
else
{
@@ -2308,26 +2308,26 @@ namespace Spring.Expressions
expField.SetValue(o, TestEnumTypePropertyClass.ESampleEnumType.Trunk);
Assert.AreEqual(TestEnumTypePropertyClass.ESampleEnumType.Trunk, o.SampleEnumField);
expField.SetValue(o, ((Int16)1));
expField.SetValue(o, (short) 1);
Assert.AreEqual(TestEnumTypePropertyClass.ESampleEnumType.Trunk, o.SampleEnumField);
expField.SetValue(o, ((Int32)1));
expField.SetValue(o, 1);
Assert.AreEqual(TestEnumTypePropertyClass.ESampleEnumType.Trunk, o.SampleEnumField);
expField.SetValue(o, ((Int64)1));
expField.SetValue(o, (long) 1);
Assert.AreEqual(TestEnumTypePropertyClass.ESampleEnumType.Trunk, o.SampleEnumField);
// test property set operations
expProperty.SetValue(o, TestEnumTypePropertyClass.ESampleEnumType.Trunk);
Assert.AreEqual(TestEnumTypePropertyClass.ESampleEnumType.Trunk, o.SampleEnumField);
expProperty.SetValue(o, ((Int16)1));
expProperty.SetValue(o, (short) 1);
Assert.AreEqual(TestEnumTypePropertyClass.ESampleEnumType.Trunk, o.SampleEnumField);
expProperty.SetValue(o, ((Int32)1));
expProperty.SetValue(o, 1);
Assert.AreEqual(TestEnumTypePropertyClass.ESampleEnumType.Trunk, o.SampleEnumField);
expProperty.SetValue(o, ((Int64)1));
expProperty.SetValue(o, (long) 1);
Assert.AreEqual(TestEnumTypePropertyClass.ESampleEnumType.Trunk, o.SampleEnumField);
expProperty.SetValue(o, "Trunk");
@@ -2335,7 +2335,7 @@ namespace Spring.Expressions
try
{
expProperty.SetValue(o, ((double)1.0));
expProperty.SetValue(o, 1.0);
Assert.Fail("should throw");
}
catch (TypeMismatchException e)

View File

@@ -18,17 +18,14 @@
#endregion
#region Imports
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
#endregion
namespace Spring.Globalization.Formatters
{
/// <summary>
///
///
/// </summary>
/// <author>Erich Eichinger</author>
[TestFixture]
@@ -47,7 +44,7 @@ namespace Spring.Globalization.Formatters
public virtual string DoFilterValueToParse(string value)
{
return base.FilterValueToParse(value);
return base.FilterValueToParse(value);
}
protected override object FilterValueToFormat(object value)
@@ -65,29 +62,24 @@ namespace Spring.Globalization.Formatters
[Test]
public void FiltersOnParseAndFormat()
{
MockRepository mocks = new MockRepository();
IFormatter underlyingFormatter = mocks.StrictMock<IFormatter>();
TestFilteringFormatter formatter = (TestFilteringFormatter) mocks.PartialMock(typeof (TestFilteringFormatter), underlyingFormatter);
IFormatter underlyingFormatter = A.Fake<IFormatter>();
TestFilteringFormatter formatter = A.Fake<TestFilteringFormatter>(x => x
.CallsBaseMethods()
.WithArgumentsForConstructor(new[] {underlyingFormatter}));
string inputText = "inputText";
string filteredInputText = "filteredInputText";
object outputValue = new object();
object filteredOutputValue = new object();
using(mocks.Ordered())
{
Expect.Call(formatter.DoFilterValueToParse(inputText)).Return(filteredInputText);
Expect.Call(underlyingFormatter.Parse(filteredInputText)).Return(outputValue);
A.CallTo(() => formatter.DoFilterValueToParse(inputText)).Returns(filteredInputText);
A.CallTo(() => underlyingFormatter.Parse(filteredInputText)).Returns(outputValue);
Expect.Call(formatter.DoFilterValueToFormat(outputValue)).Return(filteredOutputValue);
Expect.Call(underlyingFormatter.Format(filteredOutputValue)).Return(inputText);
}
mocks.ReplayAll();
A.CallTo(() => formatter.DoFilterValueToFormat(outputValue)).Returns(filteredOutputValue);
A.CallTo(() => underlyingFormatter.Format(filteredOutputValue)).Returns(inputText);
Assert.AreSame(outputValue, formatter.Parse(inputText));
Assert.AreEqual(inputText, formatter.Format(outputValue));
mocks.VerifyAll();
}
}
}

View File

@@ -18,13 +18,11 @@
#endregion
#region Imports
using System;
using NUnit.Framework;
using Rhino.Mocks;
#endregion
using FakeItEasy;
using NUnit.Framework;
namespace Spring.Objects.Factory.Config
{
@@ -35,41 +33,38 @@ namespace Spring.Objects.Factory.Config
[TestFixture]
public sealed class AbstractFactoryObjectTests
{
private MockRepository mocks;
[SetUp]
public void Setup()
{
mocks = new MockRepository();
}
[Test]
public void DisposeCallbackIsNotInvokedOnDisposeIfInPrototypeMode()
{
IDisposable disposable = mocks.StrictMock<IDisposable>();
IDisposable disposable = A.Fake<IDisposable>();
DummyFactoryObject factory = new DummyFactoryObject(disposable);
mocks.ReplayAll();
factory.IsSingleton = false;
factory.GetObject();
factory.Dispose();
// in prototype mode, so the Dispose() method of the object must not be called...
mocks.VerifyAll();
A.CallTo(() => disposable.Dispose()).MustNotHaveHappened();
}
[Test]
public void DisposeCallbackIsInvokedOnDispose()
{
IDisposable disposable = mocks.StrictMock<IDisposable>();
disposable.Dispose();
LastCall.On(disposable).Repeat.Once();
DummyFactoryObject factory = new DummyFactoryObject(disposable);
mocks.ReplayAll();
IDisposable disposable = A.Fake<IDisposable>();
DummyFactoryObject factory = new DummyFactoryObject(disposable);
factory.AfterPropertiesSet();
factory.Dispose();
mocks.VerifyAll();
A.CallTo(() => disposable.Dispose()).MustHaveHappenedOnceExactly();
}
private sealed class DummyFactoryObject : AbstractFactoryObject
private sealed class DummyFactoryObject : AbstractFactoryObject
{
public object theObject;

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
* Copyright © 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -72,7 +72,7 @@ namespace Spring.Objects.Factory.Config
public void TestLiveVariablesResolutionWithTestDriven()
{
CommandLineArgsVariableSource vs = new CommandLineArgsVariableSource();
Assert.IsTrue(((string) vs.ResolveVariable("AssemblyName")).StartsWith("TestDriven.TestRunner.Server"));
Assert.IsTrue(vs.ResolveVariable("AssemblyName").StartsWith("TestDriven.TestRunner.Server"));
}
}
}

View File

@@ -18,16 +18,14 @@
#endregion
#region Imports
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using NUnit.Framework;
using Rhino.Mocks;
#endregion
using FakeItEasy;
using NUnit.Framework;
namespace Spring.Objects.Factory.Config
{
@@ -38,15 +36,12 @@ namespace Spring.Objects.Factory.Config
[TestFixture]
public sealed class CustomConverterConfigurerTests
{
private MockRepository mocks;
private IConfigurableListableObjectFactory factory;
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
factory = mocks.StrictMock<IConfigurableListableObjectFactory>();
factory = A.Fake<IConfigurableListableObjectFactory>();
}
[Test]
@@ -93,9 +88,6 @@ namespace Spring.Objects.Factory.Config
CustomConverterConfigurer config = new CustomConverterConfigurer();
config.CustomConverters = null;
config.PostProcessObjectFactory(factory);
mocks.ReplayAll();
mocks.VerifyAll();
}
[Test]
@@ -106,21 +98,16 @@ namespace Spring.Objects.Factory.Config
DateTimeConverter dateTimeConverter = new DateTimeConverter();
Type colorType = typeof(Color);
ColorConverter colorConverter = new ColorConverter();
converters.Add(dateTimeType, dateTimeConverter);
converters.Add(colorType, colorConverter);
factory.RegisterCustomConverter(dateTimeType, dateTimeConverter);
factory.RegisterCustomConverter(colorType, colorConverter);
mocks.ReplayAll();
CustomConverterConfigurer config = new CustomConverterConfigurer();
config.CustomConverters = converters;
config.PostProcessObjectFactory(factory);
mocks.VerifyAll();
}
}
}

View File

@@ -18,13 +18,11 @@
#endregion
#region Imports
using System;
using NUnit.Framework;
using Rhino.Mocks;
#endregion
using FakeItEasy;
using NUnit.Framework;
namespace Spring.Objects.Factory.Config
{
@@ -36,28 +34,23 @@ namespace Spring.Objects.Factory.Config
[TestFixture]
public sealed class ObjectFactoryCreatingFactoryObjectTests
{
private MockRepository mocks;
[SetUp]
public void Setup()
{
mocks = new MockRepository();
}
[Test]
public void SunnyDay()
{
TestObject dude = new TestObject("Rick Evans", 30);
IObjectFactory objectFactory = mocks.StrictMock<IObjectFactory>();
IObjectFactory objectFactory = A.Fake<IObjectFactory>();
const string lookupObjectName = "rick";
Expect.Call(objectFactory.GetObject(lookupObjectName)).Return(dude).Repeat.Twice();
A.CallTo(() => objectFactory.GetObject(lookupObjectName)).Returns(dude).Twice();
ObjectFactoryCreatingFactoryObject factory = new ObjectFactoryCreatingFactoryObject();
factory.ObjectFactory = objectFactory;
factory.TargetObjectName = lookupObjectName;
factory.AfterPropertiesSet();
mocks.ReplayAll();
IGenericObjectFactory gof = (IGenericObjectFactory) factory.GetObject();
IGenericObjectFactory gofOther = (IGenericObjectFactory) factory.GetObject();
Assert.IsTrue(Object.ReferenceEquals(gof, gofOther),
@@ -68,23 +61,21 @@ namespace Spring.Objects.Factory.Config
Assert.IsNotNull(two, "Must never return null (IFactoryObject contract).");
Assert.IsTrue(Object.ReferenceEquals(one, two),
"Not returning the same instance.");
mocks.VerifyAll();
}
[Test]
public void PrototypeModeWithSingletonTarget()
{
TestObject dude = new TestObject("Rick Evans", 30);
IObjectFactory objectFactory = mocks.StrictMock<IObjectFactory>();
const string lookupObjectName = "rick";
Expect.Call(objectFactory.GetObject(lookupObjectName)).Return(dude).Repeat.Twice();
TestObject dude = new TestObject("Rick Evans", 30);
IObjectFactory objectFactory = A.Fake<IObjectFactory>();
const string lookupObjectName = "rick";
A.CallTo(() => objectFactory.GetObject(lookupObjectName)).Returns(dude).Twice();
ObjectFactoryCreatingFactoryObject factory = new ObjectFactoryCreatingFactoryObject();
factory.ObjectFactory = objectFactory;
factory.TargetObjectName = lookupObjectName;
factory.IsSingleton = false;
factory.AfterPropertiesSet();
mocks.ReplayAll();
IGenericObjectFactory gofOne = (IGenericObjectFactory) factory.GetObject();
IGenericObjectFactory gofTwo = (IGenericObjectFactory) factory.GetObject();
Assert.IsFalse(Object.ReferenceEquals(gofOne, gofTwo),
@@ -95,7 +86,6 @@ namespace Spring.Objects.Factory.Config
Assert.IsNotNull(two, "Must never return null (IFactoryObject contract).");
Assert.IsTrue(Object.ReferenceEquals(one, two),
"Not returning the same instance to singleton object.");
mocks.VerifyAll();
}
[Test]

View File

@@ -18,115 +18,98 @@
#endregion
#region Imports
using System;
using NUnit.Framework;
using Rhino.Mocks;
#endregion
using FakeItEasy;
using NUnit.Framework;
namespace Spring.Objects.Factory.Config
{
/// <summary>
/// Unit tests for the ObjectReferenceFactoryObject class.
/// <summary>
/// Unit tests for the ObjectReferenceFactoryObject class.
/// </summary>
/// <author>Rick Evans</author>
[TestFixture]
[TestFixture]
public sealed class ObjectReferenceFactoryObjectTests
{
private MockRepository mocks;
private IObjectFactory factory;
private IObjectFactory factory;
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
factory = mocks.StrictMock<IObjectFactory>();
factory = A.Fake<IObjectFactory>();
}
[Test]
public void NullTargetObjectName()
{
ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject();
{
ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject();
// simulate IFactoryObjectAware interface...
Assert.Throws<ArgumentException>(() => fac.ObjectFactory = null);
}
[Test]
public void WhitespaceTargetObjectName()
{
ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject();
fac.TargetObjectName = string.Empty;
[Test]
public void WhitespaceTargetObjectName()
{
ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject();
fac.TargetObjectName = string.Empty;
// simulate IFactoryObjectAware interface...
Assert.Throws<ArgumentException>(() => fac.ObjectFactory = null);
}
[Test]
public void FactoryDoesNotContainTargetObject()
{
Expect.Call(factory.ContainsObject("bojangles")).Return(false);
mocks.ReplayAll();
}
ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject();
fac.TargetObjectName = "bojangles";
try
{
// simulate IFactoryObjectAware interface...
fac.ObjectFactory = factory;
Assert.Fail("Must have bailed with a " +
"NoSuchObjectDefinitionException 'cos the object doesn't " +
"exist in the associated factory.");
}
catch (NoSuchObjectDefinitionException)
{
mocks.VerifyAll();
}
}
[Test]
public void DelegatesThroughToFactoryFor_IsSingleton()
{
Expect.Call(factory.ContainsObject("bojangles")).Return(true);
Expect.Call(factory.IsSingleton("bojangles")).Return(true);
mocks.ReplayAll();
[Test]
public void FactoryDoesNotContainTargetObject()
{
A.CallTo(() => factory.ContainsObject("bojangles")).Returns(false);
ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject();
fac.TargetObjectName = "bojangles";
fac.ObjectFactory = factory;
fac.TargetObjectName = "bojangles";
Assert.IsTrue(fac.IsSingleton);
mocks.VerifyAll();
}
// simulate IFactoryObjectAware interface...
Assert.Throws<NoSuchObjectDefinitionException>(() => fac.ObjectFactory = factory,
"Must have bailed with a " +
"NoSuchObjectDefinitionException 'cos the object doesn't " +
"exist in the associated factory.");
}
[Test]
public void DelegatesThroughToFactoryFor_GetObject()
{
Expect.Call(factory.ContainsObject("bojangles")).Return(true);
Expect.Call(factory.GetObject("bojangles")).Return("Rick");
mocks.ReplayAll();
[Test]
public void DelegatesThroughToFactoryFor_IsSingleton()
{
A.CallTo(() => factory.ContainsObject("bojangles")).Returns(true);
A.CallTo(() => factory.IsSingleton("bojangles")).Returns(true);
ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject();
fac.TargetObjectName = "bojangles";
fac.ObjectFactory = factory;
ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject();
fac.TargetObjectName = "bojangles";
fac.ObjectFactory = factory;
Assert.AreEqual("Rick", fac.GetObject());
mocks.VerifyAll();
}
Assert.IsTrue(fac.IsSingleton);
}
[Test]
public void DelegatesThroughToFactoryFor_ObjectType()
{
Expect.Call(factory.ContainsObject("bojangles")).Return(true);
Expect.Call(factory.GetType("bojangles")).Return(GetType());
mocks.ReplayAll();
[Test]
public void DelegatesThroughToFactoryFor_GetObject()
{
A.CallTo(() => factory.ContainsObject("bojangles")).Returns(true);
A.CallTo(() => factory.GetObject("bojangles")).Returns("Rick");
ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject();
fac.TargetObjectName = "bojangles";
fac.ObjectFactory = factory;
ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject();
fac.TargetObjectName = "bojangles";
fac.ObjectFactory = factory;
Assert.AreEqual(GetType(), fac.ObjectType);
mocks.VerifyAll();
}
Assert.AreEqual("Rick", fac.GetObject());
}
[Test]
public void DelegatesThroughToFactoryFor_ObjectType()
{
A.CallTo(() => factory.ContainsObject("bojangles")).Returns(true);
A.CallTo(() => factory.GetType("bojangles")).Returns(GetType());
ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject();
fac.TargetObjectName = "bojangles";
fac.ObjectFactory = factory;
Assert.AreEqual(GetType(), fac.ObjectType);
}
}
}
}

View File

@@ -18,19 +18,17 @@
#endregion
#region Imports
using System.Collections.Specialized;
using Common.Logging;
using Common.Logging.Simple;
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Context.Support;
using Spring.Core.IO;
using Spring.Objects.Factory.Xml;
#endregion
namespace Spring.Objects.Factory.Config
{
/// <summary>
@@ -40,13 +38,9 @@ namespace Spring.Objects.Factory.Config
[TestFixture]
public sealed class PropertyOverrideConfigurerTests
{
private MockRepository mocks;
[SetUp]
public void Setup()
{
mocks = new MockRepository();
}
/// <summary>
@@ -56,7 +50,7 @@ namespace Spring.Objects.Factory.Config
public void FixtureSetUp()
{
// enable (null appender) logging, just to ensure that the logging code is correct
LogManager.Adapter = new NoOpLoggerFactoryAdapter();
LogManager.Adapter = new NoOpLoggerFactoryAdapter();
}
[Test]
@@ -90,7 +84,7 @@ namespace Spring.Objects.Factory.Config
pvs.Add("Age", 27);
pvs.Add("Name", "Bruno");
ac.RegisterSingleton("tb1", typeof(TestObject), pvs);
pvs = new MutablePropertyValues();
pvs.Add("Properties", "<spring-config><add key=\"tb1.Age\" value=\"99\"/><add key=\"tb1.Name\" value=\"test\"/></spring-config>");
ac.RegisterSingleton("configurer", typeof (PropertyOverrideConfigurer), pvs);
@@ -105,11 +99,11 @@ namespace Spring.Objects.Factory.Config
public void OverridePropertyReference()
{
StaticApplicationContext ac = new StaticApplicationContext();
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.Add("Spouse", new RuntimeObjectReference("spouse1"));
ac.RegisterSingleton("tb1", typeof(TestObject), pvs);
ac.RegisterSingleton("spouse1", typeof(TestObject), new MutablePropertyValues());
ac.RegisterSingleton("spouse2", typeof(TestObject), new MutablePropertyValues());
@@ -144,23 +138,15 @@ namespace Spring.Objects.Factory.Config
[Test]
public void MalformedOverrideKey()
{
IConfigurableListableObjectFactory objectFactory = mocks.StrictMock<IConfigurableListableObjectFactory>();
IConfigurableListableObjectFactory objectFactory = A.Fake<IConfigurableListableObjectFactory>();
IConfigurableListableObjectFactory fac = objectFactory;
PropertyOverrideConfigurer cfg = new PropertyOverrideConfigurer();
NameValueCollection defaultProperties = new NameValueCollection();
defaultProperties.Add("malformedKey", "Rick Evans");
cfg.Properties = defaultProperties;
mocks.ReplayAll();
try
{
cfg.PostProcessObjectFactory(fac);
Assert.Fail("Should have had a FatalObjectException at this point because of a malformed key.");
}
catch (FatalObjectException)
{
}
mocks.VerifyAll();
Assert.Throws<FatalObjectException>(() => cfg.PostProcessObjectFactory(fac));
}
[Test]
@@ -168,20 +154,17 @@ namespace Spring.Objects.Factory.Config
{
const string valueTo_NOT_BeOveridden = "Jenny Lewis";
TestObject foo = new TestObject(valueTo_NOT_BeOveridden, 30);
IConfigurableListableObjectFactory objectFactory = mocks.StrictMock<IConfigurableListableObjectFactory>();
Expect.Call(objectFactory.GetObjectDefinition("rubbish")).Return(null);
IConfigurableListableObjectFactory objectFactory = A.Fake<IConfigurableListableObjectFactory>();
A.CallTo(() => objectFactory.GetObjectDefinition("rubbish")).Returns(null);
IConfigurableListableObjectFactory fac = objectFactory;
PropertyOverrideConfigurer cfg = new PropertyOverrideConfigurer();
NameValueCollection defaultProperties = new NameValueCollection();
defaultProperties.Add("rubbish.Name", "Rick Evans");
cfg.Properties = defaultProperties;
mocks.ReplayAll();
cfg.PostProcessObjectFactory(fac);
Assert.AreEqual(valueTo_NOT_BeOveridden, foo.Name,
"Property value was overridden, but a rubbish objectName root was supplied.");
mocks.VerifyAll();
cfg.PostProcessObjectFactory(fac);
Assert.AreEqual(valueTo_NOT_BeOveridden, foo.Name, "Property value was overridden, but a rubbish objectName root was supplied.");
}
[Test]

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <20> 2002-2011 the original author or authors.
* Copyright <20> 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,14 +18,12 @@
#endregion
#region Imports
using System;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Core;
#endregion
using FakeItEasy;
using NUnit.Framework;
using Spring.Core;
namespace Spring.Objects.Factory.Config
{
@@ -36,22 +34,19 @@ namespace Spring.Objects.Factory.Config
[TestFixture]
public sealed class PropertyPathFactoryObjectTests
{
private MockRepository mocks;
private IObjectFactory mockFactory;
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
mockFactory = mocks.StrictMock<IObjectFactory>();
mockFactory = A.Fake<IObjectFactory>();
}
[Test]
public void GetObject_ViaTargetObjectName()
{
Expect.Call(mockFactory.IsSingleton("foo")).Return(true);
Expect.Call(mockFactory.GetObject("foo")).Return(new TestObject("Fiona Apple", 28));
mocks.ReplayAll();
A.CallTo(() => mockFactory.IsSingleton("foo")).Returns(true);
A.CallTo(() => mockFactory.GetObject("foo")).Returns(new TestObject("Fiona Apple", 28));
PropertyPathFactoryObject fac = new PropertyPathFactoryObject();
fac.TargetObjectName = "foo";
@@ -59,17 +54,15 @@ namespace Spring.Objects.Factory.Config
fac.ObjectFactory = mockFactory;
string name = (string) fac.GetObject();
Assert.AreEqual("Fiona Apple", name);
mocks.VerifyAll();
}
[Test]
public void GetObject_ViaTargetObjectNameWithNestedPropertyPath()
{
Expect.Call(mockFactory.IsSingleton("foo")).Return(true);
A.CallTo(() => mockFactory.IsSingleton("foo")).Returns(true);
TestObject target = new TestObject("Fiona Apple", 28);
target.Spouse = target;
Expect.Call(mockFactory.GetObject("foo")).Return(target);
mocks.ReplayAll();
target.Spouse = target;
A.CallTo(() => mockFactory.GetObject("foo")).Returns(target);
PropertyPathFactoryObject fac = new PropertyPathFactoryObject();
fac.TargetObjectName = "foo";
@@ -77,30 +70,26 @@ namespace Spring.Objects.Factory.Config
fac.ObjectFactory = mockFactory;
string name = (string) fac.GetObject();
Assert.AreEqual("Fiona Apple", name);
mocks.VerifyAll();
}
[Test]
public void GetObject_ViaObjectName()
{
Expect.Call(mockFactory.IsSingleton("foo")).Return(true);
Expect.Call(mockFactory.GetObject("foo")).Return(new TestObject("Fiona Apple", 28));
mocks.ReplayAll();
A.CallTo(() => mockFactory.GetObject("foo")).Returns(new TestObject("Fiona Apple", 28));
A.CallTo(() => mockFactory.IsSingleton("foo")).Returns(true);
PropertyPathFactoryObject fac = new PropertyPathFactoryObject();
fac.ObjectName = "foo.name";
fac.ObjectFactory = mockFactory;
string name = (string) fac.GetObject();
Assert.AreEqual("Fiona Apple", name);
mocks.VerifyAll();
}
[Test]
public void GetObject_ViaObjectNameThatStartsWithAPeriod()
{
Expect.Call(mockFactory.IsSingleton("foo")).Return(true);
Expect.Call(mockFactory.GetObject("foo")).Return(new TestObject("Fiona Apple", 28));
mocks.ReplayAll();
A.CallTo(() => mockFactory.IsSingleton("foo")).Returns(true);
A.CallTo(() => mockFactory.GetObject("foo")).Returns(new TestObject("Fiona Apple", 28));
PropertyPathFactoryObject fac = new PropertyPathFactoryObject();
fac.ObjectName = ".foo.name";
@@ -110,41 +99,36 @@ namespace Spring.Objects.Factory.Config
[Test]
public void GetObject_MakeSureLeadingAndTrailingWhitspaceIsTrimmed()
{
Expect.Call(mockFactory.IsSingleton("foo")).Return(true);
Expect.Call(mockFactory.GetObject("foo")).Return(new TestObject("Fiona Apple", 28));
mocks.ReplayAll();
A.CallTo(() => mockFactory.IsSingleton("foo")).Returns(true);
A.CallTo(() => mockFactory.GetObject("foo")).Returns(new TestObject("Fiona Apple", 28));
PropertyPathFactoryObject fac = new PropertyPathFactoryObject();
fac.ObjectName = " \nfoo.name ";
fac.ObjectFactory = mockFactory;
string name = (string) fac.GetObject();
Assert.AreEqual("Fiona Apple", name);
mocks.VerifyAll();
}
[Test]
public void GetObject_ViaObjectNameWithNestedPropertyPath()
{
Expect.Call(mockFactory.IsSingleton("foo")).Return(true);
A.CallTo(() => mockFactory.IsSingleton("foo")).Returns(true);
TestObject target = new TestObject("Fiona Apple", 28);
target.Spouse = target;
Expect.Call(mockFactory.GetObject("foo")).Return(target);
mocks.ReplayAll();
target.Spouse = target;
A.CallTo(() => mockFactory.GetObject("foo")).Returns(target);
PropertyPathFactoryObject fac = new PropertyPathFactoryObject();
fac.ObjectName = "foo.spouse.name";
fac.ObjectFactory = mockFactory;
string name = (string) fac.GetObject();
Assert.AreEqual("Fiona Apple", name);
mocks.VerifyAll();
}
[Test]
public void GetObject_ViaObjectNameWithNullInNestedPropertyPath()
{
Expect.Call(mockFactory.IsSingleton("foo")).Return(true);
Expect.Call(mockFactory.GetObject("foo")).Return(new TestObject("Fiona Apple", 28));
mocks.ReplayAll();
A.CallTo(() => mockFactory.IsSingleton("foo")).Returns(true);
A.CallTo(() => mockFactory.GetObject("foo")).Returns(new TestObject("Fiona Apple", 28));
PropertyPathFactoryObject fac = new PropertyPathFactoryObject();
fac.ObjectName = "foo.spouse.name";
@@ -154,9 +138,8 @@ namespace Spring.Objects.Factory.Config
[Test]
public void GetObject_PropertyPathEvaluatesToNull()
{
Expect.Call(mockFactory.IsSingleton("foo")).Return(true);
Expect.Call(mockFactory.GetObject("foo")).Return(new TestObject(null, 28));
mocks.ReplayAll();
A.CallTo(() => mockFactory.IsSingleton("foo")).Returns(true);
A.CallTo(() => mockFactory.GetObject("foo")).Returns(new TestObject(null, 28));
PropertyPathFactoryObject fac = new PropertyPathFactoryObject();
fac.ObjectName = "foo.name";

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <20> 2002-2011 the original author or authors.
* Copyright <20> 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,22 +18,21 @@
#endregion
#region Imports
using System;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Collections;
using Spring.Context;
using Spring.Context.Support;
using Spring.Core.IO;
using Spring.Objects.Factory.Support;
using Spring.Objects.Factory.Xml;
#endregion
using Spring.Util;
namespace Spring.Objects.Factory.Config
{
@@ -44,37 +43,34 @@ namespace Spring.Objects.Factory.Config
[TestFixture]
public sealed class PropertyPlaceholderConfigurerTests
{
private MockRepository mocks;
private static string testConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\Northwind.mdb;User ID=Admin;Password=;";
private static string testConnectionStringTwo = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\Northwind.mdb;User ID=Admin;Password=Ernie;";
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
}
[Test]
public void MismatchBetweenNumberOfConfigNamesAndNumberOfLocations()
{
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
cfg.Locations = new IResource[] { mocks.StrictMock<IResource>() }; // will never get to the point where we check the validity
cfg.Locations = new IResource[] { A.Fake<IResource>() }; // will never get to the point where we check the validity
cfg.ConfigSections = new string[] { "", "" };
Assert.Throws<ObjectInitializationException>(() => cfg.PostProcessObjectFactory((IConfigurableListableObjectFactory) mocks.DynamicMock(typeof(IConfigurableListableObjectFactory))));
Assert.Throws<ObjectInitializationException>(() => cfg.PostProcessObjectFactory(A.Fake<IConfigurableListableObjectFactory>()));
}
[Test]
public void OneConfigNameIsOKForLotsOfLocations()
{
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
IResource mock = mocks.StrictMock<IResource>();
Expect.Call(mock.Exists).Return(true);
Expect.Call(mock.InputStream).Throw(new FileNotFoundException());
mocks.ReplayAll();
IResource mock = A.Fake<IResource>();
A.CallTo(() => mock.Exists).Returns(true);
A.CallTo(() => mock.InputStream).Throws(new FileNotFoundException());
cfg.Locations = new IResource [] {mock};
cfg.ConfigSections = new string[] { "" };
Assert.Throws<ObjectsException>(() => cfg.PostProcessObjectFactory((IConfigurableListableObjectFactory) mocks.DynamicMock(typeof(IConfigurableListableObjectFactory))));
Assert.Throws<ObjectsException>(() => cfg.PostProcessObjectFactory(A.Fake<IConfigurableListableObjectFactory>()));
}
[Test]
@@ -82,13 +78,12 @@ namespace Spring.Objects.Factory.Config
{
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
cfg.IgnoreResourceNotFound = false;
IResource mock = mocks.StrictMock<IResource>();
Expect.Call(mock.Exists).Return(false);
mocks.ReplayAll();
IResource mock = A.Fake<IResource>();
A.CallTo(() => mock.Exists).Returns(false);
cfg.Locations = new IResource [] { mock};
cfg.ConfigSections = new string[] { "" };
Assert.Throws<ObjectInitializationException>(() => cfg.PostProcessObjectFactory((IConfigurableListableObjectFactory) mocks.DynamicMock(typeof(IConfigurableListableObjectFactory))));
Assert.Throws<ObjectInitializationException>(() => cfg.PostProcessObjectFactory(A.Fake<IConfigurableListableObjectFactory>()));
}
[Test]
@@ -96,17 +91,14 @@ namespace Spring.Objects.Factory.Config
{
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
cfg.IgnoreResourceNotFound = true;
IResource mockResource = mocks.StrictMock<IResource>();
Expect.Call(mockResource.Exists).Return(false);
IResource mockResource = A.Fake<IResource>();
A.CallTo(() => mockResource.Exists).Returns(false);
cfg.Location = mockResource;
cfg.ConfigSections = new string[] { "" };
IConfigurableListableObjectFactory mockFactory = (IConfigurableListableObjectFactory)mocks.DynamicMock(typeof(IConfigurableListableObjectFactory));
Expect.Call(mockFactory.GetObjectDefinitionNames(false)).Return(new string[] {});
mocks.ReplayAll();
IConfigurableListableObjectFactory mockFactory = A.Fake<IConfigurableListableObjectFactory>();
A.CallTo(() => mockFactory.GetObjectDefinitionNames(false)).Returns(new string[] {});
cfg.PostProcessObjectFactory(mockFactory);
mocks.VerifyAll();
}
[Test]
@@ -143,12 +135,10 @@ namespace Spring.Objects.Factory.Config
pvs.Add(theProperty, placeholder);
RootObjectDefinition def = new RootObjectDefinition(typeof(TestObject), pvs);
IConfigurableListableObjectFactory mock = mocks.StrictMock<IConfigurableListableObjectFactory>();
Expect.Call(mock.GetObjectDefinitionNames(false)).Return(new string [] {defName});
Expect.Call(mock.GetObjectDefinition(defName, false)).Return(def);
Expect.Call(() => mock.AddEmbeddedValueResolver(null)).IgnoreArguments();
mocks.ReplayAll();
IConfigurableListableObjectFactory mock = A.Fake<IConfigurableListableObjectFactory>();
A.CallTo(() => mock.GetObjectDefinitionNames(false)).Returns(new string [] {defName});
A.CallTo(() => mock.GetObjectDefinition(defName, false)).Returns(def);
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
NameValueCollection defaultProperties = new NameValueCollection();
const string expectedName = "Rick Evans";
@@ -158,7 +148,7 @@ namespace Spring.Objects.Factory.Config
Assert.AreEqual(expectedName, def.PropertyValues.GetPropertyValue(theProperty).Value,
"Property placeholder value was not replaced with the resolved value.");
mocks.VerifyAll();
A.CallTo(() => mock.AddEmbeddedValueResolver(A<IStringValueResolver>._)).MustHaveHappened();
}
[Test]
@@ -173,11 +163,9 @@ namespace Spring.Objects.Factory.Config
pvs.Add(theProperty, placeholder);
RootObjectDefinition def = new RootObjectDefinition(typeof(TestObject), pvs);
IConfigurableListableObjectFactory mock = mocks.StrictMock<IConfigurableListableObjectFactory>();
Expect.Call(mock.GetObjectDefinitionNames(true)).Return(new string[] { defName });
Expect.Call(mock.GetObjectDefinition(defName, true)).Return(def);
Expect.Call(() => mock.AddEmbeddedValueResolver(null)).IgnoreArguments();
mocks.ReplayAll();
IConfigurableListableObjectFactory mock = A.Fake<IConfigurableListableObjectFactory>();
A.CallTo(() => mock.GetObjectDefinitionNames(true)).Returns(new string[] { defName });
A.CallTo(() => mock.GetObjectDefinition(defName, true)).Returns(def);
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
cfg.IncludeAncestors = true;
@@ -190,14 +178,14 @@ namespace Spring.Objects.Factory.Config
Assert.AreEqual(expectedName, def.PropertyValues.GetPropertyValue(theProperty).Value,
"Property placeholder value was not replaced with the resolved value.");
mocks.VerifyAll();
A.CallTo(() => mock.AddEmbeddedValueResolver(A<IStringValueResolver>._)).MustHaveHappened();
}
/// <summary>
/// Fallback is the default mode. Check if the PROCESSOR_ARCHITECTURE
/// variable is replaced.
/// </summary>
[Test]
/// <summary>
/// Fallback is the default mode. Check if the PROCESSOR_ARCHITECTURE
/// variable is replaced.
/// </summary>
[Test]
public void WithEnvironmentVariableFallback()
{
StaticApplicationContext ac = new StaticApplicationContext();
@@ -415,10 +403,9 @@ namespace Spring.Objects.Factory.Config
const string expectedName = "ba${foo}r";
properties.Add("foo", expectedName);
IConfigurableListableObjectFactory mock = mocks.StrictMock<IConfigurableListableObjectFactory>();
Expect.Call(mock.GetObjectDefinitionNames(false)).Return(new string[] {"foo"});
Expect.Call(mock.GetObjectDefinition(null, false)).IgnoreArguments().Return(def);
mocks.ReplayAll();
IConfigurableListableObjectFactory mock = A.Fake<IConfigurableListableObjectFactory>();
A.CallTo(() => mock.GetObjectDefinitionNames(false)).Returns(new string[] {"foo"});
A.CallTo(() => mock.GetObjectDefinition(null, false)).WithAnyArguments().Returns(def);
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
cfg.Properties = properties;
@@ -430,7 +417,6 @@ namespace Spring.Objects.Factory.Config
catch (ObjectDefinitionStoreException)
{
}
mocks.VerifyAll();
}
[Test]
@@ -446,19 +432,17 @@ namespace Spring.Objects.Factory.Config
const string expectedName = "Rick";
properties.Add("hope.floats", expectedName);
IConfigurableListableObjectFactory mock = mocks.StrictMock<IConfigurableListableObjectFactory>();
Expect.Call(mock.GetObjectDefinitionNames(false)).Return(new string[] {"foo"});
Expect.Call(mock.GetObjectDefinition(null, false)).IgnoreArguments().Return(def);
Expect.Call(delegate { mock.AddEmbeddedValueResolver(null); }).IgnoreArguments();
mocks.ReplayAll();
IConfigurableListableObjectFactory mock = A.Fake<IConfigurableListableObjectFactory>();
A.CallTo(() => mock.GetObjectDefinitionNames(false)).Returns(new string[] {"foo"});
A.CallTo(() => mock.GetObjectDefinition(null, false)).WithAnyArguments().Returns(def);
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
cfg.Properties = properties;
cfg.PostProcessObjectFactory(mock);
mocks.VerifyAll();
A.CallTo(() => mock.AddEmbeddedValueResolver(A<IStringValueResolver>._)).MustHaveHappened();
Assert.AreEqual(expectedName,
Assert.AreEqual(expectedName,
def.ConstructorArgumentValues.GetNamedArgumentValue("name").Value,
"Named argument placeholder value was not replaced.");
}
@@ -476,20 +460,18 @@ namespace Spring.Objects.Factory.Config
const string expectedName = "Rick";
properties.Add("hope.floats", expectedName);
IConfigurableListableObjectFactory mock = mocks.StrictMock<IConfigurableListableObjectFactory>();
Expect.Call(mock.GetObjectDefinitionNames(false)).Return(new string[] {"foo"});
Expect.Call(mock.GetObjectDefinition(null, false)).IgnoreArguments().Return(def);
Expect.Call(() => mock.AddEmbeddedValueResolver(null)).IgnoreArguments();
mocks.ReplayAll();
IConfigurableListableObjectFactory mock = A.Fake<IConfigurableListableObjectFactory>();
A.CallTo(() => mock.GetObjectDefinitionNames(false)).Returns(new string[] {"foo"});
A.CallTo(() => mock.GetObjectDefinition(null, false)).WithAnyArguments().Returns(def);
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
cfg.PlaceholderPrefix = cfg.PlaceholderSuffix = "#";
cfg.Properties = properties;
cfg.PostProcessObjectFactory(mock);
mocks.VerifyAll();
A.CallTo(() => mock.AddEmbeddedValueResolver(null)).WithAnyArguments().MustHaveHappened();
Assert.AreEqual(expectedName,
Assert.AreEqual(expectedName,
def.ConstructorArgumentValues.GetNamedArgumentValue("name").Value,
"Named argument placeholder value was not replaced.");
}
@@ -574,21 +556,19 @@ namespace Spring.Objects.Factory.Config
pvs.Add("name", placeholder);
RootObjectDefinition def = new RootObjectDefinition(typeof(TestObject), pvs);
IConfigurableListableObjectFactory mock = mocks.StrictMock<IConfigurableListableObjectFactory>();
Expect.Call(mock.GetObjectDefinitionNames(false)).Return(new string [] {defName});
Expect.Call(mock.GetObjectDefinition(defName, false)).Return(def);
Expect.Call(() => mock.AddEmbeddedValueResolver(null)).IgnoreArguments();
mocks.ReplayAll();
IConfigurableListableObjectFactory mock = A.Fake<IConfigurableListableObjectFactory>();
A.CallTo(() => mock.GetObjectDefinitionNames(false)).Returns(new string [] {defName});
A.CallTo(() => mock.GetObjectDefinition(defName, false)).Returns(def);
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
cfg.IgnoreUnresolvablePlaceholders = true;
cfg.PostProcessObjectFactory(mock);
Assert.AreEqual(placeholder, foo.Name);
mocks.VerifyAll();
A.CallTo(() => mock.AddEmbeddedValueResolver(null)).WithAnyArguments().MustHaveHappened();
}
[Test]
[Test]
public void ViaXML()
{
IResource resource = new ReadOnlyXmlTestResource("PropertyResourceConfigurerTests.xml", GetType());

View File

@@ -19,16 +19,16 @@
#endregion
using System.Collections;
using NUnit.Framework;
using Rhino.Mocks;
using FakeItEasy;
using NUnit.Framework;
using Spring.Core.IO;
using Spring.Util;
namespace Spring.Objects.Factory.Config
{
/// <summary>
/// Unit tests for the TypeAliasConfigurer class
/// </summary>
@@ -36,12 +36,9 @@ namespace Spring.Objects.Factory.Config
[TestFixture]
public class ResourceHandlerConfigurerTests
{
private MockRepository mocks;
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
}
[Test]
@@ -68,7 +65,7 @@ namespace Spring.Objects.Factory.Config
ResourceHandlerConfigurer resourceHandlerConfiguer = new ResourceHandlerConfigurer();
resourceHandlerConfiguer.ResourceHandlers = resourceHandlers;
Assert.Throws<ObjectInitializationException>(() => resourceHandlerConfiguer.PostProcessObjectFactory((IConfigurableListableObjectFactory) mocks.DynamicMock(typeof(IConfigurableListableObjectFactory))));
Assert.Throws<ObjectInitializationException>(() => resourceHandlerConfiguer.PostProcessObjectFactory(A.Fake<IConfigurableListableObjectFactory>()));
}
[Test]
@@ -81,7 +78,7 @@ namespace Spring.Objects.Factory.Config
resourceHandlerConfiguer.ResourceHandlers = resourceHandlers;
Assert.Throws<ObjectInitializationException>(() => resourceHandlerConfiguer.PostProcessObjectFactory((IConfigurableListableObjectFactory) mocks.DynamicMock(typeof(IConfigurableListableObjectFactory))));
Assert.Throws<ObjectInitializationException>(() => resourceHandlerConfiguer.PostProcessObjectFactory(A.Fake<IConfigurableListableObjectFactory>()));
}
[Test]
@@ -112,7 +109,7 @@ namespace Spring.Objects.Factory.Config
resourceHandlerConfiguer.Order = 1;
resourceHandlerConfiguer.PostProcessObjectFactory((IConfigurableListableObjectFactory) mocks.DynamicMock(typeof(IConfigurableListableObjectFactory)));
resourceHandlerConfiguer.PostProcessObjectFactory(A.Fake<IConfigurableListableObjectFactory>());
//todo investigate mocking the typeregistry, for now ask the actual one for information.
Assert.IsTrue(ResourceHandlerRegistry.IsHandlerRegistered("httpsss"),

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <20> 2002-2011 the original author or authors.
* Copyright <20> 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,8 +22,10 @@
using System;
using System.Collections;
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Objects.Factory.Support;
using Spring.Objects.Support;
@@ -113,25 +115,19 @@ namespace Spring.Objects.Factory.Config
{
DefaultListableObjectFactory of = new DefaultListableObjectFactory();
MockRepository mocks = new MockRepository();
ISharedStateFactory ssf1 = mocks.StrictMock<ISharedStateFactory>();
ISharedStateAware ssa = (ISharedStateAware)mocks.DynamicMock( typeof( ISharedStateAware ) );
ISharedStateFactory ssf1 = A.Fake<ISharedStateFactory>();
ISharedStateAware ssa = A.Fake<ISharedStateAware>();
SharedStateAwareProcessor ssap = new SharedStateAwareProcessor();
ssap.SharedStateFactories = new ISharedStateFactory[] { ssf1 };
of.RegisterSingleton( "ssap", ssap );
ssap.SharedStateFactories = new ISharedStateFactory[] {ssf1};
of.RegisterSingleton("ssap", ssap);
using (Record( mocks ))
{
// preset SharedState - ssap must ignore it
Expect.Call( ssa.SharedState ).Return( new Hashtable() );
// expect nothing else!
}
// preset SharedState - ssap must ignore it
A.CallTo(() => ssa.SharedState).Returns(new Hashtable());
using (Playback( mocks ))
{
ssap.PostProcessBeforeInitialization( ssa, "myPage" );
}
ssap.PostProcessBeforeInitialization(ssa, "myPage");
A.CallTo(ssa).Where(x => x.Method.Name == "set_SharedState").MustNotHaveHappened();
}
[Test]
@@ -139,53 +135,33 @@ namespace Spring.Objects.Factory.Config
{
DefaultListableObjectFactory of = new DefaultListableObjectFactory();
MockRepository mocks = new MockRepository();
ISharedStateFactory ssf1 = mocks.StrictMock<ISharedStateFactory>();
ISharedStateFactory ssf2 = mocks.StrictMock<ISharedStateFactory>();
ISharedStateFactory ssf3 = mocks.StrictMock<ISharedStateFactory>();
ISharedStateFactory ssf4 = mocks.StrictMock<ISharedStateFactory>();
ISharedStateFactory ssf1 = A.Fake<ISharedStateFactory>();
ISharedStateFactory ssf2 = A.Fake<ISharedStateFactory>();
ISharedStateFactory ssf3 = A.Fake<ISharedStateFactory>();
ISharedStateFactory ssf4 = A.Fake<ISharedStateFactory>();
IDictionary ssf3ProvidedState = new Hashtable();
SharedStateAwareProcessor ssap = new SharedStateAwareProcessor();
ssap.SharedStateFactories = new ISharedStateFactory[] { ssf1, ssf2, ssf3, ssf4 };
of.RegisterSingleton( "ssap", ssap );
ssap.SharedStateFactories = new ISharedStateFactory[] {ssf1, ssf2, ssf3, ssf4};
of.RegisterSingleton("ssap", ssap);
ISharedStateAware ssa = (ISharedStateAware)mocks.DynamicMock( typeof( ISharedStateAware ) );
ISharedStateAware ssa = A.Fake<ISharedStateAware>();
// Ensure we iterate over configured SharedStateFactories until
// the first provider is found that
// a) true == provider.CanProvideState( instance, name )
// b) null != provider.GetSharedState( instance, name )
using (Record( mocks ))
{
Expect.Call( ssa.SharedState ).Return( null );
Expect.Call( ssf1.CanProvideState( ssa, "pageName" ) ).Return( false );
Expect.Call( ssf2.CanProvideState( ssa, "pageName" ) ).Return( true );
Expect.Call( ssf2.GetSharedStateFor( ssa, "pageName" ) ).Return( null );
Expect.Call( ssf3.CanProvideState( ssa, "pageName" ) ).Return( true );
Expect.Call( ssf3.GetSharedStateFor( ssa, "pageName" ) ).Return( ssf3ProvidedState );
Expect.Call( ssa.SharedState = ssf3ProvidedState );
}
A.CallTo(() => ssa.SharedState).Returns(null).Once();
A.CallTo(() => ssf1.CanProvideState(ssa, "pageName")).Returns(false).Once();
A.CallTo(() => ssf2.CanProvideState(ssa, "pageName")).Returns(true).Once();
A.CallTo(() => ssf2.GetSharedStateFor(ssa, "pageName")).Returns(null);
A.CallTo(() => ssf3.CanProvideState(ssa, "pageName")).Returns(true).Once();
A.CallTo(() => ssf3.GetSharedStateFor(ssa, "pageName")).Returns(ssf3ProvidedState).Once();
using (Playback( mocks ))
{
ssap.PostProcessBeforeInitialization( ssa, "pageName" );
}
ssap.PostProcessBeforeInitialization(ssa, "pageName");
Assert.That(Equals(ssa.SharedState, ssf3ProvidedState));
}
#region Rhino.Mocks Compatibility Adapter
private static IDisposable Record( MockRepository mocks )
{
return mocks.Record();
}
private static IDisposable Playback( MockRepository mocks )
{
return mocks.Playback();
}
#endregion Rhino.Mocks Compatibility Adapter
}
}

View File

@@ -20,8 +20,10 @@
using System;
using System.Collections;
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Collections;
using Spring.Context.Support;
using Spring.Core.TypeResolution;
@@ -37,14 +39,12 @@ namespace Spring.Objects.Factory.Config
[TestFixture]
public class TypeAliasConfigurerTests
{
private MockRepository mocks;
private IConfigurableListableObjectFactory factory;
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
factory = mocks.StrictMock<IConfigurableListableObjectFactory>();
factory = A.Fake<IConfigurableListableObjectFactory>();
}
[Test]

View File

@@ -21,9 +21,9 @@
using System;
using System.Collections;
using NUnit.Framework;
using FakeItEasy;
using Rhino.Mocks;
using NUnit.Framework;
using Spring.Context.Support;
using Spring.Objects.Factory.Support;
@@ -31,18 +31,15 @@ using Spring.Objects.Factory.Support;
namespace Spring.Objects.Factory.Config
{
/// <summary>
/// This class contains tests for
/// This class contains tests for
/// </summary>
/// <author>Mark Pollack</author>
[TestFixture]
public class VariablePlaceholderConfigurerTests
{
private MockRepository mocks;
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
}
[Test]
@@ -68,7 +65,7 @@ namespace Spring.Objects.Factory.Config
StaticApplicationContext ac = new StaticApplicationContext();
VariablePlaceholderConfigurer vphc = new VariablePlaceholderConfigurer();
vphc.VariableSources = new ArrayList(new object[] { new object() });
try
{
vphc.PostProcessObjectFactory(ac.ObjectFactory);
@@ -300,10 +297,9 @@ namespace Spring.Objects.Factory.Config
pvs.Add(theProperty, placeholder);
RootObjectDefinition def = new RootObjectDefinition(typeof(TestObject), pvs);
IConfigurableListableObjectFactory mock = mocks.StrictMock<IConfigurableListableObjectFactory>();
Expect.Call(mock.GetObjectDefinitionNames(true)).Return(new string[] { defName });
Expect.Call(mock.GetObjectDefinition(defName, true)).Return(def);
mocks.ReplayAll();
IConfigurableListableObjectFactory mock = A.Fake<IConfigurableListableObjectFactory>();
A.CallTo(() => mock.GetObjectDefinitionNames(true)).Returns(new string[] { defName });
A.CallTo(() => mock.GetObjectDefinition(defName, true)).Returns(def);
VariablePlaceholderConfigurer vpc = new VariablePlaceholderConfigurer();
vpc.IgnoreUnresolvablePlaceholders = true;
@@ -311,8 +307,6 @@ namespace Spring.Objects.Factory.Config
vpc.IncludeAncestors = true;
vpc.PostProcessObjectFactory(mock);
mocks.VerifyAll();
}
}
}

View File

@@ -18,8 +18,6 @@
#endregion
#region Imports
using System;
using System.Collections;
using System.Collections.Generic;
@@ -27,15 +25,12 @@ using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Core.TypeConversion;
using Spring.Objects.Factory.Config;
using Spring.Objects.Factory.Support;
using Spring.Objects.Factory.Xml;
using Spring.Objects.Support;
#endregion
namespace Spring.Objects.Factory
{
/// <summary>
@@ -46,13 +41,11 @@ namespace Spring.Objects.Factory
[TestFixture]
public sealed class DefaultListableObjectFactoryTests
{
private MockRepository mocks;
[SetUp]
public void Setup()
{
mocks = new MockRepository();
}
/// <summary>
/// The setup logic executed before the execution of this test fixture.
/// </summary>
@@ -79,7 +72,7 @@ namespace Spring.Objects.Factory
TheStrategy = strategy;
}
}
class Class2
{
private IStrategy _strategy;
@@ -293,8 +286,8 @@ namespace Spring.Objects.Factory
[Test]
public void GetObjectPostProcessorCount()
{
IObjectPostProcessor proc1 = mocks.StrictMock<IObjectPostProcessor>();
IObjectPostProcessor proc2 = mocks.StrictMock<IObjectPostProcessor>();
IObjectPostProcessor proc1 = FakeItEasy.A.Fake<IObjectPostProcessor>();
IObjectPostProcessor proc2 = FakeItEasy.A.Fake<IObjectPostProcessor>();
DefaultListableObjectFactory lof = new DefaultListableObjectFactory();
@@ -315,9 +308,8 @@ namespace Spring.Objects.Factory
[Test]
public void GetObjectPostProcessorCountDoesntRespectHierarchy()
{
IObjectPostProcessor proc1 = mocks.StrictMock<IObjectPostProcessor>();
IObjectPostProcessor proc2 = mocks.StrictMock<IObjectPostProcessor>();
IObjectPostProcessor proc1 = FakeItEasy.A.Fake<IObjectPostProcessor>();
IObjectPostProcessor proc2 = FakeItEasy.A.Fake<IObjectPostProcessor>();
DefaultListableObjectFactory child = new DefaultListableObjectFactory();
DefaultListableObjectFactory parent = new DefaultListableObjectFactory(child);
@@ -1535,7 +1527,7 @@ namespace Spring.Objects.Factory
DefaultListableObjectFactory fac = new DefaultListableObjectFactory();
fac.RegisterObjectDefinition("foo", def);
Assert.Throws<UnsatisfiedDependencyException>(() => fac.GetObject("foo"),
Assert.Throws<UnsatisfiedDependencyException>(() => fac.GetObject("foo"),
"Error creating object with name 'foo' : Unsatisfied dependency " +
"expressed through constructor argument with index 1 of type [System.Boolean] : " +
"No unique object of type [System.Boolean] is defined : Unsatisfied dependency of type [System.Boolean]: expected at least 1 matching object to wire the [b2] parameter on the constructor of object [foo]");
@@ -1650,7 +1642,7 @@ namespace Spring.Objects.Factory
[Test]
public void IgnoreObjectPostProcessorDuplicates()
{
IObjectPostProcessor proc1 = mocks.StrictMock<IObjectPostProcessor>();
IObjectPostProcessor proc1 = FakeItEasy.A.Fake<IObjectPostProcessor>();
DefaultListableObjectFactory lof = new DefaultListableObjectFactory();
@@ -1706,7 +1698,7 @@ namespace Spring.Objects.Factory
object testObject = "TestObject";
object resultObject = of.ConfigureObject(testObject, "myObjectDefinition");
Assert.AreSame(wrapperObject, resultObject);
Assert.AreSame(wrapperObject, resultObject);
}
[Test]
@@ -1715,10 +1707,10 @@ namespace Spring.Objects.Factory
DefaultListableObjectFactory of = new DefaultListableObjectFactory();
object wrapperObject = "WrapperObject";
of.AddObjectPostProcessor( new TestObjectPostProcessor(wrapperObject));
object testObject = "TestObject";
object resultObject = of.ConfigureObject(testObject, "non-existant definition");
Assert.AreSame(testObject, resultObject);
Assert.AreSame(testObject, resultObject);
}
[Test]

View File

@@ -18,15 +18,12 @@
#endregion
#region Imports
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Core.IO;
using Spring.Util;
#endregion
namespace Spring.Objects.Factory
{
/// <summary>
@@ -36,24 +33,20 @@ namespace Spring.Objects.Factory
[TestFixture]
public sealed class ObjectDefinitionStoreExceptionTests
{
private MockRepository mocks;
[SetUp]
public void Setup()
{
mocks = new MockRepository();
}
[Test]
[Test]
public void FromResource()
{
string expectedName = "bing";
string expectedResourceDescription = "mock.resource";
IResource resource = mocks.StrictMock<IResource>();
Expect.Call(resource.Description).Return(expectedResourceDescription);
mocks.ReplayAll();
ObjectDefinitionStoreException inex
= new ObjectDefinitionStoreException(resource, expectedName, "mmm...");
mocks.VerifyAll();
string expectedResourceDescription = "mock.resource";
IResource resource = A.Fake<IResource>();
A.CallTo(() => resource.Description).Returns(expectedResourceDescription);
ObjectDefinitionStoreException inex = new ObjectDefinitionStoreException(resource, expectedName, "mmm...");
CheckSerialization(inex, expectedName, expectedResourceDescription);
}

View File

@@ -18,14 +18,12 @@
#endregion
#region Imports
using System;
using System.Reflection;
using NUnit.Framework;
using Rhino.Mocks;
#endregion
using FakeItEasy;
using NUnit.Framework;
namespace Spring.Objects.Factory.Support
{
@@ -36,52 +34,46 @@ namespace Spring.Objects.Factory.Support
[TestFixture]
public sealed class DelegatingMethodReplacerTests
{
private MockRepository mocks;
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
}
[Test]
public void InstantiationWithNullDefinition()
{
IObjectFactory factory = mocks.StrictMock<IObjectFactory>();
IObjectFactory factory = A.Fake<IObjectFactory>();
Assert.Throws<ArgumentNullException>(() => new DelegatingMethodReplacer(null, factory));
}
[Test]
public void InstantiationWithNullFactory()
{
IConfigurableObjectDefinition mock = mocks.StrictMock<IConfigurableObjectDefinition>();
IConfigurableObjectDefinition mock = A.Fake<IConfigurableObjectDefinition>();
Assert.Throws<ArgumentNullException>(() => new DelegatingMethodReplacer(mock, null));
}
[Test]
public void SunnyDayPath()
{
IObjectFactory mockFactory = mocks.StrictMock<IObjectFactory>();
IConfigurableObjectDefinition mockDefinition = mocks.StrictMock<IConfigurableObjectDefinition>();
IMethodReplacer mockReplacer = mocks.StrictMock<IMethodReplacer>();
IObjectFactory mockFactory = A.Fake<IObjectFactory>();
IConfigurableObjectDefinition mockDefinition = A.Fake<IConfigurableObjectDefinition>();
IMethodReplacer mockReplacer = A.Fake<IMethodReplacer>();
const string ReplacerObjectName = "replacer";
Expect.Call(mockFactory.GetObject(ReplacerObjectName)).Return(mockReplacer);
A.CallTo(() => mockFactory.GetObject(ReplacerObjectName)).Returns(mockReplacer);
ReplacedMethodOverride ovr = new ReplacedMethodOverride("SunnyDayPath", ReplacerObjectName);
MethodOverrides overrides = new MethodOverrides();
overrides.Add(ovr);
Expect.Call(mockDefinition.MethodOverrides).Return(overrides);
A.CallTo(() => mockDefinition.MethodOverrides).Returns(overrides);
A.CallTo(() => mockReplacer.Implement(null, null, null)).WithAnyArguments().Returns(null);
Expect.Call(mockReplacer.Implement(null, null, null)).IgnoreArguments().Return(null);
mocks.ReplayAll();
DelegatingMethodReplacer replacer = new DelegatingMethodReplacer(mockDefinition, mockFactory);
MethodInfo method = (MethodInfo) MethodBase.GetCurrentMethod();
replacer.Implement(this, method, new object[] {});
mocks.VerifyAll();
}
}
}

View File

@@ -18,14 +18,12 @@
#endregion
#region Imports
using System;
using System.Reflection;
using NUnit.Framework;
using Rhino.Mocks;
#endregion
using FakeItEasy;
using NUnit.Framework;
namespace Spring.Objects.Factory.Support
{
@@ -36,52 +34,46 @@ namespace Spring.Objects.Factory.Support
[TestFixture]
public sealed class LookupMethodReplacerTests
{
private MockRepository mocks;
[SetUp]
public void Setup()
{
mocks = new MockRepository();
}
[Test]
public void InstantiationWithNullDefinition()
{
IObjectFactory objectFactory = mocks.StrictMock<IObjectFactory>();
IObjectFactory objectFactory = A.Fake<IObjectFactory>();
Assert.Throws<ArgumentNullException>(() => new LookupMethodReplacer(null, objectFactory));
}
[Test]
public void InstantiationWithNullFactory()
{
var configurableObjectDefinition = mocks.StrictMock<IConfigurableObjectDefinition>();
var configurableObjectDefinition = A.Fake<IConfigurableObjectDefinition>();
Assert.Throws<ArgumentNullException>(() => new LookupMethodReplacer(configurableObjectDefinition, null));
}
[Test]
public void SunnyDayPath()
{
var objectFactory = mocks.StrictMock<IObjectFactory>();
var configurableObjectDefinition = mocks.StrictMock<IConfigurableObjectDefinition>();
var objectFactory = A.Fake<IObjectFactory>();
var configurableObjectDefinition = A.Fake<IConfigurableObjectDefinition>();
object expectedLookup = new object();
const string LookupObjectName = "foo";
Expect.Call(objectFactory.GetObject(LookupObjectName)).Return(expectedLookup);
A.CallTo(() => objectFactory.GetObject(LookupObjectName)).Returns(expectedLookup);
LookupMethodOverride ovr = new LookupMethodOverride("SunnyDayPath", LookupObjectName);
MethodOverrides overrides = new MethodOverrides();
overrides.Add(ovr);
Expect.Call(configurableObjectDefinition.MethodOverrides).Return(overrides);
A.CallTo(() => configurableObjectDefinition.MethodOverrides).Returns(overrides);
LookupMethodReplacer replacer = new LookupMethodReplacer(configurableObjectDefinition, objectFactory);
mocks.ReplayAll();
MethodInfo method = (MethodInfo) MethodBase.GetCurrentMethod();
object lookup = replacer.Implement(this, method, new object[] {});
Assert.AreSame(expectedLookup, lookup);
mocks.VerifyAll();
}
}
}

View File

@@ -18,14 +18,12 @@
#endregion
#region Imports
using System;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Objects.Factory.Config;
#endregion
using FakeItEasy;
using NUnit.Framework;
using Spring.Objects.Factory.Config;
namespace Spring.Objects.Factory.Support
{
@@ -36,44 +34,36 @@ namespace Spring.Objects.Factory.Support
[TestFixture]
public sealed class ObjectDefinitionReaderUtilsTests
{
private MockRepository mocks;
private IObjectDefinitionRegistry registry;
private IObjectDefinition definition;
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
registry = mocks.StrictMock<IObjectDefinitionRegistry>();
definition = mocks.StrictMock<IObjectDefinition>();
registry = A.Fake<IObjectDefinitionRegistry>();
definition = A.Fake<IObjectDefinition>();
}
[Test]
public void RegisterObjectDefinitionSunnyDay()
{
registry.RegisterObjectDefinition(null, null);
LastCall.IgnoreArguments();
mocks.ReplayAll();
ObjectDefinitionHolder holder = new ObjectDefinitionHolder(definition, "foo");
ObjectDefinitionReaderUtils.RegisterObjectDefinition(holder, registry);
mocks.VerifyAll();
A.CallTo(() => registry.RegisterObjectDefinition(null, null)).WithAnyArguments().MustHaveHappened();
}
[Test]
public void RegisterObjectDefinitionSunnyDayWithAliases()
{
registry.RegisterObjectDefinition("foo", definition);
registry.RegisterAlias("foo", "bar");
registry.RegisterAlias("foo", "baz");
mocks.ReplayAll();
ObjectDefinitionHolder holder = new ObjectDefinitionHolder(definition, "foo", new string[] {"bar", "baz"});
ObjectDefinitionReaderUtils.RegisterObjectDefinition(holder, registry);
mocks.VerifyAll();
A.CallTo(() => registry.RegisterObjectDefinition("foo", definition)).MustHaveHappened();
A.CallTo(() => registry.RegisterAlias("foo", "bar")).MustHaveHappened();
A.CallTo(() => registry.RegisterAlias("foo", "baz")).MustHaveHappened();
}
[Test]
@@ -101,24 +91,12 @@ namespace Spring.Objects.Factory.Support
registry.RegisterObjectDefinition("foo", definition);
// we assume that some other object defition has already been associated with this alias...
registry.RegisterAlias(null, null);
LastCall.IgnoreArguments().Throw(new ObjectDefinitionStoreException());
mocks.ReplayAll();
A.CallTo(() => registry.RegisterAlias(null, null)).WithAnyArguments().Throws<ObjectDefinitionStoreException>();
ObjectDefinitionHolder holder
= new ObjectDefinitionHolder(definition, "foo", new string[] { "bing" });
= new ObjectDefinitionHolder(definition, "foo", new string[] {"bing"});
try
{
ObjectDefinitionReaderUtils.RegisterObjectDefinition(holder, registry);
Assert.Fail("Must have thrown an ObjectDefinitionStoreException store by this point.");
}
catch (ObjectDefinitionStoreException)
{
// expected...
}
mocks.VerifyAll();
Assert.Throws<ObjectDefinitionStoreException>(() => ObjectDefinitionReaderUtils.RegisterObjectDefinition(holder, registry));
}
[Test]
@@ -130,7 +108,7 @@ namespace Spring.Objects.Factory.Support
[Test]
public void GenerateObjectNameWithNullRegistry()
{
Assert.Throws<ArgumentNullException>(() => ObjectDefinitionReaderUtils.GenerateObjectName(mocks.StrictMock<IConfigurableObjectDefinition>(), null));
Assert.Throws<ArgumentNullException>(() => ObjectDefinitionReaderUtils.GenerateObjectName(A.Fake<IConfigurableObjectDefinition>(), null));
}
}
}

View File

@@ -18,8 +18,6 @@
#endregion
#region Imports
using System;
using System.Collections;
using System.Collections.Generic;
@@ -31,9 +29,10 @@ using System.Threading;
using System.Web.Services;
using Common.Logging;
using Common.Logging.Simple;
using NUnit.Framework;
using Rhino.Mocks;
using FakeItEasy;
using NUnit.Framework;
using Spring.Core.IO;
using Spring.Core.TypeResolution;
@@ -42,10 +41,8 @@ using Spring.Objects.Factory.Config;
using Spring.Objects.Factory.Support;
using Spring.Util;
#endregion
namespace Spring.Objects.Factory.Xml
{
{
/// <summary>
/// Unit tests for the XmlObjectFactory class.
/// </summary>
@@ -59,8 +56,6 @@ namespace Spring.Objects.Factory.Xml
[TestFixture]
public sealed class XmlObjectFactoryTests
{
private MockRepository mocks;
/// <summary>
/// The setup logic executed before the execution of this test fixture.
/// </summary>
@@ -75,7 +70,6 @@ namespace Spring.Objects.Factory.Xml
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
}
[Test]
@@ -573,25 +567,25 @@ namespace Spring.Objects.Factory.Xml
xof.GetObject("innerObject");
TestObject hasInnerObjects = (TestObject) xof.GetObject("hasInnerObjects");
Assert.AreEqual(5, hasInnerObjects.Age);
Assert.AreEqual(5, hasInnerObjects.Age);
TestObject inner1 = (TestObject) hasInnerObjects.Spouse;
Assert.IsNotNull(inner1);
Assert.AreEqual("Spring.Objects.TestObject#", inner1.ObjectName.Substring(0, inner1.ObjectName.IndexOf("#")+1));
Assert.IsNotNull(inner1);
Assert.AreEqual("Spring.Objects.TestObject#", inner1.ObjectName.Substring(0, inner1.ObjectName.IndexOf("#")+1));
Assert.AreEqual("inner1", inner1.Name);
Assert.AreEqual(6, inner1.Age);
Assert.IsNotNull(hasInnerObjects.Friends);
IList friends = (IList) hasInnerObjects.Friends;
Assert.AreEqual(2, friends.Count);
DerivedTestObject inner2 = (DerivedTestObject) friends[0];
Assert.AreEqual("inner2", inner2.Name);
Assert.AreEqual(7, inner2.Age);
Assert.AreEqual("Spring.Objects.DerivedTestObject#", inner2.ObjectName.Substring(0, inner2.ObjectName.IndexOf("#") + 1));
Assert.AreEqual("Spring.Objects.DerivedTestObject#", inner2.ObjectName.Substring(0, inner2.ObjectName.IndexOf("#") + 1));
TestObject innerFactory = (TestObject) friends[1];
Assert.AreEqual(DummyFactory.SINGLETON_NAME, innerFactory.Name);
Assert.IsNotNull(hasInnerObjects.SomeMap);
Assert.IsFalse((hasInnerObjects.SomeMap.Count == 0));
TestObject inner3 = (TestObject) hasInnerObjects.SomeMap["someKey"];
@@ -636,11 +630,11 @@ namespace Spring.Objects.Factory.Xml
Assert.AreEqual("inner3", inner3.Name);
Assert.AreEqual(8, inner3.Age);
xof.Dispose();
Assert.IsFalse(inner2.WasDestroyed());
Assert.IsFalse(innerFactory.Name == null);
Assert.IsFalse(innerFriendOfAFriend.WasDestroyed());
}
[Test]
@@ -661,7 +655,7 @@ namespace Spring.Objects.Factory.Xml
public void SingletonInheritanceFromParentFactorySingletonUsingCtor()
{
XmlObjectFactory parent = new XmlObjectFactory(new ReadOnlyXmlTestResource("parent.xml", GetType()));
XmlObjectFactory child = new XmlObjectFactory(new ReadOnlyXmlTestResource("child.xml", GetType()), parent);
XmlObjectFactory child = new XmlObjectFactory(new ReadOnlyXmlTestResource("child.xml", GetType()), parent);
TestObject inherits = (TestObject)child.GetObject("inheritsFromParentFactoryUsingCtor");
// Name property value is overriden
Assert.IsTrue(inherits.Name.Equals("child-name"));
@@ -967,17 +961,17 @@ namespace Spring.Objects.Factory.Xml
{
IResource resource = new ReadOnlyXmlTestResource("lazy-init-multithreaded.xml", GetType());
XmlObjectFactory xof = new XmlObjectFactory(resource);
LazyWorker lw1 = new LazyWorker(xof);
LazyWorker lw2 = new LazyWorker(xof);
Thread thread1 = new Thread(new ThreadStart(lw1.DoWork));
Thread thread2 = new Thread(new ThreadStart(lw2.DoWork));
thread1.Start();
Thread.Sleep(1000);
thread2.Start();
thread1.Join();
thread2.Join();
thread2.Join();
Assert.AreEqual(typeof(LazyTestObject), lw1.ObjectFromContext.GetType());
Assert.AreEqual(typeof(LazyTestObject), lw2.ObjectFromContext.GetType());
Assert.AreEqual(1, LazyTestObject.Count);
@@ -1027,7 +1021,7 @@ namespace Spring.Objects.Factory.Xml
Assert.IsTrue(ex.InnerException is FormatException);
}
}
[Test]
public void NoSuchXmlFile()
{
@@ -1057,7 +1051,7 @@ namespace Spring.Objects.Factory.Xml
XmlObjectDefinitionReader reader = new XmlObjectDefinitionReader(xof, null);
try
{
reader.LoadObjectDefinitions(new ReadOnlyXmlTestResource("invalid.xml", GetType()));
reader.LoadObjectDefinitions(new ReadOnlyXmlTestResource("invalid.xml", GetType()));
Assert.Fail("Should have thrown XmlObjectDefinitionStoreException");
}
catch (ObjectDefinitionStoreException e)
@@ -1528,15 +1522,11 @@ namespace Spring.Objects.Factory.Xml
//FactoryMethods fm = (FactoryMethods) factory.GetObject("instanceFactoryMethodOverloads", new object[] {row});
// Assert.AreEqual("DataRowCtor", fm.Name);
IDataRecord dataRecord = (IDataRecord) mocks.DynamicMock(typeof(IDataRecord));
IDataRecord dataRecord = A.Fake<IDataRecord>();
FactoryMethods fm = (FactoryMethods)factory.GetObject("instanceFactoryMethodOverloads", new object[] { dataRecord });
Assert.AreEqual("DataRecordCtor", fm.Name);
}
#region Private Helper Methods for InstanceFactoryMethodWithOverloadedargs
private DataTable MakeNamesTable()
{
// Create a new DataTable titled 'Names.'
@@ -1569,7 +1559,6 @@ namespace Spring.Objects.Factory.Xml
return namesTable;
}
#endregion
[Test]
public void FactoryMethodNoMatchingStaticMethod()
{
@@ -1689,7 +1678,7 @@ namespace Spring.Objects.Factory.Xml
/// <summary>
/// Test creating an object using its 1 arg boolean constructor (amongst
/// others) by specifying the constructor arguments type and
/// others) by specifying the constructor arguments type and
/// not its index number.
/// </summary>
[Test]
@@ -1840,7 +1829,7 @@ namespace Spring.Objects.Factory.Xml
public void TestExpressionAttribute()
{
TypeRegistry.RegisterType("WebMethod", typeof(WebMethodAttribute));
IResource resource = new ReadOnlyXmlTestResource("expressions.xml", GetType());
XmlObjectFactory xof = new XmlObjectFactory(resource);
@@ -1886,7 +1875,7 @@ namespace Spring.Objects.Factory.Xml
private Object objectFromContext;
public LazyWorker(XmlObjectFactory xof)
{
this.xof = xof;
this.xof = xof;
}
public void DoWork()
{
@@ -2069,5 +2058,5 @@ namespace Spring.Objects.Factory.Xml
#endregion
}
}

View File

@@ -2,13 +2,13 @@
/*
* Copyright <20> 2002-2011 the original author or authors.
*
*
* 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.
@@ -18,19 +18,17 @@
#endregion
#region Imports
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Threading;
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Pool.Support;
using Spring.Threading;
#endregion
namespace Spring.Pool
{
#region Inner Class : Helper
@@ -111,23 +109,18 @@ namespace Spring.Pool
}
}
#endregion
#endregion
private MockRepository mocks;
private IPoolableObjectFactory factory;
private IPoolableObjectFactory factory;
private SimplePool pool;
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
factory = (IPoolableObjectFactory) mocks.DynamicMock(typeof(IPoolableObjectFactory));
Expect.Call(factory.MakeObject()).Return(new object()).Repeat.Any();
factory = A.Fake<IPoolableObjectFactory>();
A.CallTo(() => factory.MakeObject()).Returns(new object());
mocks.ReplayAll();
pool = new SimplePool(factory, 1);
mocks.BackToRecordAll();
}
@@ -152,85 +145,70 @@ namespace Spring.Pool
[Test]
public void ActivateOnObjectOnBorrow()
{
Expect.Call(factory.ValidateObject(null)).IgnoreArguments().Return(true).Repeat.Any();
factory.ActivateObject(null);
LastCall.IgnoreArguments();
mocks.ReplayAll();
A.CallTo(() => factory.ValidateObject(null)).WithAnyArguments().Returns(true);
Assert.AreEqual(0, pool.NumActive, "active wrong");
Assert.AreEqual(1, pool.NumIdle, "idle wrong");
pool.BorrowObject();
Assert.AreEqual(1, pool.NumActive, "active wrong");
Assert.AreEqual(0, pool.NumIdle, "idle wrong");
mocks.VerifyAll();
}
// TODO fix test!!!
[Test]
[Ignore("Cannot figure out why this is failing?")]
public void PassivateBusyObjectsBeforeClose()
{
Expect.Call(factory.ValidateObject(null)).IgnoreArguments().Return(true).Repeat.Any();
object o = pool.BorrowObject();
factory.PassivateObject(o);
mocks.ReplayAll();
pool.Close();
mocks.VerifyAll();
A.CallTo(() => factory.ActivateObject(null)).WithAnyArguments().MustHaveHappened();
}
[Test]
[Test]
public void PassivateBusyObjectsBeforeClose()
{
A.CallTo(() => factory.ValidateObject(A<object>._)).WithAnyArguments().Returns(true);
object o = pool.BorrowObject();
pool.Close();
A.CallTo(() => factory.PassivateObject(o)).MustHaveHappened();
}
[Test]
[Ignore("No longer expected behavior per SPRNET-1582 being resolved.")]
public void NoMoreUsableAfterClose()
{
object o = pool.BorrowObject();
factory.PassivateObject(o);
mocks.ReplayAll();
pool.Close();
Assert.Throws<PoolException>(() => pool.BorrowObject());
mocks.VerifyAll();
A.CallTo(() => factory.PassivateObject(null)).WithAnyArguments().MustHaveHappened();
}
[Test]
[Test]
[Ignore("No longer expected behavior per SPRNET-1582 being resolved.")]
public void ThrowsExceptionWhenOutOfItemsBecauseFailedValidation()
{
object o = new object();
Expect.Call(factory.MakeObject()).Return(o);
Expect.Call(factory.ValidateObject(o)).Return(false);
mocks.ReplayAll();
A.CallTo(() => factory.MakeObject()).Returns(o);
A.CallTo(() => factory.ValidateObject(o)).Returns(false);
pool = new SimplePool(factory, 1);
Assert.Throws<PoolException>(() => pool.BorrowObject());
mocks.VerifyAll();
}
[Test]
public void PassivateObjectOnReturn()
{
Expect.Call(factory.ValidateObject(null)).IgnoreArguments().Return(true).Repeat.Any();
factory.PassivateObject(null);
LastCall.IgnoreArguments();
mocks.ReplayAll();
A.CallTo(() => factory.ValidateObject(null)).WithAnyArguments().Returns(true);
pool.ReturnObject(pool.BorrowObject());
mocks.VerifyAll();
A.CallTo(() => factory.PassivateObject(null)).WithAnyArguments().MustHaveHappened();
}
[Test]
[Test]
public void DestroyObjectOnClose()
{
Expect.Call(factory.ValidateObject(null)).IgnoreArguments().Return(true).Repeat.Any();
factory.DestroyObject(null);
LastCall.IgnoreArguments();
mocks.ReplayAll();
A.CallTo(() => factory.ValidateObject(null)).WithAnyArguments().Returns(true);
pool.BorrowObject();
pool.Close();
}
[Test]
A.CallTo(() => factory.DestroyObject(null)).WithAnyArguments().MustHaveHappened();
}
[Test]
public void WaitOnBorrowWhenExausted()
{
int n = 100;

View File

@@ -11,10 +11,11 @@
<ProjectReference Include="..\..\..\src\Spring\Spring.Template.Velocity\Spring.Template.Velocity.2010.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="FakeItEasy" Version="$(FakeItEasyVersion)" />
<PackageReference Include="FakeItEasy.Analyzer" Version="$(FakeItEasyVersion)" PrivateAssets="All" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="$(MicrosoftTestSDKVersion)" />
<PackageReference Include="NUnit" Version="$(NUnitVersion)" />
<PackageReference Include="NUnit3TestAdapter" Version="$(NUnitTestAdapterVersion)" />
<PackageReference Include="RhinoMocks" Version="$(RhinoMocksVersion)" />
</ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />

View File

@@ -1,40 +1,37 @@
using System.Threading;
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
namespace Spring.Threading
{
[TestFixture]
public class SyncHolderTest
{
private MockRepository mocks;
public class SyncHolderTest
{
ISync sync;
[SetUp]
public void SetUp ()
public void SetUp()
{
mocks = new MockRepository();
sync = mocks.StrictMock<ISync>();
sync = A.Fake<ISync>();
}
[TearDown]
public void TearDown ()
public void TearDown()
{
mocks.VerifyAll();
}
class MySemaphore : Semaphore
{
public MySemaphore (long initialPermits) : base (initialPermits)
{}
public MySemaphore(long initialPermits) : base(initialPermits)
{
}
}
[Test]
public void CanBeUsedWithTheUsingCSharpIdiomToAttemptOnAnISync ()
public void CanBeUsedWithTheUsingCSharpIdiomToAttemptOnAnISync()
{
// no expectations
mocks.ReplayAll();
MySemaphore sync = new MySemaphore(1);
using (new SyncHolder(sync, 100))
{
@@ -57,20 +54,18 @@ namespace Spring.Threading
}
[Test]
public void CanBeUsedWithTheUsingCSharpIdiomToAcquireAnIsync()
{
public void CanBeUsedWithTheUsingCSharpIdiomToAcquireAnIsync()
{
sync.Acquire();
sync.Release();
mocks.ReplayAll();
Assert.Throws<ThreadStateException>(() =>
{
using (new SyncHolder(sync))
{
throw new ThreadStateException();
}
});
}
}
}
Assert.Throws<ThreadStateException>(() =>
{
using (new SyncHolder(sync))
{
throw new ThreadStateException();
}
});
}
}
}

View File

@@ -21,55 +21,56 @@
#region Imports
using System;
using NUnit.Framework;
#endregion
namespace Spring.Util
{
/// <summary>
/// Unit tests for the NumberUtils class.
/// </summary>
/// <author>Rick Evans</author>
[TestFixture]
public sealed class NumberUtilsTests
{
[Test]
public void IsInteger()
{
Assert.IsTrue(NumberUtils.IsInteger(10));
Assert.IsTrue(NumberUtils.IsInteger(10L));
Assert.IsTrue(NumberUtils.IsInteger((short) 10));
Assert.IsFalse(NumberUtils.IsInteger('e'));
Assert.IsFalse(NumberUtils.IsInteger(null));
Assert.IsFalse(NumberUtils.IsInteger(9.5D));
Assert.IsFalse(NumberUtils.IsInteger(9.5F));
Assert.IsFalse(NumberUtils.IsInteger(this));
Assert.IsFalse(NumberUtils.IsInteger(null));
Assert.IsFalse(NumberUtils.IsInteger(string.Empty));
}
[Test]
public void IsDecimal()
{
Assert.IsFalse(NumberUtils.IsDecimal(10));
Assert.IsFalse(NumberUtils.IsDecimal(10L));
Assert.IsFalse(NumberUtils.IsDecimal((short) 10));
Assert.IsFalse(NumberUtils.IsDecimal('e'));
Assert.IsFalse(NumberUtils.IsDecimal(null));
Assert.IsTrue(NumberUtils.IsDecimal(9.5D));
Assert.IsTrue(NumberUtils.IsDecimal(9.5F));
Assert.IsFalse(NumberUtils.IsDecimal(this));
Assert.IsFalse(NumberUtils.IsDecimal(null));
Assert.IsFalse(NumberUtils.IsDecimal(string.Empty));
}
/// <summary>
/// Unit tests for the NumberUtils class.
/// </summary>
/// <author>Rick Evans</author>
[TestFixture]
public sealed class NumberUtilsTests
{
[Test]
public void IsInteger()
{
Assert.IsTrue(NumberUtils.IsInteger(10));
Assert.IsTrue(NumberUtils.IsInteger(10L));
Assert.IsTrue(NumberUtils.IsInteger((short) 10));
Assert.IsFalse(NumberUtils.IsInteger('e'));
Assert.IsFalse(NumberUtils.IsInteger(null));
Assert.IsFalse(NumberUtils.IsInteger(9.5D));
Assert.IsFalse(NumberUtils.IsInteger(9.5F));
Assert.IsFalse(NumberUtils.IsInteger(this));
Assert.IsFalse(NumberUtils.IsInteger(null));
Assert.IsFalse(NumberUtils.IsInteger(string.Empty));
}
[Test]
public void IsNumber()
{
[Test]
public void IsDecimal()
{
Assert.IsFalse(NumberUtils.IsDecimal(10));
Assert.IsFalse(NumberUtils.IsDecimal(10L));
Assert.IsFalse(NumberUtils.IsDecimal((short) 10));
Assert.IsFalse(NumberUtils.IsDecimal('e'));
Assert.IsFalse(NumberUtils.IsDecimal(null));
Assert.IsTrue(NumberUtils.IsDecimal(9.5D));
Assert.IsTrue(NumberUtils.IsDecimal(9.5F));
Assert.IsFalse(NumberUtils.IsDecimal(this));
Assert.IsFalse(NumberUtils.IsDecimal(null));
Assert.IsFalse(NumberUtils.IsDecimal(string.Empty));
}
[Test]
public void IsNumber()
{
Assert.IsTrue(NumberUtils.IsNumber(10));
Assert.IsTrue(NumberUtils.IsNumber(10L));
Assert.IsTrue(NumberUtils.IsNumber((short)10));
Assert.IsTrue(NumberUtils.IsNumber((short) 10));
Assert.IsFalse(NumberUtils.IsNumber('e'));
Assert.IsFalse(NumberUtils.IsNumber(null));
Assert.IsTrue(NumberUtils.IsNumber(9.5D));
@@ -77,169 +78,174 @@ namespace Spring.Util
Assert.IsFalse(NumberUtils.IsNumber(this));
Assert.IsFalse(NumberUtils.IsNumber(null));
Assert.IsFalse(NumberUtils.IsNumber(string.Empty));
}
}
[Test]
public void IsZero()
{
Assert.IsFalse(NumberUtils.IsZero((Int16)2));
Assert.IsTrue(NumberUtils.IsZero((Int16)0));
Assert.IsFalse(NumberUtils.IsZero((short) 2));
Assert.IsTrue(NumberUtils.IsZero((short) 0));
Assert.IsFalse(NumberUtils.IsZero((Int32)2));
Assert.IsTrue(NumberUtils.IsZero((Int32)0));
Assert.IsFalse(NumberUtils.IsZero(2));
Assert.IsTrue(NumberUtils.IsZero(0));
Assert.IsFalse(NumberUtils.IsZero((Int64)2));
Assert.IsTrue(NumberUtils.IsZero((Int64)0));
Assert.IsFalse(NumberUtils.IsZero((long) 2));
Assert.IsTrue(NumberUtils.IsZero((long) 0));
Assert.IsFalse(NumberUtils.IsZero((UInt16)2));
Assert.IsTrue(NumberUtils.IsZero((UInt16)0));
Assert.IsFalse(NumberUtils.IsZero((ushort) 2));
Assert.IsTrue(NumberUtils.IsZero((ushort) 0));
Assert.IsFalse(NumberUtils.IsZero((UInt32)2));
Assert.IsTrue(NumberUtils.IsZero((UInt32)0));
Assert.IsFalse(NumberUtils.IsZero((uint) 2));
Assert.IsTrue(NumberUtils.IsZero((uint) 0));
Assert.IsFalse(NumberUtils.IsZero((UInt64)2));
Assert.IsTrue(NumberUtils.IsZero((UInt64)0));
Assert.IsFalse(NumberUtils.IsZero((ulong) 2));
Assert.IsTrue(NumberUtils.IsZero((ulong) 0));
Assert.IsFalse(NumberUtils.IsZero((decimal)2));
Assert.IsTrue(NumberUtils.IsZero((decimal)0));
Assert.IsFalse(NumberUtils.IsZero((decimal) 2));
Assert.IsTrue(NumberUtils.IsZero((decimal) 0));
Assert.IsTrue(NumberUtils.IsZero((Byte?)0));
Assert.IsFalse(NumberUtils.IsZero((Byte)2));
Assert.IsTrue(NumberUtils.IsZero((byte?) 0));
Assert.IsFalse(NumberUtils.IsZero((byte) 2));
Assert.IsTrue(NumberUtils.IsZero((SByte?)0));
Assert.IsFalse(NumberUtils.IsZero((SByte)2));
Assert.IsTrue(NumberUtils.IsZero((sbyte?) 0));
Assert.IsFalse(NumberUtils.IsZero((sbyte) 2));
}
[Test]
public void NegateNull()
{
[Test]
public void NegateNull()
{
Assert.Throws<ArgumentException>(() => NumberUtils.Negate(null));
}
}
[Test]
public void NegateString()
{
[Test]
public void NegateString()
{
Assert.Throws<ArgumentException>(() => NumberUtils.Negate(string.Empty));
}
}
[Test]
public void Negate()
{
Assert.AreEqual(-10, NumberUtils.Negate(10));
}
[Test]
public void Negate()
{
Assert.AreEqual(-10, NumberUtils.Negate(10));
}
[Test]
public void CoercesTypes()
{
object x = (int)1;
object y = (double)2;
object x = (int) 1;
object y = (double) 2;
NumberUtils.CoerceTypes(ref x, ref y);
Assert.AreEqual(typeof(double), x.GetType());
}
[Test]
public void Add()
{
Assert.AreEqual(5, NumberUtils.Add(2, 3));
[Test]
public void Add()
{
Assert.AreEqual(5, NumberUtils.Add(2, 3));
try
{
NumberUtils.Add(2, "3");
Assert.Fail();
}
catch(ArgumentException)
{}
}
catch (ArgumentException)
{
}
}
[Test]
public void BitwiseNot()
{
Assert.AreEqual( ~((Byte)2), NumberUtils.BitwiseNot((Byte)2) );
Assert.AreEqual(~((SByte)2), NumberUtils.BitwiseNot((SByte)2));
Assert.AreEqual(~((Int16)2), NumberUtils.BitwiseNot((Int16)2));
Assert.AreEqual(~((UInt16)2), NumberUtils.BitwiseNot((UInt16)2));
Assert.AreEqual(~((Int32)2), NumberUtils.BitwiseNot((Int32)2));
Assert.AreEqual(~((UInt32)2), NumberUtils.BitwiseNot((UInt32)2));
Assert.AreEqual(~((Int64)2), NumberUtils.BitwiseNot((Int64)2));
Assert.AreEqual(~((UInt64)2), NumberUtils.BitwiseNot((UInt64)2));
Assert.AreEqual( false, NumberUtils.BitwiseNot(true) );
Assert.AreEqual(~(byte) 2, NumberUtils.BitwiseNot((byte) 2));
Assert.AreEqual(~(sbyte) 2, NumberUtils.BitwiseNot((sbyte) 2));
Assert.AreEqual(~(short) 2, NumberUtils.BitwiseNot((short) 2));
Assert.AreEqual(~(ushort) 2, NumberUtils.BitwiseNot((ushort) 2));
Assert.AreEqual(~(int) 2, NumberUtils.BitwiseNot((int) 2));
Assert.AreEqual(~(uint) 2, NumberUtils.BitwiseNot((uint) 2));
Assert.AreEqual(~(long) 2, NumberUtils.BitwiseNot((long) 2));
Assert.AreEqual(~(ulong) 2, NumberUtils.BitwiseNot((ulong) 2));
Assert.AreEqual(false, NumberUtils.BitwiseNot(true));
try
{
NumberUtils.BitwiseNot((double)2.0);
NumberUtils.BitwiseNot((double) 2.0);
Assert.Fail();
}
catch(ArgumentException)
{}
catch (ArgumentException)
{
}
}
[Test]
public void BitwiseAnd()
{
Assert.AreEqual( ((Byte)2)&((Byte)3), NumberUtils.BitwiseAnd((Byte)2, (Byte)3));
Assert.AreEqual(((SByte)2) & ((SByte)3), NumberUtils.BitwiseAnd((SByte)2, (SByte)3));
Assert.AreEqual(((Int16)2) & ((Int16)3), NumberUtils.BitwiseAnd((Int16)2, (Int16)3));
Assert.AreEqual(((UInt16)2) & ((UInt16)3), NumberUtils.BitwiseAnd((UInt16)2, (UInt16)3));
Assert.AreEqual(((Int32)2) & ((Int32)3), NumberUtils.BitwiseAnd((Int32)2, (Int32)3));
Assert.AreEqual(((UInt32)2) & ((UInt32)3), NumberUtils.BitwiseAnd((UInt32)2, (UInt32)3));
Assert.AreEqual(((Int64)2) & ((Int64)3), NumberUtils.BitwiseAnd((Int64)2, (Int64)3));
Assert.AreEqual(((UInt64)2) & ((UInt64)3), NumberUtils.BitwiseAnd((UInt64)2, (UInt64)3));
Assert.AreEqual(((UInt64)2) & ((Byte)3), NumberUtils.BitwiseAnd((UInt64)2, (Byte)3));
Assert.AreEqual((byte) 2 & (byte) 3, NumberUtils.BitwiseAnd((byte) 2, (byte) 3));
Assert.AreEqual((sbyte) 2 & (sbyte) 3, NumberUtils.BitwiseAnd((sbyte) 2, (sbyte) 3));
Assert.AreEqual((short) 2 & (short) 3, NumberUtils.BitwiseAnd((short) 2, (short) 3));
Assert.AreEqual((ushort) 2 & (ushort) 3, NumberUtils.BitwiseAnd((ushort) 2, (ushort) 3));
Assert.AreEqual((int) 2 & (int) 3, NumberUtils.BitwiseAnd((int) 2, (int) 3));
Assert.AreEqual((uint) 2 & (uint) 3, NumberUtils.BitwiseAnd((uint) 2, (uint) 3));
Assert.AreEqual((long) 2 & (long) 3, NumberUtils.BitwiseAnd((long) 2, (long) 3));
Assert.AreEqual((ulong) 2 & (ulong) 3, NumberUtils.BitwiseAnd((ulong) 2, (ulong) 3));
Assert.AreEqual((ulong) 2 & (byte) 3, NumberUtils.BitwiseAnd((ulong) 2, (byte) 3));
Assert.AreEqual(true, NumberUtils.BitwiseAnd(true, true));
Assert.AreEqual( false, NumberUtils.BitwiseAnd(false, true) );
Assert.AreEqual(false, NumberUtils.BitwiseAnd(false, true));
try
{
NumberUtils.BitwiseAnd((double)2.0, 3);
NumberUtils.BitwiseAnd((double) 2.0, 3);
Assert.Fail();
}
catch(ArgumentException)
{}
catch (ArgumentException)
{
}
}
[Test]
public void BitwiseOr()
{
Assert.AreEqual( ((Byte)2) | ((Byte)3), NumberUtils.BitwiseOr((Byte)2, (Byte)3));
Assert.AreEqual(((SByte)2) | ((SByte)3), NumberUtils.BitwiseOr((SByte)2, (SByte)3));
Assert.AreEqual(((Int16)2) | ((Int16)3), NumberUtils.BitwiseOr((Int16)2, (Int16)3));
Assert.AreEqual(((UInt16)2) | ((UInt16)3), NumberUtils.BitwiseOr((UInt16)2, (UInt16)3));
Assert.AreEqual(((Int32)2) | ((Int32)3), NumberUtils.BitwiseOr((Int32)2, (Int32)3));
Assert.AreEqual(((UInt32)2) | ((UInt32)3), NumberUtils.BitwiseOr((UInt32)2, (UInt32)3));
Assert.AreEqual(((Int64)2) | ((Int64)3), NumberUtils.BitwiseOr((Int64)2, (Int64)3));
Assert.AreEqual(((UInt64)2) | ((UInt64)3), NumberUtils.BitwiseOr((UInt64)2, (UInt64)3));
Assert.AreEqual(((UInt64)2) | ((Byte)3), NumberUtils.BitwiseOr((UInt64)2, (Byte)3));
Assert.AreEqual((byte) 2 | (byte) 3, NumberUtils.BitwiseOr((byte) 2, (byte) 3));
Assert.AreEqual((sbyte) 2 | (sbyte) 3, NumberUtils.BitwiseOr((sbyte) 2, (sbyte) 3));
Assert.AreEqual((short) 2 | (short) 3, NumberUtils.BitwiseOr((short) 2, (short) 3));
Assert.AreEqual((ushort) 2 | (ushort) 3, NumberUtils.BitwiseOr((ushort) 2, (ushort) 3));
Assert.AreEqual((int) 2 | (int) 3, NumberUtils.BitwiseOr((int) 2, (int) 3));
Assert.AreEqual((uint) 2 | (uint) 3, NumberUtils.BitwiseOr((uint) 2, (uint) 3));
Assert.AreEqual((long) 2 | (long) 3, NumberUtils.BitwiseOr((long) 2, (long) 3));
Assert.AreEqual((ulong) 2 | (ulong) 3, NumberUtils.BitwiseOr((ulong) 2, (ulong) 3));
Assert.AreEqual((ulong) 2 | (byte) 3, NumberUtils.BitwiseOr((ulong) 2, (byte) 3));
Assert.AreEqual(false, NumberUtils.BitwiseOr(false, false));
Assert.AreEqual(true, NumberUtils.BitwiseOr(false, true));
try
{
NumberUtils.BitwiseAnd((double)2.0, 3);
NumberUtils.BitwiseAnd((double) 2.0, 3);
Assert.Fail();
}
catch(ArgumentException)
{}
catch (ArgumentException)
{
}
}
[Test]
public void BitwiseXor()
{
Assert.AreEqual( ((Byte)2) ^ ((Byte)3), NumberUtils.BitwiseXor((Byte)2, (Byte)3));
Assert.AreEqual(((SByte)2) ^ ((SByte)3), NumberUtils.BitwiseXor((SByte)2, (SByte)3));
Assert.AreEqual(((Int16)2) ^ ((Int16)3), NumberUtils.BitwiseXor((Int16)2, (Int16)3));
Assert.AreEqual(((UInt16)2) ^ ((UInt16)3), NumberUtils.BitwiseXor((UInt16)2, (UInt16)3));
Assert.AreEqual(((Int32)2) ^ ((Int32)3), NumberUtils.BitwiseXor((Int32)2, (Int32)3));
Assert.AreEqual(((UInt32)2) ^ ((UInt32)3), NumberUtils.BitwiseXor((UInt32)2, (UInt32)3));
Assert.AreEqual(((Int64)2) ^ ((Int64)3), NumberUtils.BitwiseXor((Int64)2, (Int64)3));
Assert.AreEqual(((UInt64)2) ^ ((UInt64)3), NumberUtils.BitwiseXor((UInt64)2, (UInt64)3));
Assert.AreEqual(((UInt64)2) ^ ((Byte)3), NumberUtils.BitwiseXor((UInt64)2, (Byte)3));
Assert.AreEqual((byte) 2 ^ (byte) 3, NumberUtils.BitwiseXor((byte) 2, (byte) 3));
Assert.AreEqual((sbyte) 2 ^ (sbyte) 3, NumberUtils.BitwiseXor((sbyte) 2, (sbyte) 3));
Assert.AreEqual((short) 2 ^ (short) 3, NumberUtils.BitwiseXor((short) 2, (short) 3));
Assert.AreEqual((ushort) 2 ^ (ushort) 3, NumberUtils.BitwiseXor((ushort) 2, (ushort) 3));
Assert.AreEqual((int) 2 ^ (int) 3, NumberUtils.BitwiseXor((int) 2, (int) 3));
Assert.AreEqual((uint) 2 ^ (uint) 3, NumberUtils.BitwiseXor((uint) 2, (uint) 3));
Assert.AreEqual((long) 2 ^ (long) 3, NumberUtils.BitwiseXor((long) 2, (long) 3));
Assert.AreEqual((ulong) 2 ^ (ulong) 3, NumberUtils.BitwiseXor((ulong) 2, (ulong) 3));
Assert.AreEqual((ulong) 2 ^ (byte) 3, NumberUtils.BitwiseXor((ulong) 2, (byte) 3));
Assert.AreEqual(false, NumberUtils.BitwiseXor(false, false));
Assert.AreEqual(false, NumberUtils.BitwiseXor(true, true));
Assert.AreEqual(true, NumberUtils.BitwiseXor(false, true));
Assert.AreEqual(true, NumberUtils.BitwiseXor(true, false));
try
{
NumberUtils.BitwiseAnd((double)2.0, 3);
NumberUtils.BitwiseAnd((double) 2.0, 3);
Assert.Fail();
}
catch(ArgumentException)
{}
catch (ArgumentException)
{
}
}
}
}
}

View File

@@ -922,7 +922,7 @@ namespace Spring.Util
Assert.IsNotNull(candidateMethods[1]);
Assert.IsNotNull(candidateMethods[2]);
Assert.AreEqual("ParamArrayMatch", foo.MethodWithSimilarArguments(1, new object()));
Assert.AreEqual("ExactMatch", foo.MethodWithSimilarArguments(1, (GetMethodByArgumentValuesTarget.DummyArgumentType[])typedArg));
Assert.AreEqual("ExactMatch", foo.MethodWithSimilarArguments(1, typedArg));
Assert.AreEqual("AssignableMatch", foo.MethodWithSimilarArguments(1, (ICollection)typedArg));
MethodInfo resolvedMethod = ReflectionUtils.GetMethodByArgumentValues(candidateMethods, new object[] { 1, typedArg });
@@ -950,7 +950,7 @@ namespace Spring.Util
Assert.IsNotNull(candidateMethods[2]);
Assert.IsNotNull(candidateMethods[3]);
Assert.AreEqual("ParamArrayMatch", foo.MethodWithSimilarArguments(1, new object()));
Assert.AreEqual("ExactMatch", foo.MethodWithSimilarArguments(1, (GetMethodByArgumentValuesTarget.DummyArgumentType[])typedArg));
Assert.AreEqual("ExactMatch", foo.MethodWithSimilarArguments(1, typedArg));
Assert.AreEqual("AssignableMatch", foo.MethodWithSimilarArguments(1, (ICollection)typedArg));
Assert.AreEqual("NullableArgumentMatch", foo.MethodWithNullableArgument(null));
@@ -975,7 +975,7 @@ namespace Spring.Util
Assert.IsNotNull(candidateConstructors[1]);
Assert.IsNotNull(candidateConstructors[2]);
Assert.AreEqual("ParamArrayMatch", new GetMethodByArgumentValuesTarget(1, new object()).SelectedConstructor);
Assert.AreEqual("ExactMatch", new GetMethodByArgumentValuesTarget(1, (GetMethodByArgumentValuesTarget.DummyArgumentType[])typedArg).SelectedConstructor);
Assert.AreEqual("ExactMatch", new GetMethodByArgumentValuesTarget(1, typedArg).SelectedConstructor);
Assert.AreEqual("AssignableMatch", new GetMethodByArgumentValuesTarget(1, (ICollection)typedArg).SelectedConstructor);
ConstructorInfo resolvedConstructor = ReflectionUtils.GetConstructorByArgumentValues(candidateConstructors, new object[] { 1, typedArg });

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
* Copyright © 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -41,7 +41,7 @@ namespace Spring.Util
public void MustNotCallObjectSignatureWithType()
{
Type myType = typeof(TestObject);
Assert.Throws<ArgumentException>(() => UniqueKey.GetInstanceScopedString( (object)myType, "PartialKey"));
Assert.Throws<ArgumentException>(() => UniqueKey.GetInstanceScopedString( myType, "PartialKey"));
}
[Test]
@@ -60,7 +60,7 @@ namespace Spring.Util
string expectedKeyString = string.Format("{0}.{1}", typeof(TestObject).FullName, "PartialKey");
// I know testing implementation details is not the best strategy,
// I know testing implementation details is not the best strategy,
// but I want to receive an error if this fails (oakinger)
Assert.AreEqual(expectedKeyString, expectedKey.ToString());
Assert.AreEqual(expectedKeyString.GetHashCode(), expectedKey.GetHashCode());
@@ -78,7 +78,7 @@ namespace Spring.Util
TestObject testObject = new TestObject();
string typeScopedKey = UniqueKey.GetInstanceScopedString(testObject, "PartialKey");
string expectedKey = string.Format("{0}[{1}].{2}", typeof(TestObject).FullName, testObject.GetHashCode(), "PartialKey");
Assert.AreEqual(expectedKey, typeScopedKey);
Assert.AreEqual(expectedKey, typeScopedKey);
}
[Test]
@@ -90,7 +90,7 @@ namespace Spring.Util
string expectedKeyString = string.Format("{0}[{1}].{2}", typeof(TestObject).FullName, testObject.GetHashCode(), "PartialKey");
// I know testing implementation details is not the best strategy,
// I know testing implementation details is not the best strategy,
// but I want to receive an error if this fails (oakinger)
Assert.AreEqual(expectedKeyString, expectedKey.ToString());
Assert.AreEqual(expectedKeyString.GetHashCode(), expectedKey.GetHashCode());

View File

@@ -10,10 +10,11 @@
<ProjectReference Include="..\Spring.Core.Tests\Spring.Core.Tests.2010.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="FakeItEasy" Version="$(FakeItEasyVersion)" />
<PackageReference Include="FakeItEasy.Analyzer" Version="$(FakeItEasyVersion)" PrivateAssets="All" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="$(MicrosoftTestSDKVersion)" />
<PackageReference Include="NUnit" Version="$(NUnitVersion)" />
<PackageReference Include="NUnit3TestAdapter" Version="$(NUnitTestAdapterVersion)" />
<PackageReference Include="RhinoMocks" Version="$(RhinoMocksVersion)" />
</ItemGroup>
<ItemGroup>
<Reference Include="System.configuration" />

View File

@@ -72,6 +72,6 @@ namespace Spring.Data.NHibernate
}
}

View File

@@ -1,7 +1,5 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
* Copyright © 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,17 +14,17 @@
* limitations under the License.
*/
#endregion
#region Imports
using System;
using System.Collections;
using System.Data;
using FakeItEasy;
using NHibernate;
using NHibernate.Cfg;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Dao;
using Spring.Data.Common;
using Spring.Data.Support;
@@ -34,8 +32,6 @@ using Spring.Support;
using Spring.Transaction;
using Spring.Transaction.Support;
#endregion
namespace Spring.Data.NHibernate
{
/// <summary>
@@ -68,41 +64,24 @@ namespace Spring.Data.NHibernate
}
}
private MockRepository mocks;
[SetUp]
public void Setup()
{
mocks = new MockRepository();
}
[Test]
public void TransactionCommit()
{
IDbProvider provider = mocks.StrictMock<IDbProvider>();
IDbConnection connection = mocks.StrictMock<IDbConnection>();
ISessionFactory sessionFactory = mocks.StrictMock<ISessionFactory>();
ISession session = mocks.StrictMock<ISession>();
ITransaction transaction = mocks.StrictMock<ITransaction>();
IQuery query = mocks.StrictMock<IQuery>();
IDbProvider provider = A.Fake<IDbProvider>();
IDbConnection connection = A.Fake<IDbConnection>();
ISessionFactory sessionFactory = A.Fake<ISessionFactory>();
ISession session = A.Fake<ISession>();
ITransaction transaction = A.Fake<ITransaction>();
IQuery query = A.Fake<IQuery>();
IList list = new ArrayList();
list.Add("test");
using (mocks.Ordered())
{
Expect.Call(sessionFactory.OpenSession()).Return(session);
Expect.Call(session.Connection).Return(connection);
Expect.Call(session.BeginTransaction(IsolationLevel.Serializable)).Return(transaction);
Expect.Call(session.IsOpen).Return(true);
Expect.Call(session.CreateQuery("some query string")).Return(query);
Expect.Call(query.List()).Return(list);
transaction.Commit();
LastCall.On(transaction).Repeat.Once();
Expect.Call(session.Close()).Return(null);
}
mocks.ReplayAll();
A.CallTo(() => sessionFactory.OpenSession()).Returns(session);
A.CallTo(() => session.Connection).Returns(connection);
A.CallTo(() => session.BeginTransaction(IsolationLevel.Serializable)).Returns(transaction);
A.CallTo(() => session.IsOpen).Returns(true);
A.CallTo(() => session.CreateQuery("some query string")).Returns(query);
A.CallTo(() => query.List()).Returns(list);
LocalSessionFactoryObjectStub lsfo = new LocalSessionFactoryObjectStub(sessionFactory);
lsfo.AfterPropertiesSet();
@@ -119,7 +98,7 @@ namespace Spring.Data.NHibernate
tt.TransactionIsolationLevel = IsolationLevel.Serializable;
Assert.IsFalse(TransactionSynchronizationManager.HasResource(sfProxy),"Hasn't thread session");
Assert.IsFalse(TransactionSynchronizationManager.HasResource(sfProxy), "Hasn't thread session");
Assert.IsFalse(TransactionSynchronizationManager.HasResource(provider), "Hasn't thread db provider");
Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");
Assert.IsFalse(TransactionSynchronizationManager.ActualTransactionActive, "Actual transaction not active");
@@ -133,39 +112,26 @@ namespace Spring.Data.NHibernate
Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");
Assert.IsFalse(TransactionSynchronizationManager.ActualTransactionActive, "Actual transaction not active");
mocks.VerifyAll();
A.CallTo(() => transaction.Commit()).MustHaveHappenedOnceExactly();
A.CallTo(() => session.Close()).MustHaveHappenedOnceExactly();
}
[Test]
public void TransactionRollback()
{
IDbProvider provider = A.Fake<IDbProvider>();
IDbConnection connection = A.Fake<IDbConnection>();
ISessionFactory sessionFactory = A.Fake<ISessionFactory>();
ISession session = A.Fake<ISession>();
ITransaction transaction = A.Fake<ITransaction>();
IDbTransaction adoTransaction = A.Fake<IDbTransaction>();
IDbProvider provider = mocks.StrictMock<IDbProvider>();
IDbConnection connection = mocks.StrictMock<IDbConnection>();
ISessionFactory sessionFactory = mocks.StrictMock<ISessionFactory>();
ISession session = mocks.StrictMock<ISession>();
ITransaction transaction = mocks.StrictMock<ITransaction>();
IDbTransaction adoTransaction = mocks.StrictMock<IDbTransaction>();
using (mocks.Ordered())
{
Expect.Call(sessionFactory.OpenSession()).Return(session);
Expect.Call(session.Connection).Return(connection);
Expect.Call(session.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction);
Expect.Call(session.IsOpen).Return(true);
Expect.Call(adoTransaction.Connection).Return(connection);
LastCall.On(adoTransaction).Repeat.Once();
transaction.Rollback();
LastCall.On(transaction).Repeat.Once();
Expect.Call(session.Close()).Return(null);
}
mocks.ReplayAll();
A.CallTo(() => sessionFactory.OpenSession()).Returns(session).Once();
A.CallTo(() => session.Connection).Returns(connection).Once();
A.CallTo(() => session.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction).Once();
A.CallTo(() => session.IsOpen).Returns(true).Once();
A.CallTo(() => adoTransaction.Connection).Returns(connection).Once();
TestableHibernateTransactionManager tm = new TestableHibernateTransactionManager(sessionFactory);
tm.TransactionSynchronization = TransactionSynchronizationState.Always;
@@ -180,45 +146,32 @@ namespace Spring.Data.NHibernate
{
tt.Execute(new TransactionRollbackTxCallback(sessionFactory));
Assert.Fail("Should have thrown exception");
} catch (ArgumentException)
}
catch (ArgumentException)
{
}
Assert.IsFalse(TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");
Assert.IsFalse(TransactionSynchronizationManager.HasResource(provider), "Hasn't thread db provider");
mocks.VerifyAll();
A.CallTo(() => transaction.Rollback()).MustHaveHappened();
A.CallTo(() => session.Close()).MustHaveHappened();
}
[Test]
public void TransactionRollbackOnly()
{
IDbConnection connection = mocks.StrictMock<IDbConnection>();
ISessionFactory sessionFactory = mocks.StrictMock<ISessionFactory>();
ISession session = mocks.StrictMock<ISession>();
ITransaction transaction = mocks.StrictMock<ITransaction>();
IDbTransaction adoTransaction = mocks.StrictMock<IDbTransaction>();
using (mocks.Ordered())
{
Expect.Call(sessionFactory.OpenSession()).Return(session);
Expect.Call(session.Connection).Return(connection);
Expect.Call(session.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction);
Expect.Call(session.IsOpen).Return(true);
Expect.Call(session.FlushMode).Return(FlushMode.Auto);
session.Flush();
LastCall.On(session).Repeat.Once();
Expect.Call(adoTransaction.Connection).Return(connection);
LastCall.On(adoTransaction).Repeat.Once();
transaction.Rollback();
LastCall.On(transaction).Repeat.Once();
Expect.Call(session.Close()).Return(null);
}
mocks.ReplayAll();
{
IDbConnection connection = A.Fake<IDbConnection>();
ISessionFactory sessionFactory = A.Fake<ISessionFactory>();
ISession session = A.Fake<ISession>();
ITransaction transaction = A.Fake<ITransaction>();
IDbTransaction adoTransaction = A.Fake<IDbTransaction>();
A.CallTo(() => sessionFactory.OpenSession()).Returns(session);
A.CallTo(() => session.Connection).Returns(connection);
A.CallTo(() => session.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction);
A.CallTo(() => session.IsOpen).Returns(true);
A.CallTo(() => session.FlushMode).Returns(FlushMode.Auto);
A.CallTo(() => adoTransaction.Connection).Returns(connection).Once();
TestableHibernateTransactionManager tm = new TestableHibernateTransactionManager(sessionFactory);
tm.TransactionSynchronization = TransactionSynchronizationState.Always;
@@ -231,34 +184,24 @@ namespace Spring.Data.NHibernate
tt.Execute(new TransactionRollbackOnlyTxCallback(sessionFactory));
Assert.IsFalse(TransactionSynchronizationManager.HasResource(sessionFactory), "Shouldn't have a thread session");
mocks.VerifyAll();
A.CallTo(() => session.Flush()).MustHaveHappenedOnceExactly();
A.CallTo(() => transaction.Rollback()).MustHaveHappenedOnceExactly();
A.CallTo(() => session.Close()).MustHaveHappenedOnceExactly();
}
[Test]
public void ParticipatingTransactionWithCommit()
{
IDbConnection connection = mocks.StrictMock<IDbConnection>();
ISessionFactory sessionFactory = mocks.StrictMock<ISessionFactory>();
ISession session = mocks.StrictMock<ISession>();
ITransaction transaction = mocks.StrictMock<ITransaction>();
using (mocks.Ordered())
{
Expect.Call(sessionFactory.OpenSession()).Return(session);
Expect.Call(session.Connection).Return(connection);
Expect.Call(session.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction);
Expect.Call(session.IsOpen).Return(true);
Expect.Call(session.FlushMode).Return(FlushMode.Auto);
session.Flush();
LastCall.On(session).Repeat.Once();
transaction.Commit();
LastCall.On(transaction).Repeat.Once();
Expect.Call(session.Close()).Return(null);
}
mocks.ReplayAll();
IDbConnection connection = A.Fake<IDbConnection>();
ISessionFactory sessionFactory = A.Fake<ISessionFactory>();
ISession session = A.Fake<ISession>();
ITransaction transaction = A.Fake<ITransaction>();
A.CallTo(() => sessionFactory.OpenSession()).Returns(session);
A.CallTo(() => session.Connection).Returns(connection);
A.CallTo(() => session.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction);
A.CallTo(() => session.IsOpen).Returns(true);
A.CallTo(() => session.FlushMode).Returns(FlushMode.Auto);
HibernateTransactionManager tm = new HibernateTransactionManager(sessionFactory);
tm.TransactionSynchronization = TransactionSynchronizationState.Always;
@@ -270,36 +213,25 @@ namespace Spring.Data.NHibernate
object result = tt.Execute(new ParticipatingTransactionWithCommitTxCallback(sessionFactory, list));
Assert.IsTrue(result == list);
mocks.VerifyAll();
A.CallTo(() => session.Flush()).MustHaveHappenedOnceExactly();
A.CallTo(() => transaction.Commit()).MustHaveHappenedOnceExactly();
A.CallTo(() => session.Close()).MustHaveHappenedOnceExactly();
}
[Test]
public void ParticipatingTransactionWithRollback()
{
IDbConnection connection = mocks.StrictMock<IDbConnection>();
ISessionFactory sessionFactory = mocks.StrictMock<ISessionFactory>();
ISession session = mocks.StrictMock<ISession>();
ITransaction transaction = mocks.StrictMock<ITransaction>();
IDbTransaction adoTransaction = mocks.StrictMock<IDbTransaction>();
using (mocks.Ordered())
{
Expect.Call(sessionFactory.OpenSession()).Return(session);
Expect.Call(session.Connection).Return(connection);
Expect.Call(session.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction);
Expect.Call(session.IsOpen).Return(true);
Expect.Call(session.FlushMode).Return(FlushMode.Auto);
Expect.Call(adoTransaction.Connection).Return(connection);
LastCall.On(adoTransaction).Repeat.Once();
transaction.Rollback();
LastCall.On(transaction).Repeat.Once();
Expect.Call(session.Close()).Return(null);
}
mocks.ReplayAll();
IDbConnection connection = A.Fake<IDbConnection>();
ISessionFactory sessionFactory = A.Fake<ISessionFactory>();
ISession session = A.Fake<ISession>();
ITransaction transaction = A.Fake<ITransaction>();
IDbTransaction adoTransaction = A.Fake<IDbTransaction>();
A.CallTo(() => sessionFactory.OpenSession()).Returns(session);
A.CallTo(() => session.Connection).Returns(connection);
A.CallTo(() => session.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction);
A.CallTo(() => session.IsOpen).Returns(true);
A.CallTo(() => session.FlushMode).Returns(FlushMode.Auto);
A.CallTo(() => adoTransaction.Connection).Returns(connection).Once();
TestableHibernateTransactionManager tm = new TestableHibernateTransactionManager(sessionFactory);
tm.TransactionSynchronization = TransactionSynchronizationState.Always;
@@ -313,37 +245,26 @@ namespace Spring.Data.NHibernate
}
catch (ArgumentException)
{
}
mocks.VerifyAll();
A.CallTo(() => transaction.Rollback()).MustHaveHappenedOnceExactly();
A.CallTo(() => session.Close()).MustHaveHappenedOnceExactly();
}
[Test]
public void ParticipatingTransactionWithRollbackOnly()
{
IDbConnection connection = mocks.StrictMock<IDbConnection>();
ISessionFactory sessionFactory = mocks.StrictMock<ISessionFactory>();
ISession session = mocks.StrictMock<ISession>();
ITransaction transaction = mocks.StrictMock<ITransaction>();
IDbTransaction adoTransaction = mocks.StrictMock<IDbTransaction>();
using (mocks.Ordered())
{
Expect.Call(sessionFactory.OpenSession()).Return(session);
Expect.Call(session.Connection).Return(connection);
Expect.Call(session.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction);
Expect.Call(session.IsOpen).Return(true);
Expect.Call(adoTransaction.Connection).Return(connection);
LastCall.On(adoTransaction).Repeat.Once();
transaction.Rollback();
LastCall.On(transaction).Repeat.Once();
Expect.Call(session.Close()).Return(null);
}
mocks.ReplayAll();
IDbConnection connection = A.Fake<IDbConnection>();
ISessionFactory sessionFactory = A.Fake<ISessionFactory>();
ISession session = A.Fake<ISession>();
ITransaction transaction = A.Fake<ITransaction>();
IDbTransaction adoTransaction = A.Fake<IDbTransaction>();
A.CallTo(() => sessionFactory.OpenSession()).Returns(session);
A.CallTo(() => session.Connection).Returns(connection);
A.CallTo(() => session.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction);
A.CallTo(() => session.IsOpen).Returns(true);
A.CallTo(() => adoTransaction.Connection).Returns(connection).Once();
TestableHibernateTransactionManager tm = new TestableHibernateTransactionManager(sessionFactory);
tm.TransactionSynchronization = TransactionSynchronizationState.Always;
@@ -354,50 +275,38 @@ namespace Spring.Data.NHibernate
list.Add("test");
try
{
tt.Execute(new ParticipatingTransactionWithRollbackOnlyTxCallback(tt,sessionFactory,list));
tt.Execute(new ParticipatingTransactionWithRollbackOnlyTxCallback(tt, sessionFactory, list));
Assert.Fail("Should have thrown UnexpectedRollbackException");
}
catch (UnexpectedRollbackException)
{
}
mocks.VerifyAll();
A.CallTo(() => transaction.Rollback()).MustHaveHappenedOnceExactly();
A.CallTo(() => session.Close()).MustHaveHappenedOnceExactly();
}
[Test]
public void ParticipatingTransactionWithWithRequiresNew()
{
IDbConnection connection = mocks.StrictMock<IDbConnection>();
ISessionFactory sessionFactory = mocks.StrictMock<ISessionFactory>();
ISession session1 = mocks.StrictMock<ISession>();
ISession session2 = mocks.StrictMock<ISession>();
ITransaction transaction = mocks.StrictMock<ITransaction>();
IDbConnection connection = A.Fake<IDbConnection>();
ISessionFactory sessionFactory = A.Fake<ISessionFactory>();
ISession session1 = A.Fake<ISession>();
ISession session2 = A.Fake<ISession>();
ITransaction transaction = A.Fake<ITransaction>();
//using (mocks.Ordered())
//{
Expect.Call(sessionFactory.OpenSession()).Return(session1);
Expect.Call(session1.Connection).Return(connection);
Expect.Call(session1.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction);
Expect.Call(session1.IsOpen).Return(true);
A.CallTo(() => sessionFactory.OpenSession()).Returns(session1).Once()
.Then.Returns(session2).Once();
Expect.Call(sessionFactory.OpenSession()).Return(session2);
Expect.Call(session2.Connection).Return(connection);
Expect.Call(session2.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction);
Expect.Call(session2.IsOpen).Return(true);
A.CallTo(() => session1.Connection).Returns(connection);
A.CallTo(() => session1.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction);
A.CallTo(() => session1.IsOpen).Returns(true);
Expect.Call(session2.FlushMode).Return(FlushMode.Auto);
session2.Flush();
LastCall.On(session2).Repeat.Once();
A.CallTo(() => session2.Connection).Returns(connection);
A.CallTo(() => session2.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction);
A.CallTo(() => session2.IsOpen).Returns(true);
transaction.Commit();
LastCall.On(transaction).Repeat.Twice();
Expect.Call(session1.Close()).Return(null);
Expect.Call(session2.Close()).Return(null);
//}
mocks.ReplayAll();
A.CallTo(() => session2.FlushMode).Returns(FlushMode.Auto);
HibernateTransactionManager tm = new HibernateTransactionManager(sessionFactory);
tm.TransactionSynchronization = TransactionSynchronizationState.Always;
@@ -410,36 +319,26 @@ namespace Spring.Data.NHibernate
tt.Execute(new ParticipatingTransactionWithWithRequiresNewTxCallback(tt, sessionFactory));
Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");
mocks.VerifyAll();
A.CallTo(() => transaction.Commit()).MustHaveHappenedTwiceExactly();
A.CallTo(() => session2.Flush()).MustHaveHappenedOnceExactly();
A.CallTo(() => session1.Close()).MustHaveHappenedOnceExactly();
A.CallTo(() => session2.Close()).MustHaveHappenedOnceExactly();
}
[Test]
public void ParticipatingTransactionWithWithNotSupported()
{
IDbConnection connection = mocks.StrictMock<IDbConnection>();
ISessionFactory sessionFactory = mocks.StrictMock<ISessionFactory>();
ISession session = mocks.StrictMock<ISession>();
ITransaction transaction = mocks.StrictMock<ITransaction>();
//using (mocks.Ordered())
//{
Expect.Call(sessionFactory.OpenSession()).Return(session).Repeat.Twice();
Expect.Call(session.Connection).Return(connection);
Expect.Call(session.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction);
Expect.Call(session.IsOpen).Return(true);
Expect.Call(session.FlushMode).Return(FlushMode.Auto).Repeat.Twice();
session.Flush();
LastCall.On(session).Repeat.Twice();
transaction.Commit();
LastCall.On(transaction).Repeat.Once();
Expect.Call(session.Close()).Return(null).Repeat.Once();
//}
mocks.ReplayAll();
IDbConnection connection = A.Fake<IDbConnection>();
ISessionFactory sessionFactory = A.Fake<ISessionFactory>();
ISession session = A.Fake<ISession>();
ITransaction transaction = A.Fake<ITransaction>();
A.CallTo(() => sessionFactory.OpenSession()).Returns(session).Twice();
A.CallTo(() => session.Connection).Returns(connection);
A.CallTo(() => session.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction);
A.CallTo(() => session.IsOpen).Returns(true);
A.CallTo(() => session.FlushMode).Returns(FlushMode.Auto).Twice();
HibernateTransactionManager tm = new HibernateTransactionManager(sessionFactory);
tm.TransactionSynchronization = TransactionSynchronizationState.Always;
@@ -453,28 +352,19 @@ namespace Spring.Data.NHibernate
Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");
mocks.VerifyAll();
A.CallTo(() => session.Flush()).MustHaveHappenedTwiceExactly();
A.CallTo(() => transaction.Commit()).MustHaveHappenedOnceExactly();
A.CallTo(() => session.Close()).MustHaveHappenedOnceExactly();
}
[Test]
public void TransactionWithPropagationSupports()
{
ISessionFactory sessionFactory = mocks.StrictMock<ISessionFactory>();
ISession session = mocks.StrictMock<ISession>();
Expect.Call(sessionFactory.OpenSession()).Return(session);
Expect.Call(session.FlushMode).Return(FlushMode.Never);
session.FlushMode = FlushMode.Auto;
LastCall.IgnoreArguments();
session.Flush();
LastCall.IgnoreArguments();
session.FlushMode = FlushMode.Never;
Expect.Call(session.FlushMode).Return(FlushMode.Never);
mocks.ReplayAll();
ISessionFactory sessionFactory = A.Fake<ISessionFactory>();
ISession session = A.Fake<ISession>();
A.CallTo(() => sessionFactory.OpenSession()).Returns(session);
A.CallTo(() => session.FlushMode).Returns(FlushMode.Never);
LocalSessionFactoryObjectStub lsfo = new LocalSessionFactoryObjectStub(sessionFactory);
lsfo.AfterPropertiesSet();
@@ -493,53 +383,38 @@ namespace Spring.Data.NHibernate
Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");
mocks.VerifyAll();
A.CallTo(() => session.Flush()).MustHaveHappenedOnceExactly();
}
[Test]
public void TransactionWithPropagationSupportsAndInnerTransaction()
{
IDbConnection connection = mocks.StrictMock<IDbConnection>();
ISessionFactory sessionFactory = mocks.StrictMock<ISessionFactory>();
ISession session1 = mocks.StrictMock<ISession>();
ISession session2 = mocks.StrictMock<ISession>();
ITransaction transaction = mocks.StrictMock<ITransaction>();
IDbConnection connection = A.Fake<IDbConnection>();
ISessionFactory sessionFactory = A.Fake<ISessionFactory>();
ISession session1 = A.Fake<ISession>();
ISession session2 = A.Fake<ISession>();
ITransaction transaction = A.Fake<ITransaction>();
Expect.Call(sessionFactory.OpenSession()).Return(session1);
Expect.Call(session1.Connection).Return(connection);
Expect.Call(session1.SessionFactory).Return(sessionFactory);
Expect.Call(session1.FlushMode).Return(FlushMode.Auto).Repeat.Twice();
A.CallTo(() => sessionFactory.OpenSession()).Returns(session1).Once()
.Then.Returns(session2).Once();
session1.Flush();
LastCall.IgnoreArguments().Repeat.Twice();
Expect.Call(session1.Close()).Return(null);
A.CallTo(() => session1.Connection).Returns(connection);
A.CallTo(() => session1.SessionFactory).Returns(sessionFactory);
A.CallTo(() => session1.FlushMode).Returns(FlushMode.Auto);
Expect.Call(sessionFactory.OpenSession()).Return(session2);
Expect.Call(session2.Connection).Return(connection).Repeat.Twice();
Expect.Call(session2.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction);
Expect.Call(session2.FlushMode).Return(FlushMode.Auto);
session2.Flush();
LastCall.IgnoreArguments();
Expect.Call(session2.IsOpen).Return(true);
transaction.Commit();
LastCall.On(transaction).Repeat.Once();
Expect.Call(session2.Close()).Return(null);
mocks.ReplayAll();
A.CallTo(() => session2.Connection).Returns(connection);
A.CallTo(() => session2.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction);
A.CallTo(() => session2.FlushMode).Returns(FlushMode.Auto);
A.CallTo(() => session2.IsOpen).Returns(true);
LocalSessionFactoryObjectStub lsfo = new LocalSessionFactoryObjectStub(sessionFactory);
lsfo.AfterPropertiesSet();
ISessionFactory sfProxy = (ISessionFactory)lsfo.GetObject();
ISessionFactory sfProxy = (ISessionFactory) lsfo.GetObject();
Assert.IsNotNull(sfProxy);
HibernateTransactionManager tm = new HibernateTransactionManager(sessionFactory);
tm.TransactionSynchronization = TransactionSynchronizationState.Always;
TransactionTemplate tt = new TransactionTemplate(tm);
tt.PropagationBehavior = TransactionPropagation.Supports;
TransactionTemplate tt2 = new TransactionTemplate(tm);
@@ -554,11 +429,12 @@ namespace Spring.Data.NHibernate
tt.Execute(new TransactionWithPropagationSupportsAndInnerTransactionTxCallback(tt2, sessionFactory, ht, session1, session2));
Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");
mocks.ReplayAll();
}
A.CallTo(() => transaction.Commit()).MustHaveHappenedOnceExactly();
A.CallTo(() => session1.Flush()).MustHaveHappenedTwiceExactly();
A.CallTo(() => session2.Flush()).MustHaveHappenedOnceExactly();
A.CallTo(() => session2.Close()).MustHaveHappenedOnceExactly();
}
[Test]
public void TransactionCommitWithFlushFailure()
@@ -578,54 +454,38 @@ namespace Spring.Data.NHibernate
/// <param name="fallbackTranslation">if set to <c>true</c> if the exception throw
/// is of the type NHibernate.ADOException, in which case HibernateTransactionManager
/// will 'fallback' to using the error codes in the underlying exception thrown by
/// the provider, ie. a SqlException, MySqlException. Otherwise, if it is
/// another subclass of HibernateException, then perform a direct maping as
/// the provider, ie. a SqlException, MySqlException. Otherwise, if it is
/// another subclass of HibernateException, then perform a direct maping as
/// found in SessionFactoryUtils.ConvertHibernateAccessException.</param>
private void DoTransactionCommitWithFlushFailure(bool fallbackTranslation)
{
#region Mock Setup
IDbProvider provider = new TestDbProvider();
IDbConnection connection = mocks.StrictMock<IDbConnection>();
ISessionFactory sessionFactory = mocks.StrictMock<ISessionFactory>();
ISession session = mocks.StrictMock<ISession>();
ITransaction transaction = mocks.StrictMock<ITransaction>();
IDbTransaction adoTransaction = mocks.StrictMock<IDbTransaction>();
Exception rootCause = null;
using (mocks.Ordered())
IDbConnection connection = A.Fake<IDbConnection>();
ISessionFactory sessionFactory = A.Fake<ISessionFactory>();
ISession session = A.Fake<ISession>();
ITransaction transaction = A.Fake<ITransaction>();
IDbTransaction adoTransaction = A.Fake<IDbTransaction>();
Exception rootCause;
A.CallTo(() => sessionFactory.OpenSession()).Returns(session);
A.CallTo(() => session.Connection).Returns(connection);
A.CallTo(() => session.BeginTransaction(IsolationLevel.ReadCommitted)).Returns(transaction);
A.CallTo(() => session.IsOpen).Returns(true);
Exception sqlException = new TestSqlException("mymsg", "2627");
if (fallbackTranslation)
{
Expect.Call(sessionFactory.OpenSession()).Return(session);
Expect.Call(session.Connection).Return(connection);
Expect.Call(session.BeginTransaction(IsolationLevel.ReadCommitted)).Return(transaction);
Expect.Call(session.IsOpen).Return(true);
transaction.Commit();
Exception sqlException = new TestSqlException("mymsg", "2627");
if (fallbackTranslation)
{
//error code 2627 will map to a DataAccessIntegrity exception in sqlserver, which is the metadata
//used by TestDbProvider.
rootCause = sqlException;
LastCall.On(transaction).Throw(new ADOException("mymsg", sqlException));
}
else
{
rootCause = new PropertyValueException("mymsg", typeof(string).Name, "Name");
LastCall.On(transaction).Throw(rootCause);
}
Expect.Call(adoTransaction.Connection).Return(connection);
LastCall.On(adoTransaction).Repeat.Once();
transaction.Rollback();
LastCall.On(transaction).Repeat.Once();
Expect.Call(session.Close()).Return(null);
//error code 2627 will map to a DataAccessIntegrity exception in sqlserver, which is the metadata
//used by TestDbProvider.
rootCause = sqlException;
A.CallTo(() => transaction.Commit()).Throws(new ADOException("mymsg", sqlException));
}
else
{
rootCause = new PropertyValueException("mymsg", typeof(string).Name, "Name");
A.CallTo(() => transaction.Commit()).Throws(rootCause);
}
#endregion
mocks.ReplayAll();
A.CallTo(() => adoTransaction.Connection).Returns(connection).Once();
TestableHibernateTransactionManager tm = new TestableHibernateTransactionManager(sessionFactory);
tm.TransactionSynchronization = TransactionSynchronizationState.Always;
@@ -652,31 +512,27 @@ namespace Spring.Data.NHibernate
Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sessionFactory), "Hasn't thread session");
Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");
mocks.VerifyAll();
A.CallTo(() => transaction.Rollback()).MustHaveHappenedOnceExactly();
A.CallTo(() => session.Close()).MustHaveHappenedOnceExactly();
}
}
#region Supporting classes for test TransactionCommit
public class TransactionCommitTxCallback : ITransactionCallback
{
private ISessionFactory sfProxy;
private IDbProvider provider;
public TransactionCommitTxCallback(ISessionFactory sessionFactory, IDbProvider provider)
{
sfProxy = sessionFactory;
this.provider = provider;
}
public object DoInTransaction(ITransactionStatus status)
{
Assert.IsTrue(TransactionSynchronizationManager.HasResource(sfProxy),"Has thread session");
Assert.IsTrue(TransactionSynchronizationManager.HasResource(sfProxy), "Has thread session");
Assert.IsTrue(TransactionSynchronizationManager.HasResource(provider), "Hasn't thread db provider");
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive);
@@ -685,9 +541,10 @@ namespace Spring.Data.NHibernate
}
}
public class LocalSessionFactoryObjectStub : LocalSessionFactoryObject
public class LocalSessionFactoryObjectStub : LocalSessionFactoryObject
{
private ISessionFactory sf;
public LocalSessionFactoryObjectStub(ISessionFactory sf)
{
this.sf = sf;
@@ -699,13 +556,10 @@ namespace Spring.Data.NHibernate
}
}
#endregion
#region Supporting classes for test TransactionRollback
public class TransactionRollbackTxCallback : ITransactionCallback
{
private ISessionFactory sf;
public TransactionRollbackTxCallback(ISessionFactory sf)
{
this.sf = sf;
@@ -713,7 +567,7 @@ namespace Spring.Data.NHibernate
public object DoInTransaction(ITransactionStatus status)
{
Assert.IsTrue(TransactionSynchronizationManager.HasResource(sf),"Has thread session");
Assert.IsTrue(TransactionSynchronizationManager.HasResource(sf), "Has thread session");
HibernateTemplate ht = new HibernateTemplate(sf);
return ht.ExecuteFind(new ThrowExceptionHibernateCallback());
}
@@ -727,13 +581,10 @@ namespace Spring.Data.NHibernate
}
}
#endregion
#region Supporting classes for test TransactionRollbackOnly
public class TransactionRollbackOnlyTxCallback : ITransactionCallback
{
private ISessionFactory sf;
public TransactionRollbackOnlyTxCallback(ISessionFactory sf)
{
this.sf = sf;
@@ -755,14 +606,12 @@ namespace Spring.Data.NHibernate
return null;
}
}
#endregion
#region Supporting classes for test ParticipatingTransactionWithCommit
public class ParticipatingTransactionWithCommitTxCallback : ITransactionCallback
{
private ISessionFactory sf;
private IList list;
public ParticipatingTransactionWithCommitTxCallback(ISessionFactory sf, IList list)
{
this.sf = sf;
@@ -784,13 +633,10 @@ namespace Spring.Data.NHibernate
}
}
#endregion
#region Supporting classes for test ParticipatingTransactionWithRollback
public class ParticipatingTransactionWithRollbackTxCallback : ITransactionCallback
{
private ISessionFactory sf;
public ParticipatingTransactionWithRollbackTxCallback(ISessionFactory sf)
{
this.sf = sf;
@@ -803,18 +649,14 @@ namespace Spring.Data.NHibernate
ht.TemplateFlushMode = TemplateFlushMode.Eager;
return ht.ExecuteFind(new ThrowExceptionHibernateCallback());
}
}
#endregion
#region Supporting classes for test ParticipatingTransactionWithRollbackOnly
public class ParticipatingTransactionWithRollbackOnlyTxCallback : ITransactionCallback
{
private TransactionTemplate tt;
private ISessionFactory sf;
private IList list;
public ParticipatingTransactionWithRollbackOnlyTxCallback(TransactionTemplate tt, ISessionFactory sf, IList list)
{
this.tt = tt;
@@ -840,11 +682,7 @@ namespace Spring.Data.NHibernate
{
return list;
}
}
#endregion
#region Supporting classes for test ParticipatingTransactionWithWithRequiresNew
public class ParticipatingTransactionWithWithRequiresNewTxCallback : ITransactionCallback
{
@@ -860,19 +698,17 @@ namespace Spring.Data.NHibernate
public object DoInTransaction(ITransactionStatus status)
{
SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.GetResource(sf);
Assert.IsNotNull(holder,"Has thread session");
Assert.IsNotNull(holder, "Has thread session");
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive);
tt.Execute(new RequiresNewTxCallback(sf, holder));
Assert.IsTrue(holder.Session == SessionFactoryUtils.GetSession(sf, false),"Same thread session as before");
Assert.IsTrue(holder.Session == SessionFactoryUtils.GetSession(sf, false), "Same thread session as before");
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive);
return null;
}
}
public class RequiresNewTxCallback : ITransactionCallback
@@ -905,17 +741,13 @@ namespace Spring.Data.NHibernate
public object DoInHibernate(ISession session)
{
Assert.IsTrue(session != holder.Session,"Not enclosing session");
Assert.IsTrue(session != holder.Session, "Not enclosing session");
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive);
return null;
}
}
#endregion
#region Supporting classes for test ParticipatingTransactionWithWithNotSupported
public class ParticipatingTransactionWithWithNotSupportedTxCallback : ITransactionCallback
{
@@ -930,11 +762,11 @@ namespace Spring.Data.NHibernate
public object DoInTransaction(ITransactionStatus status)
{
SessionHolder holder = (SessionHolder)TransactionSynchronizationManager.GetResource(sf);
SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.GetResource(sf);
Assert.IsNotNull(holder, "Has thread session");
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive);
tt.PropagationBehavior = TransactionPropagation.NotSupported;
tt.PropagationBehavior = TransactionPropagation.NotSupported;
tt.Execute(new NotSupportedTxCallback(sf));
Assert.IsTrue(holder.Session == SessionFactoryUtils.GetSession(sf, false), "Same thread session as before");
@@ -942,8 +774,6 @@ namespace Spring.Data.NHibernate
Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive);
return null;
}
}
public class NotSupportedTxCallback : ITransactionCallback
@@ -957,8 +787,6 @@ namespace Spring.Data.NHibernate
public object DoInTransaction(ITransactionStatus status)
{
Assert.IsTrue(!TransactionSynchronizationManager.HasResource(sf), "Hasn't thread session");
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
Assert.IsFalse(TransactionSynchronizationManager.ActualTransactionActive);
@@ -971,25 +799,19 @@ namespace Spring.Data.NHibernate
public class NotSupportedTxCallbackInner : IHibernateCallback
{
public object DoInHibernate(ISession session)
{
return null;
}
}
#endregion
#region Supporting classes for test TransactionWithPropagationSupports
public class TransactionWithPropagationSupportsTxCallback : ITransactionCallback
{
private ISessionFactory sf;
public TransactionWithPropagationSupportsTxCallback(ISessionFactory sf)
{
this.sf = sf;
}
public object DoInTransaction(ITransactionStatus status)
@@ -1013,10 +835,6 @@ namespace Spring.Data.NHibernate
}
}
#endregion
#region Supporting classes for test ParticipatingTransactionWithWithNotSupported
public class TransactionWithPropagationSupportsAndInnerTransactionTxCallback : ITransactionCallback
{
@@ -1026,7 +844,7 @@ namespace Spring.Data.NHibernate
private ISession session1;
private ISession session2;
public TransactionWithPropagationSupportsAndInnerTransactionTxCallback(TransactionTemplate tt,
public TransactionWithPropagationSupportsAndInnerTransactionTxCallback(TransactionTemplate tt,
ISessionFactory sf, HibernateTemplate ht, ISession session1, ISession session2)
{
this.tt = tt;
@@ -1051,7 +869,7 @@ namespace Spring.Data.NHibernate
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
Assert.IsFalse(TransactionSynchronizationManager.ActualTransactionActive);
return null;
}
@@ -1085,16 +903,8 @@ namespace Spring.Data.NHibernate
return null;
}
}
}
#endregion
#region Supporting classes for DoTransactionCommitWithFlushFailure
public class TransactionCommitWithFlushFailureCallback : ITransactionCallback
{
private ISessionFactory sessionFactory;
@@ -1112,13 +922,12 @@ namespace Spring.Data.NHibernate
HibernateTemplate ht = new HibernateTemplate(sessionFactory);
return ht.ExecuteFind(new TransactionCommitWithFlushFailureHibernateCallback(list));
}
}
public class TransactionCommitWithFlushFailureHibernateCallback : IHibernateCallback
{
private IList list;
public TransactionCommitWithFlushFailureHibernateCallback(IList list)
{
this.list = list;
@@ -1129,7 +938,4 @@ namespace Spring.Data.NHibernate
return list;
}
}
#endregion
}

View File

@@ -18,22 +18,18 @@
#endregion
#region Imports
using System.Data.SqlClient;
using FakeItEasy;
using NHibernate.Connection;
using NHibernate.Driver;
using NHibernate.Engine;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Data.Common;
#endregion
namespace Spring.Data.NHibernate
{
/// <summary>
@@ -46,23 +42,19 @@ namespace Spring.Data.NHibernate
[Test]
public void SessionFactoryUtilsWithGetDbProvider()
{
MockRepository mockery = new MockRepository();
ISessionFactoryImplementor sessionFactory = mockery.DynamicMock<ISessionFactoryImplementor>();
ISessionFactoryImplementor sessionFactory = A.Fake<ISessionFactoryImplementor>();
DriverBase driver = mockery.DynamicMock<DriverBase>();
Expect.Call(driver.CreateCommand()).Repeat.AtLeastOnce().Return(new SqlCommand());
DriverBase driver = A.Fake<DriverBase>();
A.CallTo(() => driver.CreateCommand()).Returns(new SqlCommand());
IConnectionProvider cp = mockery.DynamicMock<IConnectionProvider>();
Expect.Call(cp.Driver).Repeat.AtLeastOnce().Return(driver);
IConnectionProvider cp = A.Fake<IConnectionProvider>();
A.CallTo(() => cp.Driver).Returns(driver);
Expect.Call(sessionFactory.ConnectionProvider).Repeat.AtLeastOnce().Return(cp);
A.CallTo(() => sessionFactory.ConnectionProvider).Returns(cp);
mockery.ReplayAll();
IDbProvider provider = SessionFactoryUtils.GetDbProvider(sessionFactory);
Assert.AreEqual(typeof(SqlCommand), provider.DbMetadata.CommandType);
mockery.VerifyAll();
}
}
}

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
* Copyright © 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,9 +20,11 @@
#region Imports
using FakeItEasy;
using NHibernate;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Context.Support;
using Spring.Objects.Factory.Config;
@@ -43,8 +45,7 @@ namespace Spring.Data.NHibernate.Support
string SESSIONFACTORY_OBJECTNAME = ConfigSectionSessionScopeSettings.DEFAULT_SESSION_FACTORY_OBJECT_NAME;
// setup expected values
MockRepository mocks = new MockRepository();
ISessionFactory expectedSessionFactory = mocks.StrictMock<ISessionFactory>();
ISessionFactory expectedSessionFactory = A.Fake<ISessionFactory>();
IInterceptor expectedEntityInterceptor = null;
bool expectedSingleSession = SessionScopeSettings.SINGLESESSION_DEFAULT;
FlushMode expectedDefaultFlushMode = SessionScopeSettings.FLUSHMODE_DEFAULT;
@@ -70,9 +71,8 @@ namespace Spring.Data.NHibernate.Support
string SESSIONFACTORY_OBJECTNAME = "SessionFactory";
string ENTITYINTERCEPTOR_OBJECTNAME = "EntityInterceptor";
MockRepository mocks = new MockRepository();
ISessionFactory expectedSessionFactory = mocks.StrictMock<ISessionFactory>();
IInterceptor expectedEntityInterceptor = mocks.StrictMock<IInterceptor>();
ISessionFactory expectedSessionFactory = A.Fake<ISessionFactory>();
IInterceptor expectedEntityInterceptor = A.Fake<IInterceptor>();
bool expectedSingleSession = false;
FlushMode expectedDefaultFlushMode = FlushMode.Auto;
@@ -93,7 +93,7 @@ namespace Spring.Data.NHibernate.Support
.Add(thisTypeName + ".DefaultFlushMode", expectedDefaultFlushMode.ToString().ToLower() ) // case insensitive!
;
ConfigSectionSessionScopeSettings settings = new ConfigSectionSessionScopeSettings(this.GetType(), variableSource);
Assert.AreEqual( expectedSessionFactory, settings.SessionFactory );

View File

@@ -18,14 +18,13 @@
#endregion
#region Imports
using System;
using NHibernate;
using NUnit.Framework;
using Rhino.Mocks;
#endregion
using FakeItEasy;
using NHibernate;
using NUnit.Framework;
namespace Spring.Data.NHibernate.Support
{
@@ -39,7 +38,7 @@ namespace Spring.Data.NHibernate.Support
private class DerivedSessionScopeSettings : SessionScopeSettings
{
public DerivedSessionScopeSettings()
:base() // note, that we're calling default ctor here
: base() // note, that we're calling default ctor here
{
}
}
@@ -73,23 +72,22 @@ namespace Spring.Data.NHibernate.Support
[Test]
public void CheckDefaults()
{
Assert.IsTrue( SessionScopeSettings.SINGLESESSION_DEFAULT );
Assert.AreEqual( FlushMode.Never, SessionScopeSettings.FLUSHMODE_DEFAULT );
Assert.IsTrue(SessionScopeSettings.SINGLESESSION_DEFAULT);
Assert.AreEqual(FlushMode.Never, SessionScopeSettings.FLUSHMODE_DEFAULT);
}
[Test]
public void WorksAsExpected()
{
MockRepository mocks = new MockRepository();
ISessionFactory sessionFactory = mocks.StrictMock<ISessionFactory>();
IInterceptor entityInterceptor = mocks.StrictMock<IInterceptor>();
Assert.AreNotEqual( FlushMode.Auto, SessionScopeSettings.FLUSHMODE_DEFAULT ); // ensure noone changed our assumptions
SessionScopeSettings sss = new SessionScopeSettings(sessionFactory, entityInterceptor, !SessionScopeSettings.SINGLESESSION_DEFAULT, FlushMode.Auto );
ISessionFactory sessionFactory = A.Fake<ISessionFactory>();
IInterceptor entityInterceptor = A.Fake<IInterceptor>();
Assert.AreNotEqual(FlushMode.Auto, SessionScopeSettings.FLUSHMODE_DEFAULT); // ensure noone changed our assumptions
SessionScopeSettings sss = new SessionScopeSettings(sessionFactory, entityInterceptor, !SessionScopeSettings.SINGLESESSION_DEFAULT, FlushMode.Auto);
Assert.AreEqual( sessionFactory, sss.SessionFactory );
Assert.AreEqual( entityInterceptor, sss.EntityInterceptor);
Assert.AreEqual( !SessionScopeSettings.SINGLESESSION_DEFAULT, sss.SingleSession );
Assert.AreEqual( FlushMode.Auto, sss.DefaultFlushMode );
Assert.AreEqual(sessionFactory, sss.SessionFactory);
Assert.AreEqual(entityInterceptor, sss.EntityInterceptor);
Assert.AreEqual(!SessionScopeSettings.SINGLESESSION_DEFAULT, sss.SingleSession);
Assert.AreEqual(FlushMode.Auto, sss.DefaultFlushMode);
}
[Test]
@@ -108,15 +106,16 @@ namespace Spring.Data.NHibernate.Support
ISessionFactory sessionFactory = sss.SessionFactory;
Assert.Fail("should fail, because derived classes must override ResolveSessionFactory()");
}
catch (NotSupportedException) { }
catch (NotSupportedException)
{
}
}
[Test]
public void CallingDefaultConstructorCausesLazyResolvingReferences()
{
MockRepository mocks = new MockRepository();
ISessionFactory expectedSessionFactory = mocks.StrictMock<ISessionFactory>();
IInterceptor expectedEntityInterceptor = mocks.StrictMock<IInterceptor>();
ISessionFactory expectedSessionFactory = A.Fake<ISessionFactory>();
IInterceptor expectedEntityInterceptor = A.Fake<IInterceptor>();
SessionScopeSettings sss = new LazyResolvingSessionScopeSettings(expectedSessionFactory, expectedEntityInterceptor);
@@ -144,8 +143,7 @@ namespace Spring.Data.NHibernate.Support
[Test]
public void MissingEntityInterceptorIsOkDuringLazyResolving()
{
MockRepository mocks = new MockRepository();
ISessionFactory expectedSessionFactory = mocks.StrictMock<ISessionFactory>();
ISessionFactory expectedSessionFactory = A.Fake<ISessionFactory>();
SessionScopeSettings sss = new LazyResolvingSessionScopeSettings(expectedSessionFactory, null);
@@ -156,6 +154,5 @@ namespace Spring.Data.NHibernate.Support
Assert.AreSame(expectedSessionFactory, sss.SessionFactory);
Assert.AreSame(null, sss.EntityInterceptor);
}
}
}

View File

@@ -21,11 +21,16 @@
#region Imports
using System;
using FakeItEasy;
using NHibernate;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Transaction.Support;
using static FakeItEasy.A;
#endregion
namespace Spring.Data.NHibernate.Support
@@ -37,7 +42,6 @@ namespace Spring.Data.NHibernate.Support
[TestFixture]
public class SessionScopeTests
{
private MockRepository mocks;
private ISessionFactory expectedSessionFactory;
private IInterceptor expectedEntityInterceptor;
private bool expectedSingleSession;
@@ -46,9 +50,8 @@ namespace Spring.Data.NHibernate.Support
[SetUp]
public void SetUp()
{
mocks = new MockRepository();
expectedSessionFactory = mocks.StrictMock<ISessionFactory>();
expectedEntityInterceptor = mocks.StrictMock<IInterceptor>();
expectedSessionFactory = Fake<ISessionFactory>();
expectedEntityInterceptor = Fake<IInterceptor>();
expectedSingleSession = SessionScopeSettings.SINGLESESSION_DEFAULT;
expectedDefaultFlushMode = SessionScopeSettings.FLUSHMODE_DEFAULT;
}
@@ -74,14 +77,9 @@ namespace Spring.Data.NHibernate.Support
[Test]
public void CanCreateAndCloseSimpleCtor()
{
using (mocks.Ordered())
{
ISession session = mocks.StrictMock<ISession>();
Expect.Call(expectedSessionFactory.OpenSession()).Return(session);
session.FlushMode = FlushMode.Never;
Expect.Call(session.Close()).Return(null);
}
mocks.ReplayAll();
ISession session = Fake<ISession>();
CallTo(() => expectedSessionFactory.OpenSession()).Returns(session);
using (SessionScope scope = new SessionScope(expectedSessionFactory, true))
{
// no op - just create & dispose
@@ -99,7 +97,9 @@ namespace Spring.Data.NHibernate.Support
Assert.IsNotNull(sessionHolder.Session);
scope.Close();
}
mocks.VerifyAll();
CallToSet(() => session.FlushMode).WhenArgumentsMatch(x => x.Get<FlushMode>(0) == FlushMode.Never).MustHaveHappenedOnceExactly();
CallTo(() => session.Close()).MustHaveHappenedOnceExactly();
}
[Test]
@@ -210,12 +210,9 @@ namespace Spring.Data.NHibernate.Support
[Test]
public void SingleSessionAppliesDefaultFlushModeOnOpenSessionAndClosesSession()
{
ISession expectedSession = mocks.StrictMock<ISession>();
ISession expectedSession = Fake<ISession>();
Expect.Call(expectedSessionFactory.OpenSession()).Return(expectedSession);
expectedSession.FlushMode = FlushMode.Auto;
Expect.Call(expectedSession.Close()).Return(null);
mocks.ReplayAll();
CallTo(() => expectedSessionFactory.OpenSession()).Returns(expectedSession);
SessionScope scope = null;
using (scope = new SessionScope(expectedSessionFactory, null, true, FlushMode.Auto, true))
@@ -227,7 +224,8 @@ namespace Spring.Data.NHibernate.Support
Assert.IsFalse(scope.IsOpen);
Assert.IsFalse(TransactionSynchronizationManager.HasResource(expectedSessionFactory));
mocks.VerifyAll();
CallToSet(() => expectedSession.FlushMode).WhenArgumentsMatch(x => x.Get<FlushMode>(0) == FlushMode.Auto).MustHaveHappenedOnceExactly();
CallTo(() => expectedSession.Close()).MustHaveHappenedOnceExactly();
}
[Test]
@@ -287,39 +285,29 @@ namespace Spring.Data.NHibernate.Support
[Test]
public void ResolvesEntityInterceptorOnEachOpen()
{
TestSessionScopeSettings sss =
(TestSessionScopeSettings)mocks.PartialMock(typeof(TestSessionScopeSettings), expectedSessionFactory);
ISession expectedSession = mocks.StrictMock<ISession>();
TestSessionScopeSettings sss = Fake<TestSessionScopeSettings>(options => options
.CallsBaseMethods()
.WithArgumentsForConstructor(new[] {expectedSessionFactory})
);
ISession expectedSession = Fake<ISession>();
sss.DefaultFlushMode = FlushMode.Never;
SessionScope sc = new SessionScope(sss, false);
using (mocks.Ordered())
{
Expect.Call(sss.DoResolveEntityInterceptor()).Return(expectedEntityInterceptor);
Expect.Call(expectedSessionFactory.OpenSession(expectedEntityInterceptor)).Return(expectedSession);
expectedSession.FlushMode = FlushMode.Never;
Expect.Call(expectedSession.Close()).Return(null);
Expect.Call(sss.DoResolveEntityInterceptor()).Return(expectedEntityInterceptor);
Expect.Call(expectedSessionFactory.OpenSession(expectedEntityInterceptor)).Return(expectedSession);
expectedSession.FlushMode = FlushMode.Never;
Expect.Call(expectedSession.Close()).Return(null);
}
mocks.ReplayAll();
CallTo(() => sss.DoResolveEntityInterceptor()).Returns(expectedEntityInterceptor);
CallTo(() => expectedSessionFactory.OpenSession(expectedEntityInterceptor)).Returns(expectedSession);
sc.Open();
SessionHolder sessionHolder = (SessionHolder)TransactionSynchronizationManager.GetResource(expectedSessionFactory);
SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.GetResource(expectedSessionFactory);
sessionHolder.ContainsSession(null); // force opening session
sc.Close();
sc.Open();
sessionHolder = (SessionHolder)TransactionSynchronizationManager.GetResource(expectedSessionFactory);
sessionHolder = (SessionHolder) TransactionSynchronizationManager.GetResource(expectedSessionFactory);
sessionHolder.ContainsSession(null); // force opening session
sc.Close();
mocks.VerifyAll();
CallToSet(() => expectedSession.FlushMode).WhenArgumentsMatch(x => x.Get<FlushMode>(0) == FlushMode.Never).MustHaveHappenedTwiceExactly();
CallTo(() => expectedSession.Close()).MustHaveHappenedTwiceExactly();
}
}
}
}

View File

@@ -10,10 +10,11 @@
<ProjectReference Include="..\Spring.Data.Tests\Spring.Data.Tests.2010.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="FakeItEasy" Version="$(FakeItEasyVersion)" />
<PackageReference Include="FakeItEasy.Analyzer" Version="$(FakeItEasyVersion)" PrivateAssets="All" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="$(MicrosoftTestSDKVersion)" />
<PackageReference Include="NUnit" Version="$(NUnitVersion)" />
<PackageReference Include="NUnit3TestAdapter" Version="$(NUnitTestAdapterVersion)" />
<PackageReference Include="RhinoMocks" Version="$(RhinoMocksVersion)" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\Spring.Data.NHibernate.Tests\Data\NHibernate\Config\AopConfiguration.cs">

View File

@@ -10,10 +10,11 @@
<ProjectReference Include="..\Spring.Data.Tests\Spring.Data.Tests.2010.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="FakeItEasy" Version="$(FakeItEasyVersion)" />
<PackageReference Include="FakeItEasy.Analyzer" Version="$(FakeItEasyVersion)" PrivateAssets="All" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="$(MicrosoftTestSDKVersion)" />
<PackageReference Include="NUnit" Version="$(NUnitVersion)" />
<PackageReference Include="NUnit3TestAdapter" Version="$(NUnitTestAdapterVersion)" />
<PackageReference Include="RhinoMocks" Version="$(RhinoMocksVersion)" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\Spring.Data.NHibernate.Tests\Data\NHibernate\Config\AopConfiguration.cs">

View File

@@ -22,8 +22,11 @@ using System;
using System.Collections;
using System.Data;
using System.Data.Common;
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Dao;
using Spring.Threading;
@@ -36,14 +39,6 @@ namespace Spring.Data.Common
[TestFixture]
public class MultiDelegatingDbProviderTests
{
private MockRepository mocks;
[SetUp]
public void Setup()
{
mocks = new MockRepository();
}
[Test]
public void CreationWhenNoRequiredPropertiesSet()
{
@@ -197,33 +192,33 @@ namespace Spring.Data.Common
[Test]
public void CreateOperations()
{
IDbProvider dbProvider = mocks.StrictMock<IDbProvider>();
IDbConnection mockConnection = mocks.StrictMock<IDbConnection>();
Expect.Call(dbProvider.CreateConnection()).Return(mockConnection).Repeat.Once();
IDbProvider dbProvider = A.Fake<IDbProvider>();
IDbConnection mockConnection = A.Fake<IDbConnection>();
A.CallTo(() => dbProvider.CreateConnection()).Returns(mockConnection).Once();
IDbCommand mockCommand = (IDbCommand)mocks.CreateMock(typeof(IDbCommand));
Expect.Call(dbProvider.CreateCommand()).Return(mockCommand).Repeat.Once();
IDbCommand mockCommand = A.Fake<IDbCommand>();
A.CallTo(() => dbProvider.CreateCommand()).Returns(mockCommand).Once();
IDbDataParameter mockParameter = (IDbDataParameter) mocks.CreateMock(typeof (IDbDataParameter));
Expect.Call(dbProvider.CreateParameter()).Return(mockParameter).Repeat.Once();
IDbDataParameter mockParameter = A.Fake<IDbDataParameter>();
A.CallTo(() => dbProvider.CreateParameter()).Returns(mockParameter).Once();
IDbDataAdapter mockDataAdapter = (IDbDataAdapter) mocks.CreateMock(typeof (IDbDataAdapter));
Expect.Call(dbProvider.CreateDataAdapter()).Return(mockDataAdapter).Repeat.Once();
IDbDataAdapter mockDataAdapter = A.Fake<IDbDataAdapter>();
A.CallTo(() => dbProvider.CreateDataAdapter()).Returns(mockDataAdapter).Once();
DbCommandBuilder mockDbCommandBuilder = (DbCommandBuilder) mocks.CreateMock(typeof (DbCommandBuilder));
Expect.Call(dbProvider.CreateCommandBuilder()).Return(mockDbCommandBuilder).Repeat.Once();
DbCommandBuilder mockDbCommandBuilder = A.Fake<DbCommandBuilder>();
A.CallTo(() => dbProvider.CreateCommandBuilder()).Returns(mockDbCommandBuilder).Once();
Expect.Call(dbProvider.CreateParameterName("p1")).Return("@p1").Repeat.Once();
Expect.Call(dbProvider.CreateParameterNameForCollection("c1")).Return("cc1");
A.CallTo(() => dbProvider.CreateParameterName("p1")).Returns("@p1").Once();
A.CallTo(() => dbProvider.CreateParameterNameForCollection("c1")).Returns("cc1");
IDbMetadata mockDbMetaData = (IDbMetadata) mocks.CreateMock(typeof (IDbMetadata));
Expect.Call(dbProvider.DbMetadata).Return(mockDbMetaData);
IDbMetadata mockDbMetaData = A.Fake<IDbMetadata>();
A.CallTo(() => dbProvider.DbMetadata).Returns(mockDbMetaData);
Exception e = new Exception("foo");
Expect.Call(dbProvider.ExtractError(e)).Return("badsql").Repeat.Once();
DbException dbException = (DbException) mocks.CreateMock(typeof (DbException));
A.CallTo(() => dbProvider.ExtractError(e)).Returns("badsql").Once();
DbException dbException = A.Fake<DbException>();
MultiDelegatingDbProvider multiDbProvider = new MultiDelegatingDbProvider();
IDictionary targetDbProviders = new Hashtable();
targetDbProviders.Add("db1", dbProvider);
@@ -231,9 +226,6 @@ namespace Spring.Data.Common
multiDbProvider.TargetDbProviders = targetDbProviders;
multiDbProvider.AfterPropertiesSet();
mocks.ReplayAll();
Assert.IsNotNull(multiDbProvider.CreateConnection());
Assert.IsNotNull(multiDbProvider.CreateCommand());
Assert.IsNotNull(multiDbProvider.CreateParameter());
@@ -245,7 +237,6 @@ namespace Spring.Data.Common
Assert.AreEqual("badsql", multiDbProvider.ExtractError(e));
Assert.IsTrue(multiDbProvider.IsDataAccessException(dbException));
Assert.IsFalse(multiDbProvider.IsDataAccessException(e));
mocks.VerifyAll();
}
}
}

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <20> 2002-2011 the original author or authors.
* Copyright <20> 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,13 +18,11 @@
#endregion
#region Imports
using System.Data;
using NUnit.Framework;
using Rhino.Mocks;
#endregion
using FakeItEasy;
using NUnit.Framework;
namespace Spring.Data.Common
{
@@ -35,28 +33,13 @@ namespace Spring.Data.Common
[TestFixture]
public class UserCredentialsDbProviderTests
{
private MockRepository mocks;
[SetUp]
public void Setup()
{
mocks = new MockRepository();
}
[Test]
public void StaticCredentials()
{
IDbProvider dbProvider = mocks.StrictMock<IDbProvider>();
IDbConnection connection = mocks.StrictMock<IDbConnection>();
using (mocks.Ordered())
{
Expect.Call(dbProvider.CreateConnection()).Return(connection);
Expect.Call(dbProvider.ConnectionString).Return(
@"Data Source=MARKT60\SQL2005;Database=Spring;Trusted_Connection=False");
Expect.Call(connection.ConnectionString = @"Data Source=MARKT60\SQL2005;Database=Spring;Trusted_Connection=False;User ID=springqa;Password=springqa");
}
mocks.ReplayAll();
IDbProvider dbProvider = A.Fake<IDbProvider>();
IDbConnection connection = A.Fake<IDbConnection>();
A.CallTo(() => dbProvider.CreateConnection()).Returns(connection);
A.CallTo(() => dbProvider.ConnectionString).Returns(@"Data Source=MARKT60\SQL2005;Database=Spring;Trusted_Connection=False");
UserCredentialsDbProvider provider = new UserCredentialsDbProvider();
provider.TargetDbProvider = dbProvider;
@@ -64,50 +47,39 @@ namespace Spring.Data.Common
provider.Password = "Password=springqa";
Assert.AreEqual(connection, provider.CreateConnection());
mocks.VerifyAll();
A.CallToSet(() => connection.ConnectionString)
.WhenArgumentsMatch(x => (string) x[0] == "Data Source=MARKT60\\SQL2005;Database=Spring;Trusted_Connection=False;User ID=springqa;Password=springqa")
.MustHaveHappenedOnceExactly();
}
[Test]
public void NoCredentials()
{
IDbProvider dbProvider = mocks.StrictMock<IDbProvider>();
IDbConnection connection = mocks.StrictMock<IDbConnection>();
using (mocks.Ordered())
{
Expect.Call(dbProvider.CreateConnection()).Return(connection);
}
IDbProvider dbProvider = A.Fake<IDbProvider>();
IDbConnection connection = A.Fake<IDbConnection>();
A.CallTo(() => dbProvider.CreateConnection()).Returns(connection);
mocks.ReplayAll();
UserCredentialsDbProvider provider = new UserCredentialsDbProvider();
provider.TargetDbProvider = dbProvider;
Assert.AreEqual(connection, provider.CreateConnection());
mocks.VerifyAll();
}
[Test]
public void ThreadBoundCredentials()
{
IDbProvider dbProvider = mocks.StrictMock<IDbProvider>();
IDbConnection connection = mocks.StrictMock<IDbConnection>();
using (mocks.Ordered())
{
Expect.Call(dbProvider.CreateConnection()).Return(connection);
Expect.Call(dbProvider.ConnectionString).Return(
@"Data Source=MARKT60\SQL2005;Database=Spring;Trusted_Connection=False");
Expect.Call(connection.ConnectionString = @"Data Source=MARKT60\SQL2005;Database=Spring;Trusted_Connection=False;User ID=springqa;Password=springqa");
}
mocks.ReplayAll();
IDbProvider dbProvider = A.Fake<IDbProvider>();
IDbConnection connection = A.Fake<IDbConnection>();
A.CallTo(() => dbProvider.CreateConnection()).Returns(connection);
A.CallTo(() => dbProvider.ConnectionString).Returns(@"Data Source=MARKT60\SQL2005;Database=Spring;Trusted_Connection=False");
UserCredentialsDbProvider provider = new UserCredentialsDbProvider();
provider.TargetDbProvider = dbProvider;
provider.SetCredentialsForCurrentThread("User ID=springqa", "Password=springqa");
Assert.AreEqual(connection, provider.CreateConnection());
mocks.VerifyAll();
A.CallToSet(() => connection.ConnectionString)
.WhenArgumentsMatch(x => (string) x[0] == "Data Source=MARKT60\\SQL2005;Database=Spring;Trusted_Connection=False;User ID=springqa;Password=springqa")
.MustHaveHappenedOnceExactly();
}
}
}

View File

@@ -1,7 +1,5 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
* Copyright © 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,20 +14,17 @@
* limitations under the License.
*/
#endregion
#region Imports
using System;
using System.EnterpriseServices;
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Data.Support;
using Spring.Transaction;
using Spring.Transaction.Support;
#endregion
namespace Spring.Data.Core
{
/// <summary>
@@ -39,53 +34,33 @@ namespace Spring.Data.Core
[TestFixture]
public class ServiceDomainTransactionManagerTests
{
private MockRepository mocks;
[SetUp]
public void Setup()
{
mocks = new MockRepository();
}
[Test]
public void TransactionCommit()
{
#region Mock Setup
IServiceDomainAdapter txAdapter = (IServiceDomainAdapter) mocks.CreateMock(typeof (IServiceDomainAdapter));
using (mocks.Ordered())
{
Expect.Call(txAdapter.IsInTransaction).Return(false);
SimpleServiceConfig serviceConfig = new SimpleServiceConfig();
ConfigureServiceConfig(serviceConfig, true);
txAdapter.Enter(serviceConfig);
IServiceDomainAdapter txAdapter = A.Fake<IServiceDomainAdapter>();
//ProcessCommit - status.GlobalRollbackOnly check
Expect.Call(txAdapter.MyTransactionVote).Return(TransactionVote.Commit);
//DoCommit - status.GlobalRollbackOnly check
Expect.Call(txAdapter.MyTransactionVote).Return(TransactionVote.Commit);
A.CallTo(() => txAdapter.IsInTransaction).Returns(false).Once().Then.Returns(true).Once();
Expect.Call(txAdapter.IsInTransaction).Return(true);
//DoCommit - check to call SetComplete or SetAbort
Expect.Call(txAdapter.MyTransactionVote).Return(TransactionVote.Commit);
txAdapter.SetComplete();
Expect.Call(txAdapter.Leave()).Return(TransactionStatus.Commited);
//ProcessCommit - status.GlobalRollbackOnly check
//DoCommit - status.GlobalRollbackOnly check
//DoCommit - check to call SetComplete or SetAbort
A.CallTo(() => txAdapter.MyTransactionVote).Returns(TransactionVote.Commit).NumberOfTimes(3);
}
#endregion
mocks.ReplayAll();
A.CallTo(() => txAdapter.Leave()).Returns(TransactionStatus.Commited).Once();
ServiceDomainPlatformTransactionManager tm = new ServiceDomainPlatformTransactionManager(txAdapter);
TransactionTemplate tt = new TransactionTemplate(tm);
tm.TransactionSynchronization = TransactionSynchronizationState.Always;
tt.Execute(new TransactionDelegate(TransactionCommitMethod));
tt.Execute(TransactionCommitMethod);
Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive);
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
mocks.VerifyAll();
SimpleServiceConfig serviceConfig = new SimpleServiceConfig();
ConfigureServiceConfig(serviceConfig, true);
A.CallTo(() => txAdapter.Enter(serviceConfig)).MustHaveHappenedOnceExactly();
A.CallTo(() => txAdapter.SetComplete()).MustHaveHappenedOnceExactly();
}
private object TransactionCommitMethod(ITransactionStatus status)
@@ -98,23 +73,13 @@ namespace Spring.Data.Core
[Test]
public void TransactionRollback()
{
#region Mock Setup
IServiceDomainAdapter txAdapter = (IServiceDomainAdapter)mocks.CreateMock(typeof(IServiceDomainAdapter));
using (mocks.Ordered())
{
Expect.Call(txAdapter.IsInTransaction).Return(false);
SimpleServiceConfig serviceConfig = new SimpleServiceConfig();
ConfigureServiceConfig(serviceConfig, true);
txAdapter.Enter(serviceConfig);
Expect.Call(txAdapter.IsInTransaction).Return(true);
txAdapter.SetAbort();
Expect.Call(txAdapter.Leave()).Return(TransactionStatus.Commited);
SimpleServiceConfig serviceConfig = new SimpleServiceConfig();
ConfigureServiceConfig(serviceConfig, standardIsolationAndProp: true);
}
#endregion
mocks.ReplayAll();
IServiceDomainAdapter txAdapter = A.Fake<IServiceDomainAdapter>();
A.CallTo(() => txAdapter.IsInTransaction).Returns(false).Once().Then.Returns(true);
A.CallTo(() => txAdapter.Leave()).Returns(TransactionStatus.Commited);
ServiceDomainPlatformTransactionManager tm = new ServiceDomainPlatformTransactionManager(txAdapter);
tm.TransactionSynchronization = TransactionSynchronizationState.Always;
@@ -136,53 +101,25 @@ namespace Spring.Data.Core
Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");
mocks.VerifyAll();
A.CallTo(() => txAdapter.SetAbort()).MustHaveHappenedOnceExactly();
A.CallTo(() => txAdapter.Enter(serviceConfig)).MustHaveHappenedOnceExactly();
}
[Test]
public void PropagationRequiresNewWithExistingTransaction()
{
#region Mock Setup
IServiceDomainAdapter txAdapter = (IServiceDomainAdapter)mocks.CreateMock(typeof(IServiceDomainAdapter));
using (mocks.Ordered())
{
IServiceDomainAdapter txAdapter = A.Fake<IServiceDomainAdapter>();
Expect.Call(txAdapter.IsInTransaction).Return(false);
SimpleServiceConfig serviceConfig = new SimpleServiceConfig();
ConfigureServiceConfig(serviceConfig, true);
txAdapter.Enter(serviceConfig);
A.CallTo(() => txAdapter.IsInTransaction)
.Returns(false).Once()
.Then.Returns(true).NumberOfTimes(3);
A.CallTo(() => txAdapter.Leave())
.Returns(TransactionStatus.Aborted).Once()
.Then.Returns(TransactionStatus.Commited).Once();
Expect.Call(txAdapter.IsInTransaction).Return(true);
// inner tx
ConfigureServiceConfig(serviceConfig, false);
serviceConfig.TransactionOption = TransactionOption.RequiresNew;
serviceConfig.IsolationLevel = TransactionIsolationLevel.ReadCommitted;
txAdapter.Enter(serviceConfig);
Expect.Call(txAdapter.IsInTransaction).Return(true);
txAdapter.SetAbort();
Expect.Call(txAdapter.Leave()).Return(TransactionStatus.Aborted);
// innter tx aborted
//ProcessCommit - status.GlobalRollbackOnly check
Expect.Call(txAdapter.MyTransactionVote).Return(TransactionVote.Commit);
//DoCommit - status.GlobalRollbackOnly check
Expect.Call(txAdapter.MyTransactionVote).Return(TransactionVote.Commit);
Expect.Call(txAdapter.IsInTransaction).Return(true);
//DoCommit - check to call SetComplete or SetAbort
Expect.Call(txAdapter.MyTransactionVote).Return(TransactionVote.Commit);
txAdapter.SetComplete();
Expect.Call(txAdapter.Leave()).Return(TransactionStatus.Commited);
}
#endregion
mocks.ReplayAll();
A.CallTo(() => txAdapter.MyTransactionVote).Returns(TransactionVote.Commit).NumberOfTimes(3);
ServiceDomainPlatformTransactionManager tm = new ServiceDomainPlatformTransactionManager(txAdapter);
tm.TransactionSynchronization = TransactionSynchronizationState.Always;
@@ -190,10 +127,22 @@ namespace Spring.Data.Core
TransactionTemplate tt = new TransactionTemplate(tm);
tt.PropagationBehavior = TransactionPropagation.RequiresNew;
tt.Execute(new PropagationRequiresNewWithExistingTransactionCallbackSD(tt));
mocks.VerifyAll();
SimpleServiceConfig serviceConfig = new SimpleServiceConfig();
ConfigureServiceConfig(serviceConfig, false);
serviceConfig.TransactionOption = TransactionOption.RequiresNew;
serviceConfig.IsolationLevel = TransactionIsolationLevel.ReadCommitted;
A.CallTo(() => txAdapter.Enter(serviceConfig)).MustHaveHappened();
ConfigureServiceConfig(serviceConfig, false);
serviceConfig.TransactionOption = TransactionOption.RequiresNew;
serviceConfig.IsolationLevel = TransactionIsolationLevel.ReadCommitted;
A.CallTo(() => txAdapter.Enter(serviceConfig)).MustHaveHappened();
A.CallTo(() => txAdapter.SetAbort()).MustHaveHappenedOnceExactly();
A.CallTo(() => txAdapter.SetComplete()).MustHaveHappenedOnceExactly();
}
#region Helper Methods
private SimpleServiceConfig ConfigureServiceConfig(SimpleServiceConfig serviceConfig, bool standardIsolationAndProp)
{
serviceConfig.TransactionDescription = null;
@@ -206,14 +155,11 @@ namespace Spring.Data.Core
serviceConfig.TransactionOption = TransactionOption.Required;
serviceConfig.IsolationLevel = TransactionIsolationLevel.ReadCommitted;
}
return serviceConfig;
}
#endregion
#region Supporting class for TransactionRollback test
internal class TransactionRollbackTxCallback : ITransactionCallback
{
private Exception exception;
@@ -232,9 +178,6 @@ namespace Spring.Data.Core
}
}
#endregion
#region Supporting class for PropagationRequiresNewWithExistingTransactionCallback test
internal class PropagationRequiresNewWithExistingTransactionCallbackSD : ITransactionCallback
{
private TransactionTemplate tt;
@@ -264,12 +207,8 @@ namespace Spring.Data.Core
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive);
status.SetRollbackOnly();
return null;
return null;
}
}
#endregion
}
}
}

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
* Copyright © 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,15 +18,13 @@
#endregion
#region Imports
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Transaction;
using Spring.Transaction.Support;
#endregion
namespace Spring.Data.Core
{
/// <summary>
@@ -37,13 +35,6 @@ namespace Spring.Data.Core
[TestFixture]
public class TxScopeTransactionManagerIntegrationTests
{
private MockRepository mocks;
[SetUp]
public void Setup()
{
mocks = new MockRepository();
}
[TearDown]
public void TearDown()
{
@@ -53,7 +44,6 @@ namespace Spring.Data.Core
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
Assert.AreEqual(System.Data.IsolationLevel.Unspecified, TransactionSynchronizationManager.CurrentTransactionIsolationLevel);
Assert.IsFalse(TransactionSynchronizationManager.ActualTransactionActive);
}
[Test]
@@ -80,7 +70,7 @@ namespace Spring.Data.Core
{
Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive);
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
return null;
}
@@ -97,12 +87,11 @@ namespace Spring.Data.Core
public object TransactionInformationTxDelegate(ITransactionStatus status)
{
Assert.AreEqual(System.Transactions.IsolationLevel.ReadUncommitted,
System.Transactions.Transaction.Current.IsolationLevel);
System.Transactions.Transaction.Current.IsolationLevel);
Assert.AreEqual(System.Data.IsolationLevel.ReadUncommitted,
TransactionSynchronizationManager.CurrentTransactionIsolationLevel);
TransactionSynchronizationManager.CurrentTransactionIsolationLevel);
return null;
}
@@ -110,14 +99,7 @@ namespace Spring.Data.Core
[Test]
public void Rollback()
{
ITransactionSynchronization sync =
(ITransactionSynchronization) mocks.DynamicMock(typeof (ITransactionSynchronization));
sync.BeforeCompletion();
LastCall.On(sync).Repeat.Once();
sync.AfterCompletion(TransactionSynchronizationStatus.Rolledback);
LastCall.On(sync).Repeat.Once();
mocks.ReplayAll();
ITransactionSynchronization sync = A.Fake<ITransactionSynchronization>();
TxScopeTransactionManager tm = new TxScopeTransactionManager();
tm.TransactionSynchronization = TransactionSynchronizationState.Always;
@@ -130,20 +112,18 @@ namespace Spring.Data.Core
Assert.IsNull(TransactionSynchronizationManager.CurrentTransactionName);
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
tt.Execute(status =>
{
Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive);
TransactionSynchronizationManager.RegisterSynchronization(sync);
Assert.AreEqual("txName", TransactionSynchronizationManager.CurrentTransactionName);
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
status.SetRollbackOnly();
return null;
}
{
Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive);
TransactionSynchronizationManager.RegisterSynchronization(sync);
Assert.AreEqual("txName", TransactionSynchronizationManager.CurrentTransactionName);
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
status.SetRollbackOnly();
return null;
}
);
mocks.VerifyAll();
A.CallTo(() => sync.BeforeCompletion()).MustHaveHappenedOnceExactly();
A.CallTo(() => sync.AfterCompletion(TransactionSynchronizationStatus.Rolledback)).MustHaveHappenedOnceExactly();
}
}
}
}

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <20> 2002-2011 the original author or authors.
* Copyright <20> 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,91 +18,68 @@
#endregion
#region Imports
using System;
using System.Transactions;
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Data.Support;
using Spring.Transaction;
using Spring.Transaction.Support;
#endregion
namespace Spring.Data.Core
{
/// <summary>
/// This calss contains tests for
/// This calss contains tests for
/// </summary>
/// <author>Mark Pollack</author>
[TestFixture]
public class TxScopeTransactionManagerTests
{
private MockRepository mocks;
[SetUp]
public void Setup()
{
mocks = new MockRepository();
}
[Test]
public void TransactionCommit()
{
ITransactionScopeAdapter txAdapter = (ITransactionScopeAdapter) mocks.CreateMock(typeof(ITransactionScopeAdapter));
ITransactionScopeAdapter txAdapter = A.Fake<ITransactionScopeAdapter>();
A.CallTo(() => txAdapter.IsExistingTransaction).Returns(false);
using (mocks.Ordered())
{
Expect.Call(txAdapter.IsExistingTransaction).Return(false);
TransactionOptions txOptions = new TransactionOptions();
txOptions.IsolationLevel = IsolationLevel.ReadCommitted;
txAdapter.CreateTransactionScope(TransactionScopeOption.Required, txOptions, EnterpriseServicesInteropOption.None);
Expect.Call(txAdapter.RollbackOnly).Return(false);
txAdapter.Complete();
txAdapter.Dispose();
}
mocks.ReplayAll();
A.CallTo(() => txAdapter.RollbackOnly).Returns(false);
TxScopeTransactionManager tm = new TxScopeTransactionManager(txAdapter);
tm.TransactionSynchronization = TransactionSynchronizationState.Always;
TransactionTemplate tt = new TransactionTemplate(tm);
tt.Execute(status =>
{
Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive);
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
return null;
});
{
Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive);
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
return null;
});
Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive);
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
mocks.VerifyAll();
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
TransactionOptions txOptions = new TransactionOptions();
txOptions.IsolationLevel = IsolationLevel.ReadCommitted;
txAdapter.CreateTransactionScope(TransactionScopeOption.Required, txOptions, EnterpriseServicesInteropOption.None);
txAdapter.Complete();
txAdapter.Dispose();
}
[Test]
public void TransactionRollback()
{
ITransactionScopeAdapter txAdapter = (ITransactionScopeAdapter)mocks.CreateMock(typeof(ITransactionScopeAdapter));
ITransactionScopeAdapter txAdapter = A.Fake<ITransactionScopeAdapter>();
using (mocks.Ordered())
{
Expect.Call(txAdapter.IsExistingTransaction).Return(false);
TransactionOptions txOptions = new TransactionOptions();
txOptions.IsolationLevel = IsolationLevel.ReadCommitted;
txAdapter.CreateTransactionScope(TransactionScopeOption.Required, txOptions, EnterpriseServicesInteropOption.None);
txAdapter.Dispose();
}
mocks.ReplayAll();
A.CallTo(() => txAdapter.IsExistingTransaction).Returns(false);
TransactionOptions txOptions = new TransactionOptions();
txOptions.IsolationLevel = IsolationLevel.ReadCommitted;
TxScopeTransactionManager tm = new TxScopeTransactionManager(txAdapter);
tm.TransactionSynchronization = TransactionSynchronizationState.Always;
TransactionTemplate tt = new TransactionTemplate(tm);
Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");
@@ -111,13 +88,13 @@ namespace Spring.Data.Core
try
{
tt.Execute(status =>
{
Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive);
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
Assert.IsTrue(status.IsNewTransaction, "Is new transaction");
if (ex != null) throw ex;
return null;
});
{
Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive);
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
Assert.IsTrue(status.IsNewTransaction, "Is new transaction");
if (ex != null) throw ex;
return null;
});
Assert.Fail("Should have thrown exception");
}
catch (ArgumentException e)
@@ -126,36 +103,24 @@ namespace Spring.Data.Core
}
Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");
mocks.VerifyAll();
A.CallTo(() => txAdapter.CreateTransactionScope(TransactionScopeOption.Required, txOptions, EnterpriseServicesInteropOption.None)).MustHaveHappenedOnceExactly();
A.CallTo(() => txAdapter.Dispose()).MustHaveHappenedOnceExactly();
}
[Test]
public void PropagationRequiresNewWithExistingTransaction()
{
ITransactionScopeAdapter txAdapter = A.Fake<ITransactionScopeAdapter>();
A.CallTo(() => txAdapter.IsExistingTransaction).Returns(false).Once();
ITransactionScopeAdapter txAdapter = (ITransactionScopeAdapter)mocks.CreateMock(typeof(ITransactionScopeAdapter));
TransactionOptions txOptions = new TransactionOptions();
txOptions.IsolationLevel = IsolationLevel.ReadCommitted;
using (mocks.Ordered())
{
Expect.Call(txAdapter.IsExistingTransaction).Return(false);
TransactionOptions txOptions = new TransactionOptions();
txOptions.IsolationLevel = IsolationLevel.ReadCommitted;
txAdapter.CreateTransactionScope(TransactionScopeOption.RequiresNew, txOptions, EnterpriseServicesInteropOption.None);
//inner tx actions
A.CallTo(() => txAdapter.IsExistingTransaction).Returns(true).Once();
//end inner tx actions
//inner tx actions
Expect.Call(txAdapter.IsExistingTransaction).Return(true);
txAdapter.CreateTransactionScope(TransactionScopeOption.RequiresNew, txOptions, EnterpriseServicesInteropOption.None);
txAdapter.Dispose();
//end inner tx actions
Expect.Call(txAdapter.RollbackOnly).Return(false);
txAdapter.Complete();
txAdapter.Dispose();
}
mocks.ReplayAll();
A.CallTo(() => txAdapter.RollbackOnly).Returns(false);
TxScopeTransactionManager tm = new TxScopeTransactionManager(txAdapter);
tm.TransactionSynchronization = TransactionSynchronizationState.Always;
@@ -163,30 +128,32 @@ namespace Spring.Data.Core
TransactionTemplate tt = new TransactionTemplate(tm);
tt.PropagationBehavior = TransactionPropagation.RequiresNew;
tt.Execute(status =>
{
Assert.IsTrue(status.IsNewTransaction, "Is new transaction");
Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive, "Synchronization active");
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive);
{
Assert.IsTrue(status.IsNewTransaction, "Is new transaction");
Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive, "Synchronization active");
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive);
tt.Execute(status2 =>
{
Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive, "Synchronization active");
Assert.IsTrue(status2.IsNewTransaction, "Is new transaction");
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive);
status2.SetRollbackOnly();
return null;
});
tt.Execute(status2 =>
{
Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive, "Synchronization active");
Assert.IsTrue(status2.IsNewTransaction, "Is new transaction");
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive);
status2.SetRollbackOnly();
return null;
});
Assert.IsTrue(status.IsNewTransaction, "Is new transaction");
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive);
return null;
});
Assert.IsTrue(status.IsNewTransaction, "Is new transaction");
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive);
return null;
});
mocks.VerifyAll();
A.CallTo(() => txAdapter.CreateTransactionScope(TransactionScopeOption.RequiresNew, txOptions, EnterpriseServicesInteropOption.None)).MustHaveHappenedTwiceExactly();
A.CallTo(() => txAdapter.Dispose()).MustHaveHappenedTwiceExactly();
A.CallTo(() => txAdapter.Complete()).MustHaveHappenedOnceExactly();
}
}
}

View File

@@ -19,7 +19,9 @@
#endregion
using System.Data;
using Rhino.Mocks;
using FakeItEasy;
using Spring.Data.Common;
namespace Spring.Data.Objects
@@ -34,26 +36,26 @@ namespace Spring.Data.Objects
public void SetUpMocks()
{
provider = MockRepository.GenerateMock<IDbProvider>();
IDbConnection connection = MockRepository.GenerateMock<IDbConnection>();
provider = A.Fake<IDbProvider>();
IDbConnection connection = A.Fake<IDbConnection>();
provider.Stub(x => x.CreateConnection()).Return(connection).Repeat.Once();
A.CallTo(() => provider.CreateConnection()).Returns(connection).Once();
// Creating a query (setting DbProvider property)
// will call new DbParameters(IDbProvider), which is a real pain to mock.
// to store the declared parameters.
command = MockRepository.GenerateMock<IDbCommand>();
command = A.Fake<IDbCommand>();
//This IDbCommand is used as a container for the underlying parameter collection.
provider.Stub(x => x.CreateCommand()).Return(command).Repeat.Once();
A.CallTo(() => provider.CreateCommand()).Returns(command).Once();
//Create a real instance of IDbParameters to stored the declared parameters
IDbProvider realDbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient");
IDbParameters dbParameters = new DbParameters(realDbProvider);
//Pass real instance into mock instance.
command.Stub(x => x.Parameters).Return(dbParameters.DataParameterCollection).Repeat.Once();
provider.Stub(x => x.CreateCommand()).Return(command).Repeat.Once();
A.CallTo(() => command.Parameters).Returns(dbParameters.DataParameterCollection).Once();
A.CallTo(() => provider.CreateCommand()).Returns(command).Once();
// done with init of DbParameters mock/stubbing
}

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
* Copyright © 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,14 +21,14 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
*
* Copyright © 2002-2011 the original author or authors.
*
* 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.
@@ -44,9 +44,9 @@ using System.Collections;
using System.Data;
using System.Data.SqlClient;
using NUnit.Framework;
using FakeItEasy;
using Rhino.Mocks;
using NUnit.Framework;
using Spring.Dao;
using Spring.Data.Common;
@@ -75,12 +75,11 @@ namespace Spring.Data.Objects
[Test]
public void MappingAdoQueryWithContextWithoutParams()
{
IDataReader reader = MockRepository.GenerateMock<IDataReader>();
reader.Stub(x => x.Read()).Return(true).Repeat.Once();
reader.Stub(x => x.GetInt32(0)).Return(1).Repeat.Once();
reader.Stub(x => x.Read()).Return(false).Repeat.Once();
IDataReader reader = A.Fake<IDataReader>();
A.CallTo(() => reader.Read()).Returns(true).Once().Then.Returns(false);
A.CallTo(() => reader.GetInt32(0)).Returns(1).Once();
command.Stub(x => x.ExecuteReader()).Return(reader);
A.CallTo(() => command.ExecuteReader()).Returns(reader);
IntMappingQueryWithContext queryWithNoContext = new IntMappingQueryWithContext(provider);
queryWithNoContext.Compile();
@@ -95,13 +94,10 @@ namespace Spring.Data.Objects
[Test]
public void QueryWithoutEnoughParams()
{
SqlParameter sqlParameter1 = new SqlParameter();
command.Stub(x => x.CreateParameter()).Return(sqlParameter1).Repeat.Once();
provider.Stub(x => x.CreateParameterNameForCollection(COLUMN_NAMES[0])).Return("@" + COLUMN_NAMES[0]).Repeat.Once();
A.CallTo(() => command.CreateParameter()).ReturnsLazily(() => new SqlParameter());
SqlParameter sqlParameter2 = new SqlParameter();
command.Stub(x => x.CreateParameter()).Return(sqlParameter2);
provider.Stub(x => x.CreateParameterNameForCollection(COLUMN_NAMES[1])).Return("@" + COLUMN_NAMES[1]);
A.CallTo(() => provider.CreateParameterNameForCollection(COLUMN_NAMES[0])).Returns("@" + COLUMN_NAMES[0]).Once();
A.CallTo(() => provider.CreateParameterNameForCollection(COLUMN_NAMES[1])).Returns("@" + COLUMN_NAMES[1]);
IntMappingAdoQuery query = new IntMappingAdoQuery();
query.DbProvider = provider;

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
* Copyright © 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,14 +21,14 @@
#region License
/*
* Copyright <EFBFBD> 2002-2011 the original author or authors.
*
* Copyright © 2002-2011 the original author or authors.
*
* 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.
@@ -38,19 +38,15 @@
#endregion
#region Imports
using System.Data;
using System.Data.SqlClient;
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Data.Common;
#endregion
namespace Spring.Data.Objects
{
/// <summary>
@@ -70,15 +66,14 @@ namespace Spring.Data.Objects
public void NullArg()
{
SqlParameter sqlParameter1 = new SqlParameter();
command.Stub(x => x.CreateParameter()).Return(sqlParameter1);
provider.Stub(x => x.CreateParameterNameForCollection("ptest")).Return("@ptest");
A.CallTo(() => command.CreateParameter()).Returns(sqlParameter1);
A.CallTo(() => provider.CreateParameterNameForCollection("ptest")).Returns("@ptest");
//Create a real instance of IDbParameters to store the executable parameters
//IDbProvider realDbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient");
//IDbParameters dbParameters = new DbParameters(realDbProvider);
IDataParameterCollection dbParamCollection = new SqlCommand().Parameters;
//provide the same instance to another call to extract output params
command.Stub(x => x.Parameters).Return(dbParamCollection).Repeat.Twice();
A.CallTo(() => command.Parameters).ReturnsLazily(() => new SqlCommand().Parameters).Twice();
NullArg na = new NullArg(provider);
na.Execute(null);

View File

@@ -10,10 +10,11 @@
<ProjectReference Include="..\Spring.Core.Tests\Spring.Core.Tests.2010.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="FakeItEasy" Version="$(FakeItEasyVersion)" />
<PackageReference Include="FakeItEasy.Analyzer" Version="$(FakeItEasyVersion)" PrivateAssets="All" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="$(MicrosoftTestSDKVersion)" />
<PackageReference Include="NUnit" Version="$(NUnitVersion)" />
<PackageReference Include="NUnit3TestAdapter" Version="$(NUnitTestAdapterVersion)" />
<PackageReference Include="RhinoMocks" Version="$(RhinoMocksVersion)" />
</ItemGroup>
<ItemGroup>
<Reference Include="System.configuration" />

View File

@@ -1,7 +1,7 @@
#region License
/*
* Copyright <20> 2002-2011 the original author or authors.
* Copyright <20> 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,17 +18,16 @@
#endregion
#region Imports
using System;
using System.Reflection;
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Data;
using Spring.Objects;
#endregion
namespace Spring.Transaction.Interceptor
{
/// <summary>
@@ -38,44 +37,31 @@ namespace Spring.Transaction.Interceptor
[TestFixture]
public abstract class AbstractTransactionAspectTests
{
private MockRepository mocks;
[SetUp]
public void Setup()
{
mocks = new MockRepository();
}
[Test]
public void CopyAttributes()
{
IPlatformTransactionManager ptm = PlatformTxManagerForNewTransaction();
IPlatformTransactionManager ptm = A.Fake<IPlatformTransactionManager>();
AttributesTransactionAttributeSource tas = new AttributesTransactionAttributeSource();
TestObjectMgr to = new TestObjectMgr();
ITestObjectMgr ito = (ITestObjectMgr)Advised(to, ptm, tas);
ITestObjectMgr ito = (ITestObjectMgr) Advised(to, ptm, tas);
ito.DeleteTwoTestObjects("foo", "bar");
}
[Test]
public void CannotCommitTransaction()
{
ITransactionAttribute txatt = new DefaultTransactionAttribute();
MethodInfo m = typeof (ITestObject).GetMethod("GetDescription");
MethodInfo m = typeof(ITestObject).GetMethod("GetDescription");
MethodMapTransactionAttributeSource tas = new MethodMapTransactionAttributeSource();
tas.AddTransactionalMethod(m, txatt);
IPlatformTransactionManager ptm = A.Fake<IPlatformTransactionManager>();
ITransactionStatus status = A.Fake<ITransactionStatus>();
IPlatformTransactionManager ptm = PlatformTxManagerForNewTransaction();
ITransactionStatus status = TransactionStatusForNewTransaction();
Expect.On(ptm).Call(ptm.GetTransaction(txatt)).Return(status);
A.CallTo(() => ptm.GetTransaction(txatt)).Returns(status);
UnexpectedRollbackException ex = new UnexpectedRollbackException("foobar", null);
ptm.Commit(status);
LastCall.On(ptm).Throw(ex);
mocks.ReplayAll();
A.CallTo(() => ptm.Commit(status)).Throws(ex);
TestObject to = new TestObject();
ITestObject ito = (ITestObject) Advised(to, ptm, tas);
@@ -84,20 +70,11 @@ namespace Spring.Transaction.Interceptor
{
ito.GetDescription();
Assert.Fail("Shouldn't have succeeded");
} catch (UnexpectedRollbackException thrown)
}
catch (UnexpectedRollbackException thrown)
{
Assert.IsTrue(thrown == ex);
}
mocks.VerifyAll();
}
private IPlatformTransactionManager PlatformTxManagerForNewTransaction()
{
return (IPlatformTransactionManager) mocks.DynamicMock(typeof(IPlatformTransactionManager));
}
@@ -110,25 +87,19 @@ namespace Spring.Transaction.Interceptor
MethodMapTransactionAttributeSource tas = new MethodMapTransactionAttributeSource();
tas.AddTransactionalMethod(m, txatt);
ITransactionStatus status = TransactionStatusForNewTransaction();
ITransactionStatus status = A.Fake<ITransactionStatus>();
IPlatformTransactionManager ptm = PlatformTxManagerForNewTransaction();
IPlatformTransactionManager ptm = A.Fake<IPlatformTransactionManager>();
Expect.Call(ptm.GetTransaction(txatt)).Return(status).Repeat.Once();
ptm.Commit(status);
LastCall.On(ptm).Repeat.Once();
A.CallTo(() => ptm.GetTransaction(txatt)).Returns(status).Once();
mocks.ReplayAll();
RollbackTestObject to = new RollbackTestObject();
ITestObject ito = (ITestObject) Advised(to, ptm, tas);
Assert.AreEqual("test description", ito.GetDescription());
mocks.VerifyAll();
A.CallTo(() => ptm.Commit(status)).MustHaveHappenedOnceExactly();
}
[Test]
@@ -160,37 +131,21 @@ namespace Spring.Transaction.Interceptor
ITransactionAttribute txatt = new ConfigurableTransactionAttribute(shouldRollback);
MethodInfo mi = typeof (ITestObject).GetMethod("Exceptional");
MethodInfo mi = typeof(ITestObject).GetMethod("Exceptional");
MethodMapTransactionAttributeSource tas = new MethodMapTransactionAttributeSource();
tas.AddTransactionalMethod(mi, txatt);
ITransactionStatus status = TransactionStatusForNewTransaction();
ITransactionStatus status = A.Fake<ITransactionStatus>();
IPlatformTransactionManager ptm =
(IPlatformTransactionManager) mocks.DynamicMock(typeof (IPlatformTransactionManager));
IPlatformTransactionManager ptm = A.Fake<IPlatformTransactionManager>();
A.CallTo(() => ptm.GetTransaction(txatt)).Returns(status);
Expect.On(ptm).Call(ptm.GetTransaction(txatt)).Return(status);
if (shouldRollback)
{
ptm.Rollback(status);
}
else
{
ptm.Commit(status);
}
TransactionSystemException tex = new TransactionSystemException("system exception");
if (rollbackException)
{
LastCall.On(ptm).Throw(tex).Repeat.Once();
A.CallTo(() => ptm.Rollback(A<ITransactionStatus>._)).Throws(tex);
}
else
{
LastCall.On(ptm).Repeat.Once();
}
mocks.ReplayAll();
TestObject to = new TestObject();
ITestObject ito = (ITestObject) Advised(to, ptm, tas);
@@ -199,9 +154,10 @@ namespace Spring.Transaction.Interceptor
{
ito.Exceptional(exception);
Assert.Fail("Should have thrown exception");
} catch (Exception e)
}
catch (Exception e)
{
if (rollbackException)
if (rollbackException && shouldRollback)
{
Assert.AreEqual(tex, e);
}
@@ -211,17 +167,18 @@ namespace Spring.Transaction.Interceptor
}
}
mocks.VerifyAll();
}
private ITransactionStatus TransactionStatusForNewTransaction()
{
return (ITransactionStatus) mocks.DynamicMock(typeof (ITransactionStatus));
if (shouldRollback)
{
A.CallTo(() => ptm.Rollback(status)).MustHaveHappenedOnceExactly();
}
else
{
A.CallTo(() => ptm.Commit(status)).MustHaveHappenedOnceExactly();
}
}
protected abstract object Advised(object target, IPlatformTransactionManager ptm,
ITransactionAttributeSource tas);
ITransactionAttributeSource tas);
}
internal class RollbackTestObject : TestObject
@@ -232,12 +189,12 @@ namespace Spring.Transaction.Interceptor
txStatus.SetRollbackOnly();
return "test description";
}
}
internal class ConfigurableTransactionAttribute : DefaultTransactionAttribute
{
private bool shouldRollback;
public ConfigurableTransactionAttribute(bool shouldRollback)
{
this.shouldRollback = shouldRollback;

View File

@@ -1,5 +1,6 @@
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
namespace Spring.Transaction.Support
{
@@ -144,7 +145,7 @@ namespace Spring.Transaction.Support
MockTxnDefinition def = new MockTxnDefinition();
def.PropagationBehavior = TransactionPropagation.Nested;
def.ReadOnly = false;
ISavepointManager saveMgr = MockRepository.GenerateMock<ISavepointManager>();
ISavepointManager saveMgr = A.Fake<ISavepointManager>();
_mockTxnMgr.SetTransaction(saveMgr);
_mockTxnMgr.Savepoints = true;
_mockTxnMgr.NestedTransactionsAllowed = true;

View File

@@ -1,5 +1,6 @@
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
namespace Spring.Transaction.Support
{
@@ -9,7 +10,7 @@ namespace Spring.Transaction.Support
[Test]
public void DefaultConstructorTests()
{
ISmartTransactionObject txn = MockRepository.GenerateMock<ISmartTransactionObject>();
ISmartTransactionObject txn = A.Fake<ISmartTransactionObject>();
DefaultTransactionStatus stat = new DefaultTransactionStatus(txn, true, false, false, true, new object());
Assert.IsNotNull(stat.Transaction);
@@ -20,14 +21,12 @@ namespace Spring.Transaction.Support
Assert.IsTrue(! stat.RollbackOnly);
stat.SetRollbackOnly();
Assert.IsTrue(stat.RollbackOnly);
txn.AssertWasCalled(x => x.RollbackOnly, constraints => constraints.Repeat.Once());
}
[Test]
public void CreateSavepointException()
{
ISmartTransactionObject transaction = MockRepository.GenerateMock<ISmartTransactionObject>();
ISmartTransactionObject transaction = A.Fake<ISmartTransactionObject>();
DefaultTransactionStatus stat = new DefaultTransactionStatus(transaction, true, false, false, true, new object());
Assert.Throws<NestedTransactionNotSupportedException>(() => stat.CreateSavepoint("mySavePoint"));
}
@@ -35,7 +34,7 @@ namespace Spring.Transaction.Support
[Test]
public void RollbackSavepointException()
{
ISmartTransactionObject transaction = MockRepository.GenerateMock<ISmartTransactionObject>();
ISmartTransactionObject transaction = A.Fake<ISmartTransactionObject>();
DefaultTransactionStatus stat = new DefaultTransactionStatus(transaction, true, false, false, true, new object());
Assert.Throws<NestedTransactionNotSupportedException>(() => stat.RollbackToSavepoint(null));
}
@@ -43,7 +42,7 @@ namespace Spring.Transaction.Support
[Test]
public void ReleaseSavepointException()
{
ISmartTransactionObject transaction = MockRepository.GenerateMock<ISmartTransactionObject>();
ISmartTransactionObject transaction = A.Fake<ISmartTransactionObject>();
DefaultTransactionStatus stat = new DefaultTransactionStatus(transaction, true, false, false, true, new object());
Assert.Throws<NestedTransactionNotSupportedException>(() => stat.ReleaseSavepoint(null));
}
@@ -51,7 +50,7 @@ namespace Spring.Transaction.Support
[Test]
public void CreateSaveAndHoldValidSavepoint()
{
ISavepointManager saveMgr = MockRepository.GenerateMock<ISavepointManager>();
ISavepointManager saveMgr = A.Fake<ISavepointManager>();
DefaultTransactionStatus status = new DefaultTransactionStatus(saveMgr, true, false, false, true, new object());
status.CreateAndHoldSavepoint("savepoint");
Assert.IsTrue(status.HasSavepoint);
@@ -61,7 +60,7 @@ namespace Spring.Transaction.Support
[Test]
public void RollbackHeldSavepointException()
{
ISmartTransactionObject transaction = MockRepository.GenerateMock<ISmartTransactionObject>();
ISmartTransactionObject transaction = A.Fake<ISmartTransactionObject>();
DefaultTransactionStatus stat = new DefaultTransactionStatus(transaction, true, false, false, true, new object());
Assert.Throws<TransactionUsageException>(() => stat.RollbackToHeldSavepoint());
}
@@ -69,7 +68,7 @@ namespace Spring.Transaction.Support
[Test]
public void RollbackHeldSavepointSuccess()
{
ISavepointManager saveMgr = MockRepository.GenerateMock<ISavepointManager>();
ISavepointManager saveMgr = A.Fake<ISavepointManager>();
string savepoint = "savepoint";
DefaultTransactionStatus status = new DefaultTransactionStatus(saveMgr, true, false, false, true, new object());
status.CreateAndHoldSavepoint(savepoint);
@@ -77,13 +76,13 @@ namespace Spring.Transaction.Support
Assert.AreEqual(savepoint, status.Savepoint);
status.RollbackToHeldSavepoint();
saveMgr.AssertWasCalled(x => x.RollbackToSavepoint(savepoint));
A.CallTo(() => saveMgr.RollbackToSavepoint(savepoint)).MustHaveHappened();
}
[Test]
public void ReleaseHeldSavepointException()
{
ISmartTransactionObject transaction = MockRepository.GenerateMock<ISmartTransactionObject>();
ISmartTransactionObject transaction = A.Fake<ISmartTransactionObject>();
DefaultTransactionStatus stat = new DefaultTransactionStatus(transaction, true, false, false, true, new object());
Assert.Throws<TransactionUsageException>(() => stat.ReleaseHeldSavepoint());
}
@@ -91,7 +90,7 @@ namespace Spring.Transaction.Support
[Test]
public void ReleaseHeldSavepointSuccess()
{
ISavepointManager saveMgr = MockRepository.GenerateMock<ISavepointManager>();
ISavepointManager saveMgr = A.Fake<ISavepointManager>();
string savepoint = "savepoint";
DefaultTransactionStatus status = new DefaultTransactionStatus(saveMgr, true, false, false, true, new object());
status.CreateAndHoldSavepoint(savepoint);
@@ -99,8 +98,8 @@ namespace Spring.Transaction.Support
Assert.AreEqual(savepoint, status.Savepoint);
status.ReleaseHeldSavepoint();
saveMgr.AssertWasCalled(x => x.CreateSavepoint(savepoint));
saveMgr.AssertWasCalled(x => x.ReleaseSavepoint(savepoint));
A.CallTo(() => saveMgr.CreateSavepoint(savepoint)).MustHaveHappened();
A.CallTo(() => saveMgr.ReleaseSavepoint(savepoint)).MustHaveHappened();
}
}
}

View File

@@ -1,9 +1,9 @@
using System;
using System.Collections;
using NUnit.Framework;
using FakeItEasy;
using Rhino.Mocks;
using NUnit.Framework;
using Spring.Core;
using Spring.Util;
@@ -54,7 +54,7 @@ namespace Spring.Transaction.Support
[Test]
public void RegisterSyncsInvalid()
{
Assert.Throws<InvalidOperationException>(() => TransactionSynchronizationManager.RegisterSynchronization(MockRepository.GenerateMock<ITransactionSynchronization>()));
Assert.Throws<InvalidOperationException>(() => TransactionSynchronizationManager.RegisterSynchronization(A.Fake<ITransactionSynchronization>()));
}
[Test]
@@ -63,7 +63,7 @@ namespace Spring.Transaction.Support
TransactionSynchronizationManager.InitSynchronization();
IList syncs = TransactionSynchronizationManager.Synchronizations;
Assert.AreEqual(0, syncs.Count);
TransactionSynchronizationManager.RegisterSynchronization(MockRepository.GenerateMock<ITransactionSynchronization>());
TransactionSynchronizationManager.RegisterSynchronization(A.Fake<ITransactionSynchronization>());
syncs = TransactionSynchronizationManager.Synchronizations;
Assert.AreEqual(1, syncs.Count);
TransactionSynchronizationManager.ClearSynchronization();

View File

@@ -1,6 +1,8 @@
using System;
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
namespace Spring.Transaction.Support
{
@@ -18,59 +20,60 @@ namespace Spring.Transaction.Support
public void TxnMgr()
{
TransactionTemplate temp = new TransactionTemplate();
temp.PlatformTransactionManager = MockRepository.GenerateMock<IPlatformTransactionManager>();
temp.PlatformTransactionManager = A.Fake<IPlatformTransactionManager>();
temp.AfterPropertiesSet();
}
[Test]
public void ExecuteException()
{
IPlatformTransactionManager mock = MockRepository.GenerateMock<IPlatformTransactionManager>();
IPlatformTransactionManager mock = A.Fake<IPlatformTransactionManager>();
TransactionTemplate temp = new TransactionTemplate(mock);
try
{
temp.Execute(new TransactionDelegate(DummyExceptionMethod));
temp.Execute(DummyExceptionMethod);
}
catch
{
}
mock.AssertWasCalled(x => x.GetTransaction(Arg<ITransactionDefinition>.Is.Anything), constraints => constraints.Repeat.Once());
mock.AssertWasCalled(x => x.Rollback(Arg<ITransactionStatus>.Is.Anything), constraints => constraints.Repeat.Once());
A.CallTo(() => mock.GetTransaction(A<ITransactionDefinition>._)).MustHaveHappenedOnceExactly();
A.CallTo(() => mock.Rollback(A<ITransactionStatus>._)).MustHaveHappenedOnceExactly();
}
[Test]
public void ExecuteExceptionRollbackException()
{
IPlatformTransactionManager mock = MockRepository.GenerateMock<IPlatformTransactionManager>();
mock.Stub(x => x.Rollback(Arg<ITransactionStatus>.Is.Anything)).Throw(new Exception("Rollback"));
IPlatformTransactionManager mock = A.Fake<IPlatformTransactionManager>();
A.CallTo(() => mock.Rollback(A<ITransactionStatus>._)).Throws(new Exception("Rollback"));
TransactionTemplate temp = new TransactionTemplate(mock);
try
{
temp.Execute(new TransactionDelegate(DummyExceptionMethod));
temp.Execute(DummyExceptionMethod);
}
catch
{
}
mock.AssertWasCalled(x => x.GetTransaction(Arg<ITransactionDefinition>.Is.Anything), constraints => constraints.Repeat.Once());
mock.AssertWasCalled(x => x.Rollback(Arg<ITransactionStatus>.Is.Anything), constraints => constraints.Repeat.Once());
A.CallTo(() => mock.GetTransaction(A<ITransactionDefinition>._)).MustHaveHappenedOnceExactly();
A.CallTo(() => mock.Rollback(A<ITransactionStatus>._)).MustHaveHappenedOnceExactly();
}
[Test]
public void NullResult()
{
IPlatformTransactionManager mock = MockRepository.GenerateMock<IPlatformTransactionManager>();
IPlatformTransactionManager mock = A.Fake<IPlatformTransactionManager>();
A.CallTo(() => mock.GetTransaction(A<ITransactionDefinition>._)).Returns(null);
TransactionTemplate temp = new TransactionTemplate(mock);
temp.AfterPropertiesSet();
Assert.AreEqual(mock, temp.PlatformTransactionManager);
Assert.IsNull(temp.Execute(new TransactionDelegate(DummyTransactionMethod)));
Assert.IsNull(temp.Execute(DummyTransactionMethod));
mock.AssertWasCalled(x => x.GetTransaction(Arg<ITransactionDefinition>.Is.Anything), constraints => constraints.Repeat.Once());
mock.AssertWasCalled(x => x.Commit(Arg<ITransactionStatus>.Is.Anything), constraints => constraints.Repeat.Once());
A.CallTo(() => mock.GetTransaction(A<ITransactionDefinition>._)).MustHaveHappenedOnceExactly();
A.CallTo(() => mock.Commit(A<ITransactionStatus>._)).MustHaveHappenedOnceExactly();
}
public object DummyTransactionMethod(ITransactionStatus status)

View File

@@ -22,8 +22,10 @@
using System.Collections.Generic;
using Apache.NMS;
using FakeItEasy;
using NUnit.Framework;
using Rhino.Mocks;
using Spring.Context;
using Spring.Context.Support;
using Spring.Messaging.Nms.Core;
@@ -45,23 +47,16 @@ namespace Spring.Messaging.Nms.Config
[TestFixture]
public class NmsNamespaceHandlerTests
{
private static string DEFAULT_CONNECTION_FACTORY = "ConnectionFactory";
private static string EXPLICIT_CONNECTION_FACTORY = "testConnectionFactory";
private IApplicationContext ctx;
private MockRepository mocks;
[SetUp]
public void Setup()
{
// WELLKNOWN
//NamespaceParserRegistry.RegisterParser(typeof(NmsNamespaceParser));
ctx = new XmlApplicationContext(ReadOnlyXmlTestResource.GetFilePath("NmsNamespaceHandlerTests.xml", GetType()));
mocks = new MockRepository();
}
[Test]
@@ -117,37 +112,29 @@ namespace Spring.Messaging.Nms.Config
Assert.IsNull(testObject3.Message);
ITextMessage message1 = mocks.StrictMock<ITextMessage>();
Expect.Call(message1.Text).Return("Test1");
mocks.Replay(message1);
ITextMessage message1 = A.Fake<ITextMessage>();
A.CallTo(() => message1.Text).Returns("Test1");
IMessageListener listener1 = GetListener("listener1");
listener1.OnMessage(message1);
Assert.AreEqual("Test1", testObject1.Name);
mocks.Verify(message1);
ITextMessage message2 = mocks.StrictMock<ITextMessage>();
Expect.Call(message2.Text).Return("Test1");
mocks.Replay(message2);
ITextMessage message2 = A.Fake<ITextMessage>();
A.CallTo(() => message2.Text).Returns("Test1");
IMessageListener listener2 = GetListener("listener2");
listener2.OnMessage(message2);
mocks.Verify(message2);
A.CallTo(() => message2.Text).MustHaveHappened();
ITextMessage message3 = A.Fake<ITextMessage>();
ITextMessage message3 = mocks.StrictMock<ITextMessage>();
mocks.Replay(message3);
//Default naming strategy is to use full type name + # + number
string className = typeof(SimpleMessageListenerContainer).FullName;
string targetName = className + ObjectDefinitionReaderUtils.GENERATED_OBJECT_NAME_SEPARATOR + "0";
IMessageListener listener3 = GetListener(targetName);
listener3.OnMessage(message3);
Assert.AreSame(message3, testObject3.Message);
mocks.Verify(message3);
}
private IMessageListener GetListener(string containerObjectName)

Some files were not shown because too many files have changed in this diff Show More