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>
<target name="clean-obj" description="Clean all 'obj' and 'bin' folders"> <target name="clean-obj" description="Clean all 'obj' and 'bin' folders">
<delete dir="src/Spring/Spring.Aop/obj" failonerror="false"/> <delete>
<delete dir="src/Spring/Spring.Aop/bin" failonerror="false"/> <fileset basedir="src/">
<delete dir="src/Spring/Spring.Core/obj" failonerror="false"/> <include name="**/bin/**/*.*" />
<delete dir="src/Spring/Spring.Core/bin" failonerror="false"/> <include name="**/obj/**/*.*" />
<delete dir="src/Spring/Spring.Data/obj" failonerror="false"/> </fileset>
<delete dir="src/Spring/Spring.Data/bin" failonerror="false"/> </delete>
<delete dir="src/Spring/Spring.Data.NHibernate3/obj" failonerror="false"/> <delete>
<delete dir="src/Spring/Spring.Data.NHibernate3/bin" failonerror="false"/> <fileset basedir="test/">
<delete dir="src/Spring/Spring.Data.NHibernate4/obj" failonerror="false"/> <include name="**/bin/**/*.*" />
<delete dir="src/Spring/Spring.Data.NHibernate4/bin" failonerror="false"/> <include name="**/obj/**/*.*" />
<delete dir="src/Spring/Spring.Services/obj" failonerror="false"/> </fileset>
<delete dir="src/Spring/Spring.Services/bin" failonerror="false"/> </delete>
<delete dir="src/Spring/Spring.Messaging.Nms/obj" failonerror="false"/> <delete>
<delete dir="src/Spring/Spring.Messaging.Nms/bin" failonerror="false"/> <fileset basedir="examples/">
<delete dir="src/Spring/Spring.Messaging.Ems/obj" failonerror="false"/> <include name="**/bin/**/*.*" />
<delete dir="src/Spring/Spring.Messaging.Ems/bin" failonerror="false"/> <include name="**/obj/**/*.*" />
<delete dir="src/Spring/Spring.Messaging/obj" failonerror="false"/> </fileset>
<delete dir="src/Spring/Spring.Messaging/bin" failonerror="false"/> </delete>
<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"/>
</target> </target>
<target name="package" depends="set-package-configuration" description="Build and Package distribution"> <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> <NeutralLanguage>en-US</NeutralLanguage>
<WarningsAsErrors>True</WarningsAsErrors> <WarningsAsErrors>True</WarningsAsErrors>
<RepositoryType>git</RepositoryType> <PublishRepositoryUrl>true</PublishRepositoryUrl>
<RepositoryUrl>https://github.com/spring-projects/spring-net</RepositoryUrl> <EmbedUntrackedSources>true</EmbedUntrackedSources>
<TreatWarningsAsErrors>True</TreatWarningsAsErrors> <TreatWarningsAsErrors>True</TreatWarningsAsErrors>
@@ -46,8 +46,13 @@
<LangVersion>latest</LangVersion> <LangVersion>latest</LangVersion>
</PropertyGroup> </PropertyGroup>
<ItemGroup Condition="'$(SourceLinkEnabled)' != 'false'">
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0-beta-63127-02" PrivateAssets="All"/>
</ItemGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' "> <PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugType>Full</DebugType>
<DefineConstants>DEBUG;TRACE;DEBUG_DYNAMIC;$(DefineConstants)</DefineConstants> <DefineConstants>DEBUG;TRACE;DEBUG_DYNAMIC;$(DefineConstants)</DefineConstants>
</PropertyGroup> </PropertyGroup>

View File

@@ -1,7 +1,7 @@
#region License #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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.

View File

@@ -1,7 +1,7 @@
#region License #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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -41,7 +41,7 @@ namespace Spring.Aop.Framework
/// advice configuration. /// advice configuration.
/// </p> /// </p>
/// <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"/>. /// property on the controlling proxy to <see langword="true"/>.
/// The default value for the <see cref="Spring.Aop.Framework.ProxyConfig.ExposeProxy"/> property /// The default value for the <see cref="Spring.Aop.Framework.ProxyConfig.ExposeProxy"/> property
/// is <see langword="false"/>, for performance reasons. /// is <see langword="false"/>, for performance reasons.
@@ -70,7 +70,7 @@ namespace Spring.Aop.Framework
/// </summary> /// </summary>
private static Stack ProxyStack private static Stack ProxyStack
{ {
get get
{ {
if (tls_ProxyStack == null) if (tls_ProxyStack == null)
{ {
@@ -90,7 +90,7 @@ namespace Spring.Aop.Framework
/// on the controlling proxy has been set to <see langword="true"/>. /// on the controlling proxy has been set to <see langword="true"/>.
/// </p> /// </p>
/// <p> /// <p>
/// The default value for the /// The default value for the
/// <see cref="Spring.Aop.Framework.ProxyConfig.ExposeProxy"/> property /// <see cref="Spring.Aop.Framework.ProxyConfig.ExposeProxy"/> property
/// is <see langword="false"/>, for performance reasons. /// is <see langword="false"/>, for performance reasons.
/// </p> /// </p>
@@ -99,7 +99,7 @@ namespace Spring.Aop.Framework
{ {
get 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> /// <summary>
/// Sets the current proxy by pushing it to the proxy stack. /// Sets the current proxy by pushing it to the proxy stack.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// <p> /// <p>

View File

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

View File

@@ -2,13 +2,13 @@
/* /*
* Copyright © 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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

@@ -1,14 +1,14 @@
#region License #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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * 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 namespace Spring.Objects.Factory.Config
{ {
/// <summary> /// <summary>
/// Various utility methods for .NET style .config files. /// Various utility methods for .NET style .config files.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// <p> /// <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. /// <see cref="System.Collections.Specialized.NameValueCollection"/> objects.
/// </p> /// </p>
/// </remarks> /// </remarks>
@@ -314,7 +314,7 @@ namespace Spring.Objects.Factory.Config
if (typeof(IConfigurationSectionHandler).IsAssignableFrom(handlerType)) if (typeof(IConfigurationSectionHandler).IsAssignableFrom(handlerType))
{ {
IConfigurationSectionHandler handler = (IConfigurationSectionHandler)ObjectUtils.InstantiateType(handlerType); IConfigurationSectionHandler handler = (IConfigurationSectionHandler)ObjectUtils.InstantiateType(handlerType);
return ((IConfigurationSectionHandler)handler).Create(null, null, sectionContent); return handler.Create(null, null, sectionContent);
} }
// NET 2.0 ConfigurationSection // NET 2.0 ConfigurationSection
@@ -362,7 +362,7 @@ namespace Spring.Objects.Factory.Config
handlerType = defaultConfigurationSectionHandlerType; handlerType = defaultConfigurationSectionHandlerType;
} }
} }
if (xmlConfig != null) if (xmlConfig != null)
{ {
XmlAttribute xmlConfigType = xmlConfig.Attributes[ConfigSectionTypeAttribute]; XmlAttribute xmlConfigType = xmlConfig.Attributes[ConfigSectionTypeAttribute];

View File

@@ -1,7 +1,7 @@
#region License #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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.

View File

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

View File

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

View File

@@ -1,7 +1,7 @@
#region License #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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -222,7 +222,7 @@ namespace Spring.Objects.Support
#endregion #endregion
IEventHandlerValue myHandler = method.IsStatic ? IEventHandlerValue myHandler = method.IsStatic ?
(IEventHandlerValue) new StaticEventHandlerValue() : new StaticEventHandlerValue() :
(IEventHandlerValue) new InstanceEventHandlerValue(); (IEventHandlerValue) new InstanceEventHandlerValue();
myHandler.EventName = theEvent.Name; myHandler.EventName = theEvent.Name;
myHandler.MethodName = method.Name; myHandler.MethodName = method.Name;

View File

@@ -1,7 +1,7 @@
#region License #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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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"/>. /// <see cref="Spring.Objects.Factory.Config.MethodInvokingFactoryObject"/>.
/// </p> /// </p>
/// <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.TargetMethod"/> or the
/// <see cref="MethodInvoker.TargetObject"/> and /// <see cref="MethodInvoker.TargetObject"/> and
/// <see cref="MethodInvoker.TargetMethod"/> properties respectively, and /// <see cref="MethodInvoker.TargetMethod"/> properties respectively, and
@@ -58,13 +58,13 @@ namespace Spring.Objects.Support
/// arguments. /// arguments.
/// </p> /// </p>
/// <code language="C#"> /// <code language="C#">
/// public class Foo /// public class Foo
/// { /// {
/// public string ToString(string name, int age, string address) /// public string ToString(string name, int age, string address)
/// { /// {
/// return string.Format("{0}, {1} years old, {2}", name, age, address); /// return string.Format("{0}, {1} years old, {2}", name, age, address);
/// } /// }
/// ///
/// public static void Main() /// public static void Main()
/// { /// {
/// Foo foo = new Foo(); /// 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 // 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; PreparedArguments[namedArgumentsIndex] = argumentValue;
// we've prepped this index position, so mark it as so... // we've prepped this index position, so mark it as so...
argumentNamesToIndexes[argumentName] = THE_ARGUMENT_IS_PREPARED; argumentNamesToIndexes[argumentName] = THE_ARGUMENT_IS_PREPARED;
@@ -420,7 +420,7 @@ namespace Spring.Objects.Support
} }
if (theMethod == null) if (theMethod == null)
{ {
// search for a method with a matching signature... // search for a method with a matching signature...
ComposedCriteria searchCriteria = new ComposedCriteria(); ComposedCriteria searchCriteria = new ComposedCriteria();
searchCriteria.Add(new MethodNameMatchCriteria(genericInfo.GenericMethodName)); searchCriteria.Add(new MethodNameMatchCriteria(genericInfo.GenericMethodName));
searchCriteria.Add(new MethodParametersCountCriteria(ArgumentCount)); searchCriteria.Add(new MethodParametersCountCriteria(ArgumentCount));

View File

@@ -1,7 +1,7 @@
#region License #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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.

View File

@@ -1,14 +1,14 @@
#region License #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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * 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, /// or handling Session lifecycle exceptions. For typical single step actions,
/// there are various convenience methods (Find, Load, SaveOrUpdate, Delete). /// there are various convenience methods (Find, Load, SaveOrUpdate, Delete).
/// </p> /// </p>
/// ///
/// <p>Can be used within a service implementation via direct instantiation /// <p>Can be used within a service implementation via direct instantiation
/// with a ISessionFactory reference, or get prepared in an application context /// with a ISessionFactory reference, or get prepared in an application context
/// and given to services as an object reference. Note: The ISessionFactory should /// 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 /// 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. /// given to the service directly, in the second case to the prepared template.
/// </p> /// </p>
/// ///
/// <p>This class can be considered as a direct alternative to working with the raw /// <p>This class can be considered as a direct alternative to working with the raw
/// Hibernate Session API (through SessionFactoryUtils.Session). /// Hibernate Session API (through SessionFactoryUtils.Session).
/// </p> /// </p>
/// ///
/// <p>LocalSessionFactoryObject is the preferred way of obtaining a reference /// <p>LocalSessionFactoryObject is the preferred way of obtaining a reference
/// to a specific NHibernate ISessionFactory. /// to a specific NHibernate ISessionFactory.
/// </p> /// </p>
@@ -73,8 +73,8 @@ namespace Spring.Data.NHibernate.Generic
#region Fields #region Fields
NHibernate.HibernateTemplate classicHibernateTemplate; NHibernate.HibernateTemplate classicHibernateTemplate;
#endregion #endregion
#region Constructor (s) #region Constructor (s)
@@ -89,25 +89,25 @@ namespace Spring.Data.NHibernate.Generic
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="HibernateTemplate"/> class. /// Initializes a new instance of the <see cref="HibernateTemplate"/> class.
/// </summary> /// </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> /// transactional Session can be found for the current thread</remarks>
/// <param name="sessionFactory">The session factory to create sessions.</param> /// <param name="sessionFactory">The session factory to create sessions.</param>
public HibernateTemplate(ISessionFactory sessionFactory) public HibernateTemplate(ISessionFactory sessionFactory)
{ {
classicHibernateTemplate = new Spring.Data.NHibernate.HibernateTemplate(sessionFactory); classicHibernateTemplate = new Spring.Data.NHibernate.HibernateTemplate(sessionFactory);
AfterPropertiesSet(); AfterPropertiesSet();
} }
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="HibernateTemplate"/> class. /// Initializes a new instance of the <see cref="HibernateTemplate"/> class.
/// </summary> /// </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 /// <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> /// for the current thread.</param>
public HibernateTemplate(ISessionFactory sessionFactory, bool allowCreate) public HibernateTemplate(ISessionFactory sessionFactory, bool allowCreate)
{ {
classicHibernateTemplate = new Spring.Data.NHibernate.HibernateTemplate(sessionFactory, allowCreate); classicHibernateTemplate = new Spring.Data.NHibernate.HibernateTemplate(sessionFactory, allowCreate);
AfterPropertiesSet(); AfterPropertiesSet();
} }
@@ -247,7 +247,7 @@ namespace Spring.Data.NHibernate.Generic
} }
/// <summary> /// <summary>
/// Gets or sets a value indicating whether to /// Gets or sets a value indicating whether to
/// cache all queries executed by this template. /// cache all queries executed by this template.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
@@ -344,7 +344,7 @@ namespace Spring.Data.NHibernate.Generic
/// <summary> /// <summary>
/// Gets or sets the proxy factory. /// Gets or sets the proxy factory.
/// </summary> /// </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 /// HibernateTemplate and/or HibernateDaoSupport. This allows the same
/// ProxyFactory implementation to be used thereby limiting the /// ProxyFactory implementation to be used thereby limiting the
/// number of dynamic proxy types created in the temporary assembly, which /// number of dynamic proxy types created in the temporary assembly, which
@@ -362,8 +362,8 @@ namespace Spring.Data.NHibernate.Generic
#region Properties #region Properties
#endregion #endregion
#region Methods #region Methods
@@ -374,7 +374,7 @@ namespace Spring.Data.NHibernate.Generic
/// </summary> /// </summary>
public void Clear() public void Clear()
{ {
classicHibernateTemplate.Clear(); classicHibernateTemplate.Clear();
} }
@@ -606,13 +606,13 @@ namespace Spring.Data.NHibernate.Generic
#endif #endif
/// <summary> /// <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. /// 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. /// 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". /// 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> /// </summary>
/// <param name="entity">The persistent object to merge. /// <param name="entity">The persistent object to merge.
/// (<i>not</i> necessarily to be associated with the Hibernate Session) /// (<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> /// <typeparam name="T">The object type to get.</typeparam>
/// <param name="id">The id of the object to get.</param> /// <param name="id">The id of the object to get.</param>
/// <returns>the persistent instance, or null if not found</returns> /// <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) public T Get<T>(object id)
{ {
return Get<T>(id, null); return Get<T>(id, null);
@@ -668,7 +668,7 @@ namespace Spring.Data.NHibernate.Generic
/// <typeparam name="T">The object type to load.</typeparam> /// <typeparam name="T">The object type to load.</typeparam>
/// <param name="id">An identifier of the persistent instance.</param> /// <param name="id">An identifier of the persistent instance.</param>
/// <returns>The persistent instance</returns> /// <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> /// <exception cref="DataAccessException">In case of Hibernate errors</exception>
public T Load<T>(object id) 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="id">An identifier of the persistent instance.</param>
/// <param name="lockMode">The lock mode.</param> /// <param name="lockMode">The lock mode.</param>
/// <returns>The persistent instance</returns> /// <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> /// <exception cref="DataAccessException">In case of Hibernate errors</exception>
public T Load<T>(object id, LockMode lockMode) public T Load<T>(object id, LockMode lockMode)
{ {
return Execute(new LoadByTypeHibernateCallback<T>(id, lockMode), true); return Execute(new LoadByTypeHibernateCallback<T>(id, lockMode), true);
@@ -715,7 +715,7 @@ namespace Spring.Data.NHibernate.Generic
/// <returns> /// <returns>
/// a generic List containing 0 or more persistent instances /// a generic List containing 0 or more persistent instances
/// </returns> /// </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) public IList<T> Find<T>(string queryString)
{ {
return Find<T>(queryString, (object[]) null, (IType[]) null); return Find<T>(queryString, (object[]) null, (IType[]) null);
@@ -731,7 +731,7 @@ namespace Spring.Data.NHibernate.Generic
/// <returns> /// <returns>
/// a generic List containing 0 or more persistent instances /// a generic List containing 0 or more persistent instances
/// </returns> /// </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) public IList<T> Find<T>(string queryString, object value)
{ {
return Find<T>(queryString, new object[] {value}, (IType[]) null); return Find<T>(queryString, new object[] {value}, (IType[]) null);
@@ -748,7 +748,7 @@ namespace Spring.Data.NHibernate.Generic
/// <returns> /// <returns>
/// a generic List containing 0 or more persistent instances /// a generic List containing 0 or more persistent instances
/// </returns> /// </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) public IList<T> Find<T>(string queryString, object value, IType type)
{ {
return Find<T>(queryString, new object[] {value}, new 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="queryString">a query expressed in Hibernate's query language</param>
/// <param name="values">the values of the parameters</param> /// <param name="values">the values of the parameters</param>
/// <returns>a generic List containing 0 or more persistent instances</returns> /// <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) public IList<T> Find<T>(string queryString, object[] values)
{ {
return Find<T>(queryString, values, (IType[]) null); return Find<T>(queryString, values, (IType[]) null);
@@ -779,8 +779,8 @@ namespace Spring.Data.NHibernate.Generic
/// <returns> /// <returns>
/// a generic List containing 0 or more persistent instances /// a generic List containing 0 or more persistent instances
/// </returns> /// </returns>
/// <exception cref="DataAccessException">In case of Hibernate errors</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> /// <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) public IList<T> Find<T>(string queryString, object[] values, IType[] types)
{ {
if (values != null && types != null && values.Length != types.Length) 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> /// <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>
/// <exception cref="ArgumentOutOfRangeException">If paramNames length is not equal to values length or /// <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, public IList<T> FindByNamedQueryAndNamedParam<T>(string queryName, string[] paramNames, object[] values,
IType[] types) IType[] types)
{ {
@@ -1050,7 +1050,7 @@ namespace Spring.Data.NHibernate.Generic
/// of the given object to <i>named</i> parameters in the query string. /// of the given object to <i>named</i> parameters in the query string.
/// </summary> /// </summary>
/// <typeparam name="T">The object type to find.</typeparam> /// <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> /// <param name="valueObject">The values of the parameters</param>
/// <returns>A generic List containing 0 or more persistent instances</returns> /// <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>

View File

@@ -1,7 +1,7 @@
#region License #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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.

View File

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

View File

@@ -36,11 +36,11 @@ namespace Spring.Web.UI.Controls
/// within the page. /// within the page.
/// </para> /// </para>
/// <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. /// any control within the current page - it is not limited to replacing ContentPlaceholders on master pages.
/// </para> /// </para>
/// <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. /// design requires navigation elements to be distributed across different places within the HTML code.
/// </para> /// </para>
/// </remarks> /// </remarks>
@@ -71,7 +71,7 @@ namespace Spring.Web.UI.Controls
if (!Visible) return; if (!Visible) return;
//log.Debug(string.Format("OnPreRender Content['{0}']", this.contentPlaceHolderID)); //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); Control ctl = ctlRoot.FindControl(this.contentPlaceHolderID);
if (ctl != null) if (ctl != null)
@@ -120,7 +120,7 @@ namespace Spring.Web.UI.Controls
private static readonly PropertyInfo piRareFieldsEnsured = private static readonly PropertyInfo piRareFieldsEnsured =
typeof(Control).GetProperty("RareFieldsEnsured", BindingFlags.NonPublic | BindingFlags.Instance); 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"); typeof(Control).GetNestedType("ControlRareFields",BindingFlags.NonPublic).GetField("RenderMethod");
private RenderMethod GetRenderMethod() private RenderMethod GetRenderMethod()

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,13 +1,13 @@
#region License #region License
/* /*
* Copyright 2002-2010 the original author or authors. * Copyright 2002-2010 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -16,14 +16,14 @@
*/ */
#endregion #endregion
#region Imports
using System; using System;
using NUnit.Framework; using NUnit.Framework;
using AopAlliance.Aop; using AopAlliance.Aop;
using Rhino.Mocks;
using FakeItEasy;
using Spring.Aop.Framework; using Spring.Aop.Framework;
using Spring.Objects; using Spring.Objects;
#endregion
namespace Spring.Aop.Support namespace Spring.Aop.Support
{ {
@@ -58,9 +58,9 @@ namespace Spring.Aop.Support
TestObject raw = new TestObject(); TestObject raw = new TestObject();
Assert.IsTrue(! (raw is ITimeStamped)); Assert.IsTrue(! (raw is ITimeStamped));
ProxyFactory factory = new ProxyFactory(raw); ProxyFactory factory = new ProxyFactory(raw);
ITimeStampedIntroduction ts = MockRepository.GenerateMock<ITimeStampedIntroduction>(); ITimeStampedIntroduction ts = A.Fake<ITimeStampedIntroduction>();
ts.Stub(x => x.TimeStamp).Return(EXPECTED_TIMESTAMP); A.CallTo(() => ts.TimeStamp).Returns(EXPECTED_TIMESTAMP);
DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor(ts); DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor(ts);
factory.AddIntroduction(advisor); factory.AddIntroduction(advisor);
@@ -74,17 +74,18 @@ namespace Spring.Aop.Support
public interface ISubTimeStampedIntroduction: ISubTimeStamped, IAdvice public interface ISubTimeStampedIntroduction: ISubTimeStamped, IAdvice
{ {
} }
public void TestIntroductionInterceptorWithInterfaceHierarchy() [Test]
public void TestIntroductionInterceptorWithInterfaceHierarchy()
{ {
TestObject raw = new TestObject(); TestObject raw = new TestObject();
Assert.IsTrue(! (raw is ISubTimeStamped)); Assert.IsTrue(! (raw is ISubTimeStamped));
ProxyFactory factory = new ProxyFactory(raw); ProxyFactory factory = new ProxyFactory(raw);
ISubTimeStampedIntroduction ts = MockRepository.GenerateMock<ISubTimeStampedIntroduction>(); ISubTimeStampedIntroduction ts = A.Fake<ISubTimeStampedIntroduction>();
ts.Stub(x => x.TimeStamp).Return(EXPECTED_TIMESTAMP); A.CallTo(() => ts.TimeStamp).Returns(EXPECTED_TIMESTAMP);
DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor(ts); DefaultIntroductionAdvisor advisor = new DefaultIntroductionAdvisor(ts);
// we must add introduction, not an advisor // we must add introduction, not an advisor
factory.AddIntroduction(advisor); factory.AddIntroduction(advisor);
@@ -93,17 +94,18 @@ namespace Spring.Aop.Support
Assert.IsTrue(tsp.TimeStamp == EXPECTED_TIMESTAMP); Assert.IsTrue(tsp.TimeStamp == EXPECTED_TIMESTAMP);
} }
public void TestIntroductionInterceptorWithSuperInterface() [Test]
public void TestIntroductionInterceptorWithSuperInterface()
{ {
TestObject raw = new TestObject(); TestObject raw = new TestObject();
Assert.IsTrue(! (raw is ITimeStamped)); Assert.IsTrue(! (raw is ITimeStamped));
ProxyFactory factory = new ProxyFactory(raw); ProxyFactory factory = new ProxyFactory(raw);
ISubTimeStamped ts = MockRepository.GenerateMock<ISubTimeStampedIntroduction>(); ISubTimeStampedIntroduction ts = A.Fake<ISubTimeStampedIntroduction>();
ts.Stub(x => x.TimeStamp).Return(EXPECTED_TIMESTAMP); A.CallTo(() => ts.TimeStamp).Returns(EXPECTED_TIMESTAMP);
factory.AddIntroduction(0, new DefaultIntroductionAdvisor( factory.AddIntroduction(0, new DefaultIntroductionAdvisor(
(ISubTimeStampedIntroduction)ts, ts,
typeof(ITimeStamped)) typeof(ITimeStamped))
); );
@@ -121,42 +123,42 @@ namespace Spring.Aop.Support
{ {
private DateTime _timestamp; private DateTime _timestamp;
public Test(DateTime timestamp) public Test(DateTime timestamp)
{ {
_timestamp = timestamp; _timestamp = timestamp;
} }
public void Foo() public void Foo()
{ {
} }
public DateTime TimeStamp public DateTime TimeStamp
{ {
get get
{ {
return _timestamp; return _timestamp;
} }
} }
} }
public void TestAutomaticInterfaceRecognitionInDelegate() public void TestAutomaticInterfaceRecognitionInDelegate()
{ {
IIntroductionAdvisor ia = new DefaultIntroductionAdvisor(new Test(EXPECTED_TIMESTAMP)); IIntroductionAdvisor ia = new DefaultIntroductionAdvisor(new Test(EXPECTED_TIMESTAMP));
TestObject target = new TestObject(); TestObject target = new TestObject();
ProxyFactory pf = new ProxyFactory(target); ProxyFactory pf = new ProxyFactory(target);
pf.AddIntroduction(0, ia); pf.AddIntroduction(0, ia);
ITimeStamped ts = (ITimeStamped) pf.GetProxy(); ITimeStamped ts = (ITimeStamped) pf.GetProxy();
Assert.IsTrue(ts.TimeStamp == EXPECTED_TIMESTAMP); Assert.IsTrue(ts.TimeStamp == EXPECTED_TIMESTAMP);
((ITest) ts).Foo(); ((ITest) ts).Foo();
int age = ((ITestObject) ts).Age; int age = ((ITestObject) ts).Age;
} }
/* /*
* The rest of the tests in the original tested subclassing the * The rest of the tests in the original tested subclassing the
* DelegatingIntroductionInterceptor. * DelegatingIntroductionInterceptor.
* *
* Since we don't need to subclass anything to make a delegating * Since we don't need to subclass anything to make a delegating
* introduction, the rest of the tests are not necessary. * 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 // must be public to be used for AOP
// AOP creates a new assembly which must have access to the // AOP creates a new assembly which must have access to the
// interfaces that it intends to expose. // interfaces that it intends to expose.
public interface ITest public interface ITest
{ {
void Foo(); void Foo();
} }
public interface ISubTimeStamped : ITimeStamped public interface ISubTimeStamped : ITimeStamped
{ {
} }

View File

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

View File

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

View File

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

View File

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

View File

@@ -18,18 +18,16 @@
#endregion #endregion
#region Imports
using System; using System;
using System.Reflection; using System.Reflection;
using AopAlliance.Intercept; using AopAlliance.Intercept;
using Common.Logging; 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 namespace Spring.Aspects.Logging
{ {
@@ -51,12 +49,9 @@ namespace Spring.Aspects.Logging
{ } { }
} }
private MockRepository mocks;
[SetUp] [SetUp]
public void Setup() public void Setup()
{ {
mocks = new MockRepository();
} }
[Test] [Test]
@@ -64,101 +59,76 @@ namespace Spring.Aspects.Logging
{ {
ProxyFactory pf = new ProxyFactory(new TestTarget()); ProxyFactory pf = new ProxyFactory(new TestTarget());
ILog log = (ILog)mocks.CreateMock(typeof(ILog)); ILog log = A.Fake<ILog>();
SimpleLoggingAdvice loggingAdvice = new SimpleLoggingAdvice(log); SimpleLoggingAdvice loggingAdvice = new SimpleLoggingAdvice(log);
pf.AddAdvice(loggingAdvice); pf.AddAdvice(loggingAdvice);
Expect.Call(log.IsTraceEnabled).Return(true).Repeat.Any(); A.CallTo(() => log.IsTraceEnabled).Returns(true);
log.Trace("Entering DoSomething");
log.Trace("Exiting DoSomething");
mocks.ReplayAll();
object proxy = pf.GetProxy(); object proxy = pf.GetProxy();
ITestTarget ptt = (ITestTarget)proxy; ITestTarget ptt = (ITestTarget)proxy;
ptt.DoSomething(); ptt.DoSomething();
mocks.VerifyAll(); A.CallTo(() => log.Trace("Entering DoSomething")).MustHaveHappened();
A.CallTo(() => log.Trace("Exiting DoSomething")).MustHaveHappened();
} }
[Test] [Test]
public void SunnyDayLoggingCorrectly() public void SunnyDayLoggingCorrectly()
{ {
ILog log = (ILog)mocks.CreateMock(typeof(ILog)); ILog log = A.Fake<ILog>();
IMethodInvocation methodInvocation = (IMethodInvocation)mocks.CreateMock(typeof(IMethodInvocation)); IMethodInvocation methodInvocation = A.Fake<IMethodInvocation>();
MethodInfo mi = typeof(string).GetMethod("ToString", Type.EmptyTypes); MethodInfo mi = typeof(string).GetMethod("ToString", Type.EmptyTypes);
//two additional calls the method are to retrieve the method name on entry/exit... //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);
A.CallTo(() => log.IsTraceEnabled).Returns(true);
Expect.Call(log.IsTraceEnabled).Return(true).Repeat.Any(); A.CallTo(() => methodInvocation.Proceed()).Returns(null);
log.Trace("Entering ToString");
Expect.Call(methodInvocation.Proceed()).Return(null);
log.Trace("Exiting ToString");
mocks.ReplayAll();
TestableSimpleLoggingAdvice loggingAdvice = new TestableSimpleLoggingAdvice(true); TestableSimpleLoggingAdvice loggingAdvice = new TestableSimpleLoggingAdvice(true);
loggingAdvice.CallInvokeUnderLog(methodInvocation, log); loggingAdvice.CallInvokeUnderLog(methodInvocation, log);
mocks.VerifyAll(); A.CallTo(() => log.Trace("Entering ToString")).MustHaveHappened();
A.CallTo(() => log.Trace("Exiting ToString")).MustHaveHappened();
} }
[Test] [Test]
public void SunnyDayLoggingCorrectlyDebugLevel() public void SunnyDayLoggingCorrectlyDebugLevel()
{ {
ILog log = (ILog)mocks.CreateMock(typeof(ILog)); ILog log = A.Fake<ILog>();
IMethodInvocation methodInvocation = (IMethodInvocation)mocks.CreateMock(typeof(IMethodInvocation)); IMethodInvocation methodInvocation = A.Fake<IMethodInvocation>();
MethodInfo mi = typeof(string).GetMethod("ToString", Type.EmptyTypes); MethodInfo mi = typeof(string).GetMethod("ToString", Type.EmptyTypes);
//two additional calls the method are to retrieve the method name on entry/exit... //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(); A.CallTo(() => log.IsTraceEnabled).Returns(false);
Expect.Call(log.IsDebugEnabled).Return(true).Repeat.Any(); A.CallTo(() => log.IsDebugEnabled).Returns(true);
log.Debug("Entering ToString");
Expect.Call(methodInvocation.Proceed()).Return(null); A.CallTo(() => methodInvocation.Proceed()).Returns(null);
log.Debug("Exiting ToString");
mocks.ReplayAll();
TestableSimpleLoggingAdvice loggingAdvice = new TestableSimpleLoggingAdvice(true); TestableSimpleLoggingAdvice loggingAdvice = new TestableSimpleLoggingAdvice(true);
loggingAdvice.LogLevel = LogLevel.Debug; loggingAdvice.LogLevel = LogLevel.Debug;
Assert.IsTrue(loggingAdvice.CallIsInterceptorEnabled(methodInvocation, log)); Assert.IsTrue(loggingAdvice.CallIsInterceptorEnabled(methodInvocation, log));
loggingAdvice.CallInvokeUnderLog(methodInvocation, log); loggingAdvice.CallInvokeUnderLog(methodInvocation, log);
mocks.VerifyAll(); A.CallTo(() => log.Debug("Entering ToString")).MustHaveHappened();
A.CallTo(() => log.Debug("Exiting ToString")).MustHaveHappened();
} }
[Test] [Test]
public void ExceptionPathStillLogsCorrectly() public void ExceptionPathStillLogsCorrectly()
{ {
ILog log = (ILog)mocks.CreateMock(typeof(ILog)); ILog log = A.Fake<ILog>();
IMethodInvocation methodInvocation = (IMethodInvocation)mocks.CreateMock(typeof(IMethodInvocation)); IMethodInvocation methodInvocation = A.Fake<IMethodInvocation>();
MethodInfo mi = typeof(string).GetMethod("ToString", Type.EmptyTypes); MethodInfo mi = typeof(string).GetMethod("ToString", Type.EmptyTypes);
//two additional calls the method are to retrieve the method name on entry/exit... //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);
A.CallTo(() => log.IsTraceEnabled).Returns(true);
Expect.Call(log.IsTraceEnabled).Return(true).Repeat.Any();
log.Trace("Entering...");
LastCall.On(log).IgnoreArguments();
Exception e = new ArgumentException("bad value"); Exception e = new ArgumentException("bad value");
Expect.Call(methodInvocation.Proceed()).Throw(e); A.CallTo(() => methodInvocation.Proceed()).Throws(e);
log.Trace("Exception...", e);
LastCall.On(log).IgnoreArguments();
mocks.ReplayAll();
TestableSimpleLoggingAdvice loggingAdvice = new TestableSimpleLoggingAdvice(true); TestableSimpleLoggingAdvice loggingAdvice = new TestableSimpleLoggingAdvice(true);
try try
@@ -168,39 +138,27 @@ namespace Spring.Aspects.Logging
} }
catch (ArgumentException) catch (ArgumentException)
{ {
} }
mocks.VerifyAll(); A.CallTo(() => log.Trace("Entering ToString")).MustHaveHappened();
A.CallTo(() => log.Trace("Exception thrown in ToString, ToString", e)).MustHaveHappened();
} }
[Test] [Test]
public void SunnyDayLoggingAllOptionalInformationCorrectly() public void SunnyDayLoggingAllOptionalInformationCorrectly()
{ {
ILog log = (ILog)mocks.CreateMock(typeof(ILog)); ILog log = A.Fake<ILog>();
IMethodInvocation methodInvocation = (IMethodInvocation)mocks.CreateMock(typeof(IMethodInvocation)); IMethodInvocation methodInvocation = A.Fake<IMethodInvocation>();
MethodInfo mi = typeof(Dog).GetMethod("Bark"); MethodInfo mi = typeof(Dog).GetMethod("Bark");
//two additional calls the method are to retrieve the method name on entry/exit... //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 }; int[] luckyNumbers = new int[] { 1, 2, 3 };
object[] args = new object[] { "hello", luckyNumbers }; object[] args = new object[] { "hello", luckyNumbers };
A.CallTo(() => methodInvocation.Arguments).Returns(args);
Expect.Call(methodInvocation.Arguments).Return(args); A.CallTo(() => log.IsTraceEnabled).Returns(true);
A.CallTo(() => methodInvocation.Proceed()).Returns(4);
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();
TestableSimpleLoggingAdvice loggingAdvice = new TestableSimpleLoggingAdvice(true); TestableSimpleLoggingAdvice loggingAdvice = new TestableSimpleLoggingAdvice(true);
loggingAdvice.LogExecutionTime = true; loggingAdvice.LogExecutionTime = true;
@@ -209,7 +167,8 @@ namespace Spring.Aspects.Logging
loggingAdvice.CallInvokeUnderLog(methodInvocation, log); 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 #endregion
#region Imports
using System; using System;
using System.Reflection; using System.Reflection;
using Rhino.Mocks;
using FakeItEasy;
using NUnit.Framework; using NUnit.Framework;
using Spring.Context; using Spring.Context;
using Spring.Validation; using Spring.Validation;
using Spring.Validation.Actions; using Spring.Validation.Actions;
#endregion
namespace Spring.Aspects.Validation namespace Spring.Aspects.Validation
{ {
/// <summary> /// <summary>
@@ -42,13 +40,11 @@ namespace Spring.Aspects.Validation
private IApplicationContext mockContext; private IApplicationContext mockContext;
private ParameterValidationAdvice advice; private ParameterValidationAdvice advice;
private RequiredValidator requiredValidator; private RequiredValidator requiredValidator;
private MockRepository mocks;
[SetUp] [SetUp]
public void SetUp() public void SetUp()
{ {
mocks = new MockRepository(); mockContext = A.Fake<IApplicationContext>();
mockContext = mocks.CreateMock<IApplicationContext>();
advice = new ParameterValidationAdvice(); advice = new ParameterValidationAdvice();
advice.ApplicationContext = mockContext; advice.ApplicationContext = mockContext;
@@ -65,18 +61,11 @@ namespace Spring.Aspects.Validation
ValidationTarget target = new ValidationTarget(); ValidationTarget target = new ValidationTarget();
object[] args = new object[] {inventor}; object[] args = new object[] {inventor};
using (mocks.Record()) ExpectValidatorRetrieval("required", requiredValidator);
{
ExpectValidatorRetrieval("required", requiredValidator);
}
using (mocks.Playback())
{
advice.Before(method, args, target);
method.Invoke(target, args);
Assert.AreEqual("NIKOLA TESLA", inventor.Name);
}
advice.Before(method, args, target);
method.Invoke(target, args);
Assert.AreEqual("NIKOLA TESLA", inventor.Name);
} }
[Test] [Test]
@@ -84,25 +73,15 @@ namespace Spring.Aspects.Validation
{ {
MethodInfo method = typeof(ValidationTarget).GetMethod("Save"); 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) 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 #region Inner Class : ValidationTarget

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,7 +1,7 @@
#region License #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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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() public void TestLiveVariablesResolutionWithTestDriven()
{ {
CommandLineArgsVariableSource vs = new CommandLineArgsVariableSource(); 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 #endregion
#region Imports
using System; using System;
using System.Collections; using System.Collections;
using System.ComponentModel; using System.ComponentModel;
using System.Drawing; using System.Drawing;
using NUnit.Framework;
using Rhino.Mocks;
#endregion using FakeItEasy;
using NUnit.Framework;
namespace Spring.Objects.Factory.Config namespace Spring.Objects.Factory.Config
{ {
@@ -38,15 +36,12 @@ namespace Spring.Objects.Factory.Config
[TestFixture] [TestFixture]
public sealed class CustomConverterConfigurerTests public sealed class CustomConverterConfigurerTests
{ {
private MockRepository mocks;
private IConfigurableListableObjectFactory factory; private IConfigurableListableObjectFactory factory;
[SetUp] [SetUp]
public void SetUp() public void SetUp()
{ {
mocks = new MockRepository(); factory = A.Fake<IConfigurableListableObjectFactory>();
factory = mocks.StrictMock<IConfigurableListableObjectFactory>();
} }
[Test] [Test]
@@ -93,9 +88,6 @@ namespace Spring.Objects.Factory.Config
CustomConverterConfigurer config = new CustomConverterConfigurer(); CustomConverterConfigurer config = new CustomConverterConfigurer();
config.CustomConverters = null; config.CustomConverters = null;
config.PostProcessObjectFactory(factory); config.PostProcessObjectFactory(factory);
mocks.ReplayAll();
mocks.VerifyAll();
} }
[Test] [Test]
@@ -106,21 +98,16 @@ namespace Spring.Objects.Factory.Config
DateTimeConverter dateTimeConverter = new DateTimeConverter(); DateTimeConverter dateTimeConverter = new DateTimeConverter();
Type colorType = typeof(Color); Type colorType = typeof(Color);
ColorConverter colorConverter = new ColorConverter(); ColorConverter colorConverter = new ColorConverter();
converters.Add(dateTimeType, dateTimeConverter); converters.Add(dateTimeType, dateTimeConverter);
converters.Add(colorType, colorConverter); converters.Add(colorType, colorConverter);
factory.RegisterCustomConverter(dateTimeType, dateTimeConverter); factory.RegisterCustomConverter(dateTimeType, dateTimeConverter);
factory.RegisterCustomConverter(colorType, colorConverter); factory.RegisterCustomConverter(colorType, colorConverter);
mocks.ReplayAll();
CustomConverterConfigurer config = new CustomConverterConfigurer(); CustomConverterConfigurer config = new CustomConverterConfigurer();
config.CustomConverters = converters; config.CustomConverters = converters;
config.PostProcessObjectFactory(factory); config.PostProcessObjectFactory(factory);
mocks.VerifyAll();
} }
} }
} }

View File

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

View File

@@ -18,115 +18,98 @@
#endregion #endregion
#region Imports
using System; using System;
using NUnit.Framework;
using Rhino.Mocks;
#endregion using FakeItEasy;
using NUnit.Framework;
namespace Spring.Objects.Factory.Config namespace Spring.Objects.Factory.Config
{ {
/// <summary> /// <summary>
/// Unit tests for the ObjectReferenceFactoryObject class. /// Unit tests for the ObjectReferenceFactoryObject class.
/// </summary> /// </summary>
/// <author>Rick Evans</author> /// <author>Rick Evans</author>
[TestFixture] [TestFixture]
public sealed class ObjectReferenceFactoryObjectTests public sealed class ObjectReferenceFactoryObjectTests
{ {
private MockRepository mocks; private IObjectFactory factory;
private IObjectFactory factory;
[SetUp] [SetUp]
public void SetUp() public void SetUp()
{ {
mocks = new MockRepository(); factory = A.Fake<IObjectFactory>();
factory = mocks.StrictMock<IObjectFactory>();
} }
[Test] [Test]
public void NullTargetObjectName() public void NullTargetObjectName()
{ {
ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject(); ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject();
// simulate IFactoryObjectAware interface... // simulate IFactoryObjectAware interface...
Assert.Throws<ArgumentException>(() => fac.ObjectFactory = null); Assert.Throws<ArgumentException>(() => fac.ObjectFactory = null);
} }
[Test] [Test]
public void WhitespaceTargetObjectName() public void WhitespaceTargetObjectName()
{ {
ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject(); ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject();
fac.TargetObjectName = string.Empty; fac.TargetObjectName = string.Empty;
// simulate IFactoryObjectAware interface... // simulate IFactoryObjectAware interface...
Assert.Throws<ArgumentException>(() => fac.ObjectFactory = null); Assert.Throws<ArgumentException>(() => fac.ObjectFactory = null);
} }
[Test]
public void FactoryDoesNotContainTargetObject()
{
Expect.Call(factory.ContainsObject("bojangles")).Return(false);
mocks.ReplayAll();
ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject(); [Test]
fac.TargetObjectName = "bojangles"; public void FactoryDoesNotContainTargetObject()
try {
{ A.CallTo(() => factory.ContainsObject("bojangles")).Returns(false);
// 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();
ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject(); ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject();
fac.TargetObjectName = "bojangles"; fac.TargetObjectName = "bojangles";
fac.ObjectFactory = factory;
Assert.IsTrue(fac.IsSingleton); // simulate IFactoryObjectAware interface...
mocks.VerifyAll(); Assert.Throws<NoSuchObjectDefinitionException>(() => fac.ObjectFactory = factory,
} "Must have bailed with a " +
"NoSuchObjectDefinitionException 'cos the object doesn't " +
"exist in the associated factory.");
}
[Test] [Test]
public void DelegatesThroughToFactoryFor_GetObject() public void DelegatesThroughToFactoryFor_IsSingleton()
{ {
Expect.Call(factory.ContainsObject("bojangles")).Return(true); A.CallTo(() => factory.ContainsObject("bojangles")).Returns(true);
Expect.Call(factory.GetObject("bojangles")).Return("Rick"); A.CallTo(() => factory.IsSingleton("bojangles")).Returns(true);
mocks.ReplayAll();
ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject(); ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject();
fac.TargetObjectName = "bojangles"; fac.TargetObjectName = "bojangles";
fac.ObjectFactory = factory; fac.ObjectFactory = factory;
Assert.AreEqual("Rick", fac.GetObject()); Assert.IsTrue(fac.IsSingleton);
mocks.VerifyAll(); }
}
[Test] [Test]
public void DelegatesThroughToFactoryFor_ObjectType() public void DelegatesThroughToFactoryFor_GetObject()
{ {
Expect.Call(factory.ContainsObject("bojangles")).Return(true); A.CallTo(() => factory.ContainsObject("bojangles")).Returns(true);
Expect.Call(factory.GetType("bojangles")).Return(GetType()); A.CallTo(() => factory.GetObject("bojangles")).Returns("Rick");
mocks.ReplayAll();
ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject(); ObjectReferenceFactoryObject fac = new ObjectReferenceFactoryObject();
fac.TargetObjectName = "bojangles"; fac.TargetObjectName = "bojangles";
fac.ObjectFactory = factory; fac.ObjectFactory = factory;
Assert.AreEqual(GetType(), fac.ObjectType); Assert.AreEqual("Rick", fac.GetObject());
mocks.VerifyAll(); }
}
[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 #endregion
#region Imports
using System.Collections.Specialized; using System.Collections.Specialized;
using Common.Logging; using Common.Logging;
using Common.Logging.Simple; using Common.Logging.Simple;
using FakeItEasy;
using NUnit.Framework; using NUnit.Framework;
using Rhino.Mocks;
using Spring.Context.Support; using Spring.Context.Support;
using Spring.Core.IO; using Spring.Core.IO;
using Spring.Objects.Factory.Xml; using Spring.Objects.Factory.Xml;
#endregion
namespace Spring.Objects.Factory.Config namespace Spring.Objects.Factory.Config
{ {
/// <summary> /// <summary>
@@ -40,13 +38,9 @@ namespace Spring.Objects.Factory.Config
[TestFixture] [TestFixture]
public sealed class PropertyOverrideConfigurerTests public sealed class PropertyOverrideConfigurerTests
{ {
private MockRepository mocks;
[SetUp] [SetUp]
public void Setup() public void Setup()
{ {
mocks = new MockRepository();
} }
/// <summary> /// <summary>
@@ -56,7 +50,7 @@ namespace Spring.Objects.Factory.Config
public void FixtureSetUp() public void FixtureSetUp()
{ {
// enable (null appender) logging, just to ensure that the logging code is correct // enable (null appender) logging, just to ensure that the logging code is correct
LogManager.Adapter = new NoOpLoggerFactoryAdapter(); LogManager.Adapter = new NoOpLoggerFactoryAdapter();
} }
[Test] [Test]
@@ -90,7 +84,7 @@ namespace Spring.Objects.Factory.Config
pvs.Add("Age", 27); pvs.Add("Age", 27);
pvs.Add("Name", "Bruno"); pvs.Add("Name", "Bruno");
ac.RegisterSingleton("tb1", typeof(TestObject), pvs); ac.RegisterSingleton("tb1", typeof(TestObject), pvs);
pvs = new MutablePropertyValues(); pvs = new MutablePropertyValues();
pvs.Add("Properties", "<spring-config><add key=\"tb1.Age\" value=\"99\"/><add key=\"tb1.Name\" value=\"test\"/></spring-config>"); 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); ac.RegisterSingleton("configurer", typeof (PropertyOverrideConfigurer), pvs);
@@ -105,11 +99,11 @@ namespace Spring.Objects.Factory.Config
public void OverridePropertyReference() public void OverridePropertyReference()
{ {
StaticApplicationContext ac = new StaticApplicationContext(); StaticApplicationContext ac = new StaticApplicationContext();
MutablePropertyValues pvs = new MutablePropertyValues(); MutablePropertyValues pvs = new MutablePropertyValues();
pvs.Add("Spouse", new RuntimeObjectReference("spouse1")); pvs.Add("Spouse", new RuntimeObjectReference("spouse1"));
ac.RegisterSingleton("tb1", typeof(TestObject), pvs); ac.RegisterSingleton("tb1", typeof(TestObject), pvs);
ac.RegisterSingleton("spouse1", typeof(TestObject), new MutablePropertyValues()); ac.RegisterSingleton("spouse1", typeof(TestObject), new MutablePropertyValues());
ac.RegisterSingleton("spouse2", typeof(TestObject), new MutablePropertyValues()); ac.RegisterSingleton("spouse2", typeof(TestObject), new MutablePropertyValues());
@@ -144,23 +138,15 @@ namespace Spring.Objects.Factory.Config
[Test] [Test]
public void MalformedOverrideKey() public void MalformedOverrideKey()
{ {
IConfigurableListableObjectFactory objectFactory = mocks.StrictMock<IConfigurableListableObjectFactory>(); IConfigurableListableObjectFactory objectFactory = A.Fake<IConfigurableListableObjectFactory>();
IConfigurableListableObjectFactory fac = objectFactory; IConfigurableListableObjectFactory fac = objectFactory;
PropertyOverrideConfigurer cfg = new PropertyOverrideConfigurer(); PropertyOverrideConfigurer cfg = new PropertyOverrideConfigurer();
NameValueCollection defaultProperties = new NameValueCollection(); NameValueCollection defaultProperties = new NameValueCollection();
defaultProperties.Add("malformedKey", "Rick Evans"); defaultProperties.Add("malformedKey", "Rick Evans");
cfg.Properties = defaultProperties; cfg.Properties = defaultProperties;
mocks.ReplayAll();
try Assert.Throws<FatalObjectException>(() => cfg.PostProcessObjectFactory(fac));
{
cfg.PostProcessObjectFactory(fac);
Assert.Fail("Should have had a FatalObjectException at this point because of a malformed key.");
}
catch (FatalObjectException)
{
}
mocks.VerifyAll();
} }
[Test] [Test]
@@ -168,20 +154,17 @@ namespace Spring.Objects.Factory.Config
{ {
const string valueTo_NOT_BeOveridden = "Jenny Lewis"; const string valueTo_NOT_BeOveridden = "Jenny Lewis";
TestObject foo = new TestObject(valueTo_NOT_BeOveridden, 30); TestObject foo = new TestObject(valueTo_NOT_BeOveridden, 30);
IConfigurableListableObjectFactory objectFactory = mocks.StrictMock<IConfigurableListableObjectFactory>(); IConfigurableListableObjectFactory objectFactory = A.Fake<IConfigurableListableObjectFactory>();
Expect.Call(objectFactory.GetObjectDefinition("rubbish")).Return(null); A.CallTo(() => objectFactory.GetObjectDefinition("rubbish")).Returns(null);
IConfigurableListableObjectFactory fac = objectFactory; IConfigurableListableObjectFactory fac = objectFactory;
PropertyOverrideConfigurer cfg = new PropertyOverrideConfigurer(); PropertyOverrideConfigurer cfg = new PropertyOverrideConfigurer();
NameValueCollection defaultProperties = new NameValueCollection(); NameValueCollection defaultProperties = new NameValueCollection();
defaultProperties.Add("rubbish.Name", "Rick Evans"); defaultProperties.Add("rubbish.Name", "Rick Evans");
cfg.Properties = defaultProperties; 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] [Test]

View File

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

View File

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

View File

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

View File

@@ -1,7 +1,7 @@
#region License #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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -22,8 +22,10 @@
using System; using System;
using System.Collections; using System.Collections;
using FakeItEasy;
using NUnit.Framework; using NUnit.Framework;
using Rhino.Mocks;
using Spring.Objects.Factory.Support; using Spring.Objects.Factory.Support;
using Spring.Objects.Support; using Spring.Objects.Support;
@@ -113,25 +115,19 @@ namespace Spring.Objects.Factory.Config
{ {
DefaultListableObjectFactory of = new DefaultListableObjectFactory(); DefaultListableObjectFactory of = new DefaultListableObjectFactory();
MockRepository mocks = new MockRepository(); ISharedStateFactory ssf1 = A.Fake<ISharedStateFactory>();
ISharedStateFactory ssf1 = mocks.StrictMock<ISharedStateFactory>(); ISharedStateAware ssa = A.Fake<ISharedStateAware>();
ISharedStateAware ssa = (ISharedStateAware)mocks.DynamicMock( typeof( ISharedStateAware ) );
SharedStateAwareProcessor ssap = new SharedStateAwareProcessor(); SharedStateAwareProcessor ssap = new SharedStateAwareProcessor();
ssap.SharedStateFactories = new ISharedStateFactory[] { ssf1 }; ssap.SharedStateFactories = new ISharedStateFactory[] {ssf1};
of.RegisterSingleton( "ssap", ssap ); of.RegisterSingleton("ssap", ssap);
using (Record( mocks )) // preset SharedState - ssap must ignore it
{ A.CallTo(() => ssa.SharedState).Returns(new Hashtable());
// preset SharedState - ssap must ignore it
Expect.Call( ssa.SharedState ).Return( new Hashtable() );
// expect nothing else!
}
using (Playback( mocks )) ssap.PostProcessBeforeInitialization(ssa, "myPage");
{
ssap.PostProcessBeforeInitialization( ssa, "myPage" ); A.CallTo(ssa).Where(x => x.Method.Name == "set_SharedState").MustNotHaveHappened();
}
} }
[Test] [Test]
@@ -139,53 +135,33 @@ namespace Spring.Objects.Factory.Config
{ {
DefaultListableObjectFactory of = new DefaultListableObjectFactory(); DefaultListableObjectFactory of = new DefaultListableObjectFactory();
MockRepository mocks = new MockRepository(); ISharedStateFactory ssf1 = A.Fake<ISharedStateFactory>();
ISharedStateFactory ssf1 = mocks.StrictMock<ISharedStateFactory>(); ISharedStateFactory ssf2 = A.Fake<ISharedStateFactory>();
ISharedStateFactory ssf2 = mocks.StrictMock<ISharedStateFactory>(); ISharedStateFactory ssf3 = A.Fake<ISharedStateFactory>();
ISharedStateFactory ssf3 = mocks.StrictMock<ISharedStateFactory>(); ISharedStateFactory ssf4 = A.Fake<ISharedStateFactory>();
ISharedStateFactory ssf4 = mocks.StrictMock<ISharedStateFactory>();
IDictionary ssf3ProvidedState = new Hashtable(); IDictionary ssf3ProvidedState = new Hashtable();
SharedStateAwareProcessor ssap = new SharedStateAwareProcessor(); SharedStateAwareProcessor ssap = new SharedStateAwareProcessor();
ssap.SharedStateFactories = new ISharedStateFactory[] { ssf1, ssf2, ssf3, ssf4 }; ssap.SharedStateFactories = new ISharedStateFactory[] {ssf1, ssf2, ssf3, ssf4};
of.RegisterSingleton( "ssap", ssap ); of.RegisterSingleton("ssap", ssap);
ISharedStateAware ssa = (ISharedStateAware)mocks.DynamicMock( typeof( ISharedStateAware ) ); ISharedStateAware ssa = A.Fake<ISharedStateAware>();
// Ensure we iterate over configured SharedStateFactories until // Ensure we iterate over configured SharedStateFactories until
// the first provider is found that // the first provider is found that
// a) true == provider.CanProvideState( instance, name ) // a) true == provider.CanProvideState( instance, name )
// b) null != provider.GetSharedState( instance, name ) // b) null != provider.GetSharedState( instance, name )
using (Record( mocks )) A.CallTo(() => ssa.SharedState).Returns(null).Once();
{ A.CallTo(() => ssf1.CanProvideState(ssa, "pageName")).Returns(false).Once();
Expect.Call( ssa.SharedState ).Return( null ); A.CallTo(() => ssf2.CanProvideState(ssa, "pageName")).Returns(true).Once();
Expect.Call( ssf1.CanProvideState( ssa, "pageName" ) ).Return( false ); A.CallTo(() => ssf2.GetSharedStateFor(ssa, "pageName")).Returns(null);
Expect.Call( ssf2.CanProvideState( ssa, "pageName" ) ).Return( true ); A.CallTo(() => ssf3.CanProvideState(ssa, "pageName")).Returns(true).Once();
Expect.Call( ssf2.GetSharedStateFor( ssa, "pageName" ) ).Return( null ); A.CallTo(() => ssf3.GetSharedStateFor(ssa, "pageName")).Returns(ssf3ProvidedState).Once();
Expect.Call( ssf3.CanProvideState( ssa, "pageName" ) ).Return( true );
Expect.Call( ssf3.GetSharedStateFor( ssa, "pageName" ) ).Return( ssf3ProvidedState );
Expect.Call( ssa.SharedState = ssf3ProvidedState );
}
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;
using System.Collections; using System.Collections;
using FakeItEasy;
using NUnit.Framework; using NUnit.Framework;
using Rhino.Mocks;
using Spring.Collections; using Spring.Collections;
using Spring.Context.Support; using Spring.Context.Support;
using Spring.Core.TypeResolution; using Spring.Core.TypeResolution;
@@ -37,14 +39,12 @@ namespace Spring.Objects.Factory.Config
[TestFixture] [TestFixture]
public class TypeAliasConfigurerTests public class TypeAliasConfigurerTests
{ {
private MockRepository mocks;
private IConfigurableListableObjectFactory factory; private IConfigurableListableObjectFactory factory;
[SetUp] [SetUp]
public void SetUp() public void SetUp()
{ {
mocks = new MockRepository(); factory = A.Fake<IConfigurableListableObjectFactory>();
factory = mocks.StrictMock<IConfigurableListableObjectFactory>();
} }
[Test] [Test]

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -18,14 +18,12 @@
#endregion #endregion
#region Imports
using System; 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 namespace Spring.Objects.Factory.Support
{ {
@@ -36,44 +34,36 @@ namespace Spring.Objects.Factory.Support
[TestFixture] [TestFixture]
public sealed class ObjectDefinitionReaderUtilsTests public sealed class ObjectDefinitionReaderUtilsTests
{ {
private MockRepository mocks;
private IObjectDefinitionRegistry registry; private IObjectDefinitionRegistry registry;
private IObjectDefinition definition; private IObjectDefinition definition;
[SetUp] [SetUp]
public void SetUp() public void SetUp()
{ {
mocks = new MockRepository(); registry = A.Fake<IObjectDefinitionRegistry>();
registry = mocks.StrictMock<IObjectDefinitionRegistry>(); definition = A.Fake<IObjectDefinition>();
definition = mocks.StrictMock<IObjectDefinition>();
} }
[Test] [Test]
public void RegisterObjectDefinitionSunnyDay() public void RegisterObjectDefinitionSunnyDay()
{ {
registry.RegisterObjectDefinition(null, null);
LastCall.IgnoreArguments();
mocks.ReplayAll();
ObjectDefinitionHolder holder = new ObjectDefinitionHolder(definition, "foo"); ObjectDefinitionHolder holder = new ObjectDefinitionHolder(definition, "foo");
ObjectDefinitionReaderUtils.RegisterObjectDefinition(holder, registry); ObjectDefinitionReaderUtils.RegisterObjectDefinition(holder, registry);
mocks.VerifyAll();
A.CallTo(() => registry.RegisterObjectDefinition(null, null)).WithAnyArguments().MustHaveHappened();
} }
[Test] [Test]
public void RegisterObjectDefinitionSunnyDayWithAliases() 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"}); ObjectDefinitionHolder holder = new ObjectDefinitionHolder(definition, "foo", new string[] {"bar", "baz"});
ObjectDefinitionReaderUtils.RegisterObjectDefinition(holder, registry); 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] [Test]
@@ -101,24 +91,12 @@ namespace Spring.Objects.Factory.Support
registry.RegisterObjectDefinition("foo", definition); registry.RegisterObjectDefinition("foo", definition);
// we assume that some other object defition has already been associated with this alias... // we assume that some other object defition has already been associated with this alias...
registry.RegisterAlias(null, null); A.CallTo(() => registry.RegisterAlias(null, null)).WithAnyArguments().Throws<ObjectDefinitionStoreException>();
LastCall.IgnoreArguments().Throw(new ObjectDefinitionStoreException());
mocks.ReplayAll();
ObjectDefinitionHolder holder ObjectDefinitionHolder holder
= new ObjectDefinitionHolder(definition, "foo", new string[] { "bing" }); = new ObjectDefinitionHolder(definition, "foo", new string[] {"bing"});
try Assert.Throws<ObjectDefinitionStoreException>(() => ObjectDefinitionReaderUtils.RegisterObjectDefinition(holder, registry));
{
ObjectDefinitionReaderUtils.RegisterObjectDefinition(holder, registry);
Assert.Fail("Must have thrown an ObjectDefinitionStoreException store by this point.");
}
catch (ObjectDefinitionStoreException)
{
// expected...
}
mocks.VerifyAll();
} }
[Test] [Test]
@@ -130,7 +108,7 @@ namespace Spring.Objects.Factory.Support
[Test] [Test]
public void GenerateObjectNameWithNullRegistry() 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 #endregion
#region Imports
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
@@ -31,9 +29,10 @@ using System.Threading;
using System.Web.Services; using System.Web.Services;
using Common.Logging; using Common.Logging;
using Common.Logging.Simple; using Common.Logging.Simple;
using NUnit.Framework;
using Rhino.Mocks; using FakeItEasy;
using NUnit.Framework;
using Spring.Core.IO; using Spring.Core.IO;
using Spring.Core.TypeResolution; using Spring.Core.TypeResolution;
@@ -42,10 +41,8 @@ using Spring.Objects.Factory.Config;
using Spring.Objects.Factory.Support; using Spring.Objects.Factory.Support;
using Spring.Util; using Spring.Util;
#endregion
namespace Spring.Objects.Factory.Xml namespace Spring.Objects.Factory.Xml
{ {
/// <summary> /// <summary>
/// Unit tests for the XmlObjectFactory class. /// Unit tests for the XmlObjectFactory class.
/// </summary> /// </summary>
@@ -59,8 +56,6 @@ namespace Spring.Objects.Factory.Xml
[TestFixture] [TestFixture]
public sealed class XmlObjectFactoryTests public sealed class XmlObjectFactoryTests
{ {
private MockRepository mocks;
/// <summary> /// <summary>
/// The setup logic executed before the execution of this test fixture. /// The setup logic executed before the execution of this test fixture.
/// </summary> /// </summary>
@@ -75,7 +70,6 @@ namespace Spring.Objects.Factory.Xml
[SetUp] [SetUp]
public void SetUp() public void SetUp()
{ {
mocks = new MockRepository();
} }
[Test] [Test]
@@ -573,25 +567,25 @@ namespace Spring.Objects.Factory.Xml
xof.GetObject("innerObject"); xof.GetObject("innerObject");
TestObject hasInnerObjects = (TestObject) xof.GetObject("hasInnerObjects"); TestObject hasInnerObjects = (TestObject) xof.GetObject("hasInnerObjects");
Assert.AreEqual(5, hasInnerObjects.Age); Assert.AreEqual(5, hasInnerObjects.Age);
TestObject inner1 = (TestObject) hasInnerObjects.Spouse; TestObject inner1 = (TestObject) hasInnerObjects.Spouse;
Assert.IsNotNull(inner1); Assert.IsNotNull(inner1);
Assert.AreEqual("Spring.Objects.TestObject#", inner1.ObjectName.Substring(0, inner1.ObjectName.IndexOf("#")+1)); Assert.AreEqual("Spring.Objects.TestObject#", inner1.ObjectName.Substring(0, inner1.ObjectName.IndexOf("#")+1));
Assert.AreEqual("inner1", inner1.Name); Assert.AreEqual("inner1", inner1.Name);
Assert.AreEqual(6, inner1.Age); Assert.AreEqual(6, inner1.Age);
Assert.IsNotNull(hasInnerObjects.Friends); Assert.IsNotNull(hasInnerObjects.Friends);
IList friends = (IList) hasInnerObjects.Friends; IList friends = (IList) hasInnerObjects.Friends;
Assert.AreEqual(2, friends.Count); Assert.AreEqual(2, friends.Count);
DerivedTestObject inner2 = (DerivedTestObject) friends[0]; DerivedTestObject inner2 = (DerivedTestObject) friends[0];
Assert.AreEqual("inner2", inner2.Name); Assert.AreEqual("inner2", inner2.Name);
Assert.AreEqual(7, inner2.Age); 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]; TestObject innerFactory = (TestObject) friends[1];
Assert.AreEqual(DummyFactory.SINGLETON_NAME, innerFactory.Name); Assert.AreEqual(DummyFactory.SINGLETON_NAME, innerFactory.Name);
Assert.IsNotNull(hasInnerObjects.SomeMap); Assert.IsNotNull(hasInnerObjects.SomeMap);
Assert.IsFalse((hasInnerObjects.SomeMap.Count == 0)); Assert.IsFalse((hasInnerObjects.SomeMap.Count == 0));
TestObject inner3 = (TestObject) hasInnerObjects.SomeMap["someKey"]; TestObject inner3 = (TestObject) hasInnerObjects.SomeMap["someKey"];
@@ -636,11 +630,11 @@ namespace Spring.Objects.Factory.Xml
Assert.AreEqual("inner3", inner3.Name); Assert.AreEqual("inner3", inner3.Name);
Assert.AreEqual(8, inner3.Age); Assert.AreEqual(8, inner3.Age);
xof.Dispose(); xof.Dispose();
Assert.IsFalse(inner2.WasDestroyed()); Assert.IsFalse(inner2.WasDestroyed());
Assert.IsFalse(innerFactory.Name == null); Assert.IsFalse(innerFactory.Name == null);
Assert.IsFalse(innerFriendOfAFriend.WasDestroyed()); Assert.IsFalse(innerFriendOfAFriend.WasDestroyed());
} }
[Test] [Test]
@@ -661,7 +655,7 @@ namespace Spring.Objects.Factory.Xml
public void SingletonInheritanceFromParentFactorySingletonUsingCtor() public void SingletonInheritanceFromParentFactorySingletonUsingCtor()
{ {
XmlObjectFactory parent = new XmlObjectFactory(new ReadOnlyXmlTestResource("parent.xml", GetType())); 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"); TestObject inherits = (TestObject)child.GetObject("inheritsFromParentFactoryUsingCtor");
// Name property value is overriden // Name property value is overriden
Assert.IsTrue(inherits.Name.Equals("child-name")); 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()); IResource resource = new ReadOnlyXmlTestResource("lazy-init-multithreaded.xml", GetType());
XmlObjectFactory xof = new XmlObjectFactory(resource); XmlObjectFactory xof = new XmlObjectFactory(resource);
LazyWorker lw1 = new LazyWorker(xof); LazyWorker lw1 = new LazyWorker(xof);
LazyWorker lw2 = new LazyWorker(xof); LazyWorker lw2 = new LazyWorker(xof);
Thread thread1 = new Thread(new ThreadStart(lw1.DoWork)); Thread thread1 = new Thread(new ThreadStart(lw1.DoWork));
Thread thread2 = new Thread(new ThreadStart(lw2.DoWork)); Thread thread2 = new Thread(new ThreadStart(lw2.DoWork));
thread1.Start(); thread1.Start();
Thread.Sleep(1000); Thread.Sleep(1000);
thread2.Start(); thread2.Start();
thread1.Join(); thread1.Join();
thread2.Join(); thread2.Join();
Assert.AreEqual(typeof(LazyTestObject), lw1.ObjectFromContext.GetType()); Assert.AreEqual(typeof(LazyTestObject), lw1.ObjectFromContext.GetType());
Assert.AreEqual(typeof(LazyTestObject), lw2.ObjectFromContext.GetType()); Assert.AreEqual(typeof(LazyTestObject), lw2.ObjectFromContext.GetType());
Assert.AreEqual(1, LazyTestObject.Count); Assert.AreEqual(1, LazyTestObject.Count);
@@ -1027,7 +1021,7 @@ namespace Spring.Objects.Factory.Xml
Assert.IsTrue(ex.InnerException is FormatException); Assert.IsTrue(ex.InnerException is FormatException);
} }
} }
[Test] [Test]
public void NoSuchXmlFile() public void NoSuchXmlFile()
{ {
@@ -1057,7 +1051,7 @@ namespace Spring.Objects.Factory.Xml
XmlObjectDefinitionReader reader = new XmlObjectDefinitionReader(xof, null); XmlObjectDefinitionReader reader = new XmlObjectDefinitionReader(xof, null);
try try
{ {
reader.LoadObjectDefinitions(new ReadOnlyXmlTestResource("invalid.xml", GetType())); reader.LoadObjectDefinitions(new ReadOnlyXmlTestResource("invalid.xml", GetType()));
Assert.Fail("Should have thrown XmlObjectDefinitionStoreException"); Assert.Fail("Should have thrown XmlObjectDefinitionStoreException");
} }
catch (ObjectDefinitionStoreException e) catch (ObjectDefinitionStoreException e)
@@ -1528,15 +1522,11 @@ namespace Spring.Objects.Factory.Xml
//FactoryMethods fm = (FactoryMethods) factory.GetObject("instanceFactoryMethodOverloads", new object[] {row}); //FactoryMethods fm = (FactoryMethods) factory.GetObject("instanceFactoryMethodOverloads", new object[] {row});
// Assert.AreEqual("DataRowCtor", fm.Name); // 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 }); FactoryMethods fm = (FactoryMethods)factory.GetObject("instanceFactoryMethodOverloads", new object[] { dataRecord });
Assert.AreEqual("DataRecordCtor", fm.Name); Assert.AreEqual("DataRecordCtor", fm.Name);
} }
#region Private Helper Methods for InstanceFactoryMethodWithOverloadedargs
private DataTable MakeNamesTable() private DataTable MakeNamesTable()
{ {
// Create a new DataTable titled 'Names.' // Create a new DataTable titled 'Names.'
@@ -1569,7 +1559,6 @@ namespace Spring.Objects.Factory.Xml
return namesTable; return namesTable;
} }
#endregion
[Test] [Test]
public void FactoryMethodNoMatchingStaticMethod() public void FactoryMethodNoMatchingStaticMethod()
{ {
@@ -1689,7 +1678,7 @@ namespace Spring.Objects.Factory.Xml
/// <summary> /// <summary>
/// Test creating an object using its 1 arg boolean constructor (amongst /// 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. /// not its index number.
/// </summary> /// </summary>
[Test] [Test]
@@ -1840,7 +1829,7 @@ namespace Spring.Objects.Factory.Xml
public void TestExpressionAttribute() public void TestExpressionAttribute()
{ {
TypeRegistry.RegisterType("WebMethod", typeof(WebMethodAttribute)); TypeRegistry.RegisterType("WebMethod", typeof(WebMethodAttribute));
IResource resource = new ReadOnlyXmlTestResource("expressions.xml", GetType()); IResource resource = new ReadOnlyXmlTestResource("expressions.xml", GetType());
XmlObjectFactory xof = new XmlObjectFactory(resource); XmlObjectFactory xof = new XmlObjectFactory(resource);
@@ -1886,7 +1875,7 @@ namespace Spring.Objects.Factory.Xml
private Object objectFromContext; private Object objectFromContext;
public LazyWorker(XmlObjectFactory xof) public LazyWorker(XmlObjectFactory xof)
{ {
this.xof = xof; this.xof = xof;
} }
public void DoWork() public void DoWork()
{ {
@@ -2069,5 +2058,5 @@ namespace Spring.Objects.Factory.Xml
#endregion #endregion
} }
} }

View File

@@ -2,13 +2,13 @@
/* /*
* 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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -18,19 +18,17 @@
#endregion #endregion
#region Imports
using System; using System;
using System.Collections; using System.Collections;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Threading; using System.Threading;
using FakeItEasy;
using NUnit.Framework; using NUnit.Framework;
using Rhino.Mocks;
using Spring.Pool.Support; using Spring.Pool.Support;
using Spring.Threading; using Spring.Threading;
#endregion
namespace Spring.Pool namespace Spring.Pool
{ {
#region Inner Class : Helper #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; private SimplePool pool;
[SetUp] [SetUp]
public void SetUp() public void SetUp()
{ {
mocks = new MockRepository(); factory = A.Fake<IPoolableObjectFactory>();
factory = (IPoolableObjectFactory) mocks.DynamicMock(typeof(IPoolableObjectFactory)); A.CallTo(() => factory.MakeObject()).Returns(new object());
Expect.Call(factory.MakeObject()).Return(new object()).Repeat.Any();
mocks.ReplayAll();
pool = new SimplePool(factory, 1); pool = new SimplePool(factory, 1);
mocks.BackToRecordAll();
} }
@@ -152,85 +145,70 @@ namespace Spring.Pool
[Test] [Test]
public void ActivateOnObjectOnBorrow() public void ActivateOnObjectOnBorrow()
{ {
Expect.Call(factory.ValidateObject(null)).IgnoreArguments().Return(true).Repeat.Any(); A.CallTo(() => factory.ValidateObject(null)).WithAnyArguments().Returns(true);
factory.ActivateObject(null);
LastCall.IgnoreArguments();
mocks.ReplayAll();
Assert.AreEqual(0, pool.NumActive, "active wrong"); Assert.AreEqual(0, pool.NumActive, "active wrong");
Assert.AreEqual(1, pool.NumIdle, "idle wrong"); Assert.AreEqual(1, pool.NumIdle, "idle wrong");
pool.BorrowObject(); pool.BorrowObject();
Assert.AreEqual(1, pool.NumActive, "active wrong"); Assert.AreEqual(1, pool.NumActive, "active wrong");
Assert.AreEqual(0, pool.NumIdle, "idle wrong"); Assert.AreEqual(0, pool.NumIdle, "idle wrong");
mocks.VerifyAll();
}
// TODO fix test!!! A.CallTo(() => factory.ActivateObject(null)).WithAnyArguments().MustHaveHappened();
[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();
} }
[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.")] [Ignore("No longer expected behavior per SPRNET-1582 being resolved.")]
public void NoMoreUsableAfterClose() public void NoMoreUsableAfterClose()
{ {
object o = pool.BorrowObject();
factory.PassivateObject(o);
mocks.ReplayAll();
pool.Close(); pool.Close();
Assert.Throws<PoolException>(() => pool.BorrowObject()); 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.")] [Ignore("No longer expected behavior per SPRNET-1582 being resolved.")]
public void ThrowsExceptionWhenOutOfItemsBecauseFailedValidation() public void ThrowsExceptionWhenOutOfItemsBecauseFailedValidation()
{ {
object o = new object(); object o = new object();
Expect.Call(factory.MakeObject()).Return(o); A.CallTo(() => factory.MakeObject()).Returns(o);
Expect.Call(factory.ValidateObject(o)).Return(false); A.CallTo(() => factory.ValidateObject(o)).Returns(false);
mocks.ReplayAll();
pool = new SimplePool(factory, 1); pool = new SimplePool(factory, 1);
Assert.Throws<PoolException>(() => pool.BorrowObject()); Assert.Throws<PoolException>(() => pool.BorrowObject());
mocks.VerifyAll();
} }
[Test] [Test]
public void PassivateObjectOnReturn() public void PassivateObjectOnReturn()
{ {
Expect.Call(factory.ValidateObject(null)).IgnoreArguments().Return(true).Repeat.Any(); A.CallTo(() => factory.ValidateObject(null)).WithAnyArguments().Returns(true);
factory.PassivateObject(null);
LastCall.IgnoreArguments();
mocks.ReplayAll();
pool.ReturnObject(pool.BorrowObject()); pool.ReturnObject(pool.BorrowObject());
mocks.VerifyAll(); A.CallTo(() => factory.PassivateObject(null)).WithAnyArguments().MustHaveHappened();
} }
[Test] [Test]
public void DestroyObjectOnClose() public void DestroyObjectOnClose()
{ {
Expect.Call(factory.ValidateObject(null)).IgnoreArguments().Return(true).Repeat.Any(); A.CallTo(() => factory.ValidateObject(null)).WithAnyArguments().Returns(true);
factory.DestroyObject(null);
LastCall.IgnoreArguments();
mocks.ReplayAll();
pool.BorrowObject(); pool.BorrowObject();
pool.Close(); pool.Close();
}
[Test] A.CallTo(() => factory.DestroyObject(null)).WithAnyArguments().MustHaveHappened();
}
[Test]
public void WaitOnBorrowWhenExausted() public void WaitOnBorrowWhenExausted()
{ {
int n = 100; int n = 100;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,7 +1,7 @@
#region License #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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -18,13 +18,11 @@
#endregion #endregion
#region Imports
using System.Data; using System.Data;
using NUnit.Framework;
using Rhino.Mocks;
#endregion using FakeItEasy;
using NUnit.Framework;
namespace Spring.Data.Common namespace Spring.Data.Common
{ {
@@ -35,28 +33,13 @@ namespace Spring.Data.Common
[TestFixture] [TestFixture]
public class UserCredentialsDbProviderTests public class UserCredentialsDbProviderTests
{ {
private MockRepository mocks;
[SetUp]
public void Setup()
{
mocks = new MockRepository();
}
[Test] [Test]
public void StaticCredentials() public void StaticCredentials()
{ {
IDbProvider dbProvider = mocks.StrictMock<IDbProvider>(); IDbProvider dbProvider = A.Fake<IDbProvider>();
IDbConnection connection = mocks.StrictMock<IDbConnection>(); IDbConnection connection = A.Fake<IDbConnection>();
using (mocks.Ordered()) A.CallTo(() => dbProvider.CreateConnection()).Returns(connection);
{ A.CallTo(() => dbProvider.ConnectionString).Returns(@"Data Source=MARKT60\SQL2005;Database=Spring;Trusted_Connection=False");
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();
UserCredentialsDbProvider provider = new UserCredentialsDbProvider(); UserCredentialsDbProvider provider = new UserCredentialsDbProvider();
provider.TargetDbProvider = dbProvider; provider.TargetDbProvider = dbProvider;
@@ -64,50 +47,39 @@ namespace Spring.Data.Common
provider.Password = "Password=springqa"; provider.Password = "Password=springqa";
Assert.AreEqual(connection, provider.CreateConnection()); 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] [Test]
public void NoCredentials() public void NoCredentials()
{ {
IDbProvider dbProvider = mocks.StrictMock<IDbProvider>(); IDbProvider dbProvider = A.Fake<IDbProvider>();
IDbConnection connection = mocks.StrictMock<IDbConnection>(); IDbConnection connection = A.Fake<IDbConnection>();
using (mocks.Ordered()) A.CallTo(() => dbProvider.CreateConnection()).Returns(connection);
{
Expect.Call(dbProvider.CreateConnection()).Return(connection);
}
mocks.ReplayAll();
UserCredentialsDbProvider provider = new UserCredentialsDbProvider(); UserCredentialsDbProvider provider = new UserCredentialsDbProvider();
provider.TargetDbProvider = dbProvider; provider.TargetDbProvider = dbProvider;
Assert.AreEqual(connection, provider.CreateConnection()); Assert.AreEqual(connection, provider.CreateConnection());
mocks.VerifyAll();
} }
[Test] [Test]
public void ThreadBoundCredentials() public void ThreadBoundCredentials()
{ {
IDbProvider dbProvider = mocks.StrictMock<IDbProvider>(); IDbProvider dbProvider = A.Fake<IDbProvider>();
IDbConnection connection = mocks.StrictMock<IDbConnection>(); IDbConnection connection = A.Fake<IDbConnection>();
using (mocks.Ordered()) A.CallTo(() => dbProvider.CreateConnection()).Returns(connection);
{ A.CallTo(() => dbProvider.ConnectionString).Returns(@"Data Source=MARKT60\SQL2005;Database=Spring;Trusted_Connection=False");
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();
UserCredentialsDbProvider provider = new UserCredentialsDbProvider(); UserCredentialsDbProvider provider = new UserCredentialsDbProvider();
provider.TargetDbProvider = dbProvider; provider.TargetDbProvider = dbProvider;
provider.SetCredentialsForCurrentThread("User ID=springqa", "Password=springqa"); provider.SetCredentialsForCurrentThread("User ID=springqa", "Password=springqa");
Assert.AreEqual(connection, provider.CreateConnection()); 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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,20 +14,17 @@
* limitations under the License. * limitations under the License.
*/ */
#endregion
#region Imports
using System; using System;
using System.EnterpriseServices; using System.EnterpriseServices;
using FakeItEasy;
using NUnit.Framework; using NUnit.Framework;
using Rhino.Mocks;
using Spring.Data.Support; using Spring.Data.Support;
using Spring.Transaction; using Spring.Transaction;
using Spring.Transaction.Support; using Spring.Transaction.Support;
#endregion
namespace Spring.Data.Core namespace Spring.Data.Core
{ {
/// <summary> /// <summary>
@@ -39,53 +34,33 @@ namespace Spring.Data.Core
[TestFixture] [TestFixture]
public class ServiceDomainTransactionManagerTests public class ServiceDomainTransactionManagerTests
{ {
private MockRepository mocks;
[SetUp]
public void Setup()
{
mocks = new MockRepository();
}
[Test] [Test]
public void TransactionCommit() public void TransactionCommit()
{ {
#region Mock Setup IServiceDomainAdapter txAdapter = A.Fake<IServiceDomainAdapter>();
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);
//ProcessCommit - status.GlobalRollbackOnly check A.CallTo(() => txAdapter.IsInTransaction).Returns(false).Once().Then.Returns(true).Once();
Expect.Call(txAdapter.MyTransactionVote).Return(TransactionVote.Commit);
//DoCommit - status.GlobalRollbackOnly check
Expect.Call(txAdapter.MyTransactionVote).Return(TransactionVote.Commit);
Expect.Call(txAdapter.IsInTransaction).Return(true); //ProcessCommit - status.GlobalRollbackOnly check
//DoCommit - check to call SetComplete or SetAbort //DoCommit - status.GlobalRollbackOnly check
Expect.Call(txAdapter.MyTransactionVote).Return(TransactionVote.Commit); //DoCommit - check to call SetComplete or SetAbort
txAdapter.SetComplete(); A.CallTo(() => txAdapter.MyTransactionVote).Returns(TransactionVote.Commit).NumberOfTimes(3);
Expect.Call(txAdapter.Leave()).Return(TransactionStatus.Commited);
} A.CallTo(() => txAdapter.Leave()).Returns(TransactionStatus.Commited).Once();
#endregion
mocks.ReplayAll();
ServiceDomainPlatformTransactionManager tm = new ServiceDomainPlatformTransactionManager(txAdapter); ServiceDomainPlatformTransactionManager tm = new ServiceDomainPlatformTransactionManager(txAdapter);
TransactionTemplate tt = new TransactionTemplate(tm); TransactionTemplate tt = new TransactionTemplate(tm);
tm.TransactionSynchronization = TransactionSynchronizationState.Always; tm.TransactionSynchronization = TransactionSynchronizationState.Always;
tt.Execute(new TransactionDelegate(TransactionCommitMethod)); tt.Execute(TransactionCommitMethod);
Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive); Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive);
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); 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) private object TransactionCommitMethod(ITransactionStatus status)
@@ -98,23 +73,13 @@ namespace Spring.Data.Core
[Test] [Test]
public void TransactionRollback() 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();
SimpleServiceConfig serviceConfig = new SimpleServiceConfig(); ConfigureServiceConfig(serviceConfig, standardIsolationAndProp: true);
ConfigureServiceConfig(serviceConfig, true);
txAdapter.Enter(serviceConfig);
Expect.Call(txAdapter.IsInTransaction).Return(true);
txAdapter.SetAbort();
Expect.Call(txAdapter.Leave()).Return(TransactionStatus.Commited);
} IServiceDomainAdapter txAdapter = A.Fake<IServiceDomainAdapter>();
#endregion A.CallTo(() => txAdapter.IsInTransaction).Returns(false).Once().Then.Returns(true);
A.CallTo(() => txAdapter.Leave()).Returns(TransactionStatus.Commited);
mocks.ReplayAll();
ServiceDomainPlatformTransactionManager tm = new ServiceDomainPlatformTransactionManager(txAdapter); ServiceDomainPlatformTransactionManager tm = new ServiceDomainPlatformTransactionManager(txAdapter);
tm.TransactionSynchronization = TransactionSynchronizationState.Always; tm.TransactionSynchronization = TransactionSynchronizationState.Always;
@@ -136,53 +101,25 @@ namespace Spring.Data.Core
Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active"); Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");
A.CallTo(() => txAdapter.SetAbort()).MustHaveHappenedOnceExactly();
mocks.VerifyAll(); A.CallTo(() => txAdapter.Enter(serviceConfig)).MustHaveHappenedOnceExactly();
} }
[Test] [Test]
public void PropagationRequiresNewWithExistingTransaction() public void PropagationRequiresNewWithExistingTransaction()
{ {
#region Mock Setup IServiceDomainAdapter txAdapter = A.Fake<IServiceDomainAdapter>();
IServiceDomainAdapter txAdapter = (IServiceDomainAdapter)mocks.CreateMock(typeof(IServiceDomainAdapter));
using (mocks.Ordered())
{
Expect.Call(txAdapter.IsInTransaction).Return(false); A.CallTo(() => txAdapter.IsInTransaction)
SimpleServiceConfig serviceConfig = new SimpleServiceConfig(); .Returns(false).Once()
ConfigureServiceConfig(serviceConfig, true); .Then.Returns(true).NumberOfTimes(3);
txAdapter.Enter(serviceConfig);
A.CallTo(() => txAdapter.Leave())
.Returns(TransactionStatus.Aborted).Once()
.Then.Returns(TransactionStatus.Commited).Once();
Expect.Call(txAdapter.IsInTransaction).Return(true); A.CallTo(() => txAdapter.MyTransactionVote).Returns(TransactionVote.Commit).NumberOfTimes(3);
// 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();
ServiceDomainPlatformTransactionManager tm = new ServiceDomainPlatformTransactionManager(txAdapter); ServiceDomainPlatformTransactionManager tm = new ServiceDomainPlatformTransactionManager(txAdapter);
tm.TransactionSynchronization = TransactionSynchronizationState.Always; tm.TransactionSynchronization = TransactionSynchronizationState.Always;
@@ -190,10 +127,22 @@ namespace Spring.Data.Core
TransactionTemplate tt = new TransactionTemplate(tm); TransactionTemplate tt = new TransactionTemplate(tm);
tt.PropagationBehavior = TransactionPropagation.RequiresNew; tt.PropagationBehavior = TransactionPropagation.RequiresNew;
tt.Execute(new PropagationRequiresNewWithExistingTransactionCallbackSD(tt)); 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) private SimpleServiceConfig ConfigureServiceConfig(SimpleServiceConfig serviceConfig, bool standardIsolationAndProp)
{ {
serviceConfig.TransactionDescription = null; serviceConfig.TransactionDescription = null;
@@ -206,14 +155,11 @@ namespace Spring.Data.Core
serviceConfig.TransactionOption = TransactionOption.Required; serviceConfig.TransactionOption = TransactionOption.Required;
serviceConfig.IsolationLevel = TransactionIsolationLevel.ReadCommitted; serviceConfig.IsolationLevel = TransactionIsolationLevel.ReadCommitted;
} }
return serviceConfig; return serviceConfig;
} }
#endregion
#region Supporting class for TransactionRollback test
internal class TransactionRollbackTxCallback : ITransactionCallback internal class TransactionRollbackTxCallback : ITransactionCallback
{ {
private Exception exception; private Exception exception;
@@ -232,9 +178,6 @@ namespace Spring.Data.Core
} }
} }
#endregion
#region Supporting class for PropagationRequiresNewWithExistingTransactionCallback test
internal class PropagationRequiresNewWithExistingTransactionCallbackSD : ITransactionCallback internal class PropagationRequiresNewWithExistingTransactionCallbackSD : ITransactionCallback
{ {
private TransactionTemplate tt; private TransactionTemplate tt;
@@ -264,12 +207,8 @@ namespace Spring.Data.Core
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive); Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive);
status.SetRollbackOnly(); status.SetRollbackOnly();
return null; return null;
} }
} }
#endregion
} }
}
}

View File

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

View File

@@ -1,7 +1,7 @@
#region License #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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -18,91 +18,68 @@
#endregion #endregion
#region Imports
using System; using System;
using System.Transactions; using System.Transactions;
using FakeItEasy;
using NUnit.Framework; using NUnit.Framework;
using Rhino.Mocks;
using Spring.Data.Support; using Spring.Data.Support;
using Spring.Transaction; using Spring.Transaction;
using Spring.Transaction.Support; using Spring.Transaction.Support;
#endregion
namespace Spring.Data.Core namespace Spring.Data.Core
{ {
/// <summary> /// <summary>
/// This calss contains tests for /// This calss contains tests for
/// </summary> /// </summary>
/// <author>Mark Pollack</author> /// <author>Mark Pollack</author>
[TestFixture] [TestFixture]
public class TxScopeTransactionManagerTests public class TxScopeTransactionManagerTests
{ {
private MockRepository mocks;
[SetUp]
public void Setup()
{
mocks = new MockRepository();
}
[Test] [Test]
public void TransactionCommit() public void TransactionCommit()
{ {
ITransactionScopeAdapter txAdapter = (ITransactionScopeAdapter) mocks.CreateMock(typeof(ITransactionScopeAdapter)); ITransactionScopeAdapter txAdapter = A.Fake<ITransactionScopeAdapter>();
A.CallTo(() => txAdapter.IsExistingTransaction).Returns(false);
using (mocks.Ordered()) A.CallTo(() => txAdapter.RollbackOnly).Returns(false);
{
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();
TxScopeTransactionManager tm = new TxScopeTransactionManager(txAdapter); TxScopeTransactionManager tm = new TxScopeTransactionManager(txAdapter);
tm.TransactionSynchronization = TransactionSynchronizationState.Always; tm.TransactionSynchronization = TransactionSynchronizationState.Always;
TransactionTemplate tt = new TransactionTemplate(tm); TransactionTemplate tt = new TransactionTemplate(tm);
tt.Execute(status => tt.Execute(status =>
{ {
Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive); Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive);
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
return null; return null;
}); });
Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive); Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive);
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
mocks.VerifyAll();
TransactionOptions txOptions = new TransactionOptions();
txOptions.IsolationLevel = IsolationLevel.ReadCommitted;
txAdapter.CreateTransactionScope(TransactionScopeOption.Required, txOptions, EnterpriseServicesInteropOption.None);
txAdapter.Complete();
txAdapter.Dispose();
} }
[Test] [Test]
public void TransactionRollback() public void TransactionRollback()
{ {
ITransactionScopeAdapter txAdapter = (ITransactionScopeAdapter)mocks.CreateMock(typeof(ITransactionScopeAdapter)); ITransactionScopeAdapter txAdapter = A.Fake<ITransactionScopeAdapter>();
using (mocks.Ordered()) A.CallTo(() => txAdapter.IsExistingTransaction).Returns(false);
{ TransactionOptions txOptions = new TransactionOptions();
Expect.Call(txAdapter.IsExistingTransaction).Return(false); txOptions.IsolationLevel = IsolationLevel.ReadCommitted;
TransactionOptions txOptions = new TransactionOptions();
txOptions.IsolationLevel = IsolationLevel.ReadCommitted;
txAdapter.CreateTransactionScope(TransactionScopeOption.Required, txOptions, EnterpriseServicesInteropOption.None);
txAdapter.Dispose();
}
mocks.ReplayAll();
TxScopeTransactionManager tm = new TxScopeTransactionManager(txAdapter); TxScopeTransactionManager tm = new TxScopeTransactionManager(txAdapter);
tm.TransactionSynchronization = TransactionSynchronizationState.Always; tm.TransactionSynchronization = TransactionSynchronizationState.Always;
TransactionTemplate tt = new TransactionTemplate(tm); TransactionTemplate tt = new TransactionTemplate(tm);
Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active"); Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");
@@ -111,13 +88,13 @@ namespace Spring.Data.Core
try try
{ {
tt.Execute(status => tt.Execute(status =>
{ {
Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive); Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive);
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
Assert.IsTrue(status.IsNewTransaction, "Is new transaction"); Assert.IsTrue(status.IsNewTransaction, "Is new transaction");
if (ex != null) throw ex; if (ex != null) throw ex;
return null; return null;
}); });
Assert.Fail("Should have thrown exception"); Assert.Fail("Should have thrown exception");
} }
catch (ArgumentException e) catch (ArgumentException e)
@@ -126,36 +103,24 @@ namespace Spring.Data.Core
} }
Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active"); Assert.IsTrue(!TransactionSynchronizationManager.SynchronizationActive, "Synchronizations not active");
A.CallTo(() => txAdapter.CreateTransactionScope(TransactionScopeOption.Required, txOptions, EnterpriseServicesInteropOption.None)).MustHaveHappenedOnceExactly();
A.CallTo(() => txAdapter.Dispose()).MustHaveHappenedOnceExactly();
mocks.VerifyAll();
} }
[Test] [Test]
public void PropagationRequiresNewWithExistingTransaction() 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()) //inner tx actions
{ A.CallTo(() => txAdapter.IsExistingTransaction).Returns(true).Once();
Expect.Call(txAdapter.IsExistingTransaction).Return(false); //end inner tx actions
TransactionOptions txOptions = new TransactionOptions();
txOptions.IsolationLevel = IsolationLevel.ReadCommitted;
txAdapter.CreateTransactionScope(TransactionScopeOption.RequiresNew, txOptions, EnterpriseServicesInteropOption.None);
//inner tx actions A.CallTo(() => txAdapter.RollbackOnly).Returns(false);
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();
TxScopeTransactionManager tm = new TxScopeTransactionManager(txAdapter); TxScopeTransactionManager tm = new TxScopeTransactionManager(txAdapter);
tm.TransactionSynchronization = TransactionSynchronizationState.Always; tm.TransactionSynchronization = TransactionSynchronizationState.Always;
@@ -163,30 +128,32 @@ namespace Spring.Data.Core
TransactionTemplate tt = new TransactionTemplate(tm); TransactionTemplate tt = new TransactionTemplate(tm);
tt.PropagationBehavior = TransactionPropagation.RequiresNew; tt.PropagationBehavior = TransactionPropagation.RequiresNew;
tt.Execute(status => tt.Execute(status =>
{ {
Assert.IsTrue(status.IsNewTransaction, "Is new transaction"); Assert.IsTrue(status.IsNewTransaction, "Is new transaction");
Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive, "Synchronization active"); Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive, "Synchronization active");
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive); Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive);
tt.Execute(status2 => tt.Execute(status2 =>
{ {
Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive, "Synchronization active"); Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive, "Synchronization active");
Assert.IsTrue(status2.IsNewTransaction, "Is new transaction"); Assert.IsTrue(status2.IsNewTransaction, "Is new transaction");
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive); Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive);
status2.SetRollbackOnly(); status2.SetRollbackOnly();
return null; return null;
}); });
Assert.IsTrue(status.IsNewTransaction, "Is new transaction"); Assert.IsTrue(status.IsNewTransaction, "Is new transaction");
Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly);
Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive); Assert.IsTrue(TransactionSynchronizationManager.ActualTransactionActive);
return null; 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 #endregion
using System.Data; using System.Data;
using Rhino.Mocks;
using FakeItEasy;
using Spring.Data.Common; using Spring.Data.Common;
namespace Spring.Data.Objects namespace Spring.Data.Objects
@@ -34,26 +36,26 @@ namespace Spring.Data.Objects
public void SetUpMocks() public void SetUpMocks()
{ {
provider = MockRepository.GenerateMock<IDbProvider>(); provider = A.Fake<IDbProvider>();
IDbConnection connection = MockRepository.GenerateMock<IDbConnection>(); 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) // Creating a query (setting DbProvider property)
// will call new DbParameters(IDbProvider), which is a real pain to mock. // will call new DbParameters(IDbProvider), which is a real pain to mock.
// to store the declared parameters. // 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. //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 //Create a real instance of IDbParameters to stored the declared parameters
IDbProvider realDbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient"); IDbProvider realDbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient");
IDbParameters dbParameters = new DbParameters(realDbProvider); IDbParameters dbParameters = new DbParameters(realDbProvider);
//Pass real instance into mock instance. //Pass real instance into mock instance.
command.Stub(x => x.Parameters).Return(dbParameters.DataParameterCollection).Repeat.Once(); A.CallTo(() => command.Parameters).Returns(dbParameters.DataParameterCollection).Once();
provider.Stub(x => x.CreateCommand()).Return(command).Repeat.Once(); A.CallTo(() => provider.CreateCommand()).Returns(command).Once();
// done with init of DbParameters mock/stubbing // done with init of DbParameters mock/stubbing
} }

View File

@@ -1,7 +1,7 @@
#region License #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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -21,14 +21,14 @@
#region License #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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -44,9 +44,9 @@ using System.Collections;
using System.Data; using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using NUnit.Framework; using FakeItEasy;
using Rhino.Mocks; using NUnit.Framework;
using Spring.Dao; using Spring.Dao;
using Spring.Data.Common; using Spring.Data.Common;
@@ -75,12 +75,11 @@ namespace Spring.Data.Objects
[Test] [Test]
public void MappingAdoQueryWithContextWithoutParams() public void MappingAdoQueryWithContextWithoutParams()
{ {
IDataReader reader = MockRepository.GenerateMock<IDataReader>(); IDataReader reader = A.Fake<IDataReader>();
reader.Stub(x => x.Read()).Return(true).Repeat.Once(); A.CallTo(() => reader.Read()).Returns(true).Once().Then.Returns(false);
reader.Stub(x => x.GetInt32(0)).Return(1).Repeat.Once(); A.CallTo(() => reader.GetInt32(0)).Returns(1).Once();
reader.Stub(x => x.Read()).Return(false).Repeat.Once();
command.Stub(x => x.ExecuteReader()).Return(reader); A.CallTo(() => command.ExecuteReader()).Returns(reader);
IntMappingQueryWithContext queryWithNoContext = new IntMappingQueryWithContext(provider); IntMappingQueryWithContext queryWithNoContext = new IntMappingQueryWithContext(provider);
queryWithNoContext.Compile(); queryWithNoContext.Compile();
@@ -95,13 +94,10 @@ namespace Spring.Data.Objects
[Test] [Test]
public void QueryWithoutEnoughParams() public void QueryWithoutEnoughParams()
{ {
SqlParameter sqlParameter1 = new SqlParameter(); A.CallTo(() => command.CreateParameter()).ReturnsLazily(() => 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();
SqlParameter sqlParameter2 = new SqlParameter(); A.CallTo(() => provider.CreateParameterNameForCollection(COLUMN_NAMES[0])).Returns("@" + COLUMN_NAMES[0]).Once();
command.Stub(x => x.CreateParameter()).Return(sqlParameter2); A.CallTo(() => provider.CreateParameterNameForCollection(COLUMN_NAMES[1])).Returns("@" + COLUMN_NAMES[1]);
provider.Stub(x => x.CreateParameterNameForCollection(COLUMN_NAMES[1])).Return("@" + COLUMN_NAMES[1]);
IntMappingAdoQuery query = new IntMappingAdoQuery(); IntMappingAdoQuery query = new IntMappingAdoQuery();
query.DbProvider = provider; query.DbProvider = provider;

View File

@@ -1,7 +1,7 @@
#region License #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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -21,14 +21,14 @@
#region License #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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -38,19 +38,15 @@
#endregion #endregion
#region Imports
using System.Data; using System.Data;
using System.Data.SqlClient; using System.Data.SqlClient;
using FakeItEasy;
using NUnit.Framework; using NUnit.Framework;
using Rhino.Mocks;
using Spring.Data.Common; using Spring.Data.Common;
#endregion
namespace Spring.Data.Objects namespace Spring.Data.Objects
{ {
/// <summary> /// <summary>
@@ -70,15 +66,14 @@ namespace Spring.Data.Objects
public void NullArg() public void NullArg()
{ {
SqlParameter sqlParameter1 = new SqlParameter(); SqlParameter sqlParameter1 = new SqlParameter();
command.Stub(x => x.CreateParameter()).Return(sqlParameter1); A.CallTo(() => command.CreateParameter()).Returns(sqlParameter1);
provider.Stub(x => x.CreateParameterNameForCollection("ptest")).Return("@ptest"); A.CallTo(() => provider.CreateParameterNameForCollection("ptest")).Returns("@ptest");
//Create a real instance of IDbParameters to store the executable parameters //Create a real instance of IDbParameters to store the executable parameters
//IDbProvider realDbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient"); //IDbProvider realDbProvider = DbProviderFactory.GetDbProvider("System.Data.SqlClient");
//IDbParameters dbParameters = new DbParameters(realDbProvider); //IDbParameters dbParameters = new DbParameters(realDbProvider);
IDataParameterCollection dbParamCollection = new SqlCommand().Parameters;
//provide the same instance to another call to extract output params //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); NullArg na = new NullArg(provider);
na.Execute(null); na.Execute(null);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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