.NET—Spring.NET保持数据现场测试

本文介绍了一个使用Spring.NET框架进行事务管理的测试案例,通过NUnit进行单元测试,重点展示了如何配置事务传播行为并验证其正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. .NET—Spring.NET保持数据现场测试
    解:
    这个版本提供两种方式进行测试:1、破坏现场测试;2、恢复现场测试
    Nunit2.5.5与VS2008集成
    赵海燕
    20160625
    关键点,配置文件实现bean注入初始化,AdoTemplate可以直接取数据库数据,前一个实现控制反转,后一个是ADO.NET的封装。
    1.1 项目地址:
    Svn项目地址:
    https://cyberzhaohyVM/svn/SmartCode/Spring.NET保持数据现场测试20160625
    1.2 项目结构:
    这里写图片描述

1.3 AccountManager
黄色为启动事务;构造函数时注入。

using System;
using System.Data;
using Spring.Transaction;
using Spring.Transaction.Interceptor;
using Spring.TxQuickStart.Dao;

namespace Spring.TxQuickStart.Services
{
public class AccountManager : IAccountManager
{

    private IAccountCreditDao accountCreditDao;
    private IAccountDebitDao accountDebitDao;

    private float maxTransferAmount = 1000000;

    public AccountManager(IAccountCreditDao accountCreditDao, IAccountDebitDao accountDebitDao)
    {
        this.accountCreditDao = accountCreditDao;
        this.accountDebitDao = accountDebitDao;
    }

    public float MaxTransferAmount
    {
        get { return maxTransferAmount; }
        set { maxTransferAmount = value; }
    }


    // The following rollback rule will result in commiting of only work done
    // by the CreateCreate DAO method.  The exception is still propagated out to the
    // calling code.

    // [Transaction(NoRollbackFor = new Type[] { typeof(ArithmeticException) })]

    [Transaction(TransactionPropagation.Required)]
    public void DoTransfer(float creditAmount, float debitAmount)
    {
        accountCreditDao.CreateCredit(creditAmount);

        if (creditAmount > maxTransferAmount || debitAmount > maxTransferAmount)
        {
            throw new ArithmeticException("see a teller big spender...");
        }

        accountDebitDao.DebitAccount(debitAmount);
    }

}

}
1.4 application-config.xml
黄色为初始化注入

region License

/*
* Copyright ?2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the “License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

endregion

region Imports

using System;
using System.Collections;
using System.Data;
using NUnit.Framework;
using Spring.Aop.Config;
using Spring.Context;
using Spring.Context.Support;
using Spring.Data.Common;
using Spring.Data.Config;
using Spring.Data.Core;
using Spring.Objects.Factory.Support;
using Spring.Objects.Factory.Xml;
using Spring.Transaction.Config;
using Spring.TxQuickStart.Services;

endregion

namespace Spring.TxQuickStart
{
[TestFixture]
public class AccountManagerTests
{
private AdoTemplate adoTemplateCredit;
private AdoTemplate adoTemplateDebit;

    private IAccountManager accountManager;

    [SetUp]
    public void SetUp()
    {
        // Configure Spring programmatically
        NamespaceParserRegistry.RegisterParser(typeof(DatabaseNamespaceParser));
        NamespaceParserRegistry.RegisterParser(typeof(TxNamespaceParser));
        NamespaceParserRegistry.RegisterParser(typeof(AopNamespaceParser));
        IApplicationContext context = CreateContextFromXml();
        IDictionary dict = context.GetObjectsOfType(typeof (IAccountManager));
        accountManager = context["accountManager"] as IAccountManager;  
        CleanDb(context);
    }

    private static IApplicationContext CreateContextFromXml()
    {
        return new XmlApplicationContext(
        // use for demoing ado tx manager
            "assembly://Spring.TxQuickStart.Tests/Spring.TxQuickStart/system-test-local-config.xml" 
        // use for demoing TransactionScope tx manager

// “assembly://Spring.TxQuickStart.Tests/Spring.TxQuickStart/system-test-dtc-config.xml”
);
}

    [Test]
    public void TransferBelowMaxAmount()
    {
        accountManager.DoTransfer(217, 217);

        //asserts to read from db...

        int numCreditRecords = (int)adoTemplateCredit.ExecuteScalar(CommandType.Text, "select count(*) from Credits");
        int numDebitRecords =  (int)adoTemplateDebit.ExecuteScalar(CommandType.Text, "select count(*) from Debits");
        Assert.AreEqual(1, numCreditRecords);
        Assert.AreEqual(1, numDebitRecords);
    }

    [Test]
    public void TransferAboveMaxAmount()
    {
        try
        {
            accountManager.DoTransfer(2000000, 200000);
            Assert.Fail("Should have thrown Arithmethic Exception");
        } catch (ArithmeticException)
        {
            int numCreditRecords = (int)adoTemplateCredit.ExecuteScalar(CommandType.Text, "select count(*) from Credits");
            int numDebitRecords = (int)adoTemplateDebit.ExecuteScalar(CommandType.Text, "select count(*) from Debits");
            Assert.AreEqual(0, numCreditRecords);
            Assert.AreEqual(0, numDebitRecords);
        }

    }


    // Run the following test only if you have changed to the alternate implementation
    // of the method DoTransfer in AccountManager that specifies the NoRollbackFor property.
    [Test]   
    [Ignore("Change impl of AccountManager as shown before running this test")]
    public void TransferAboveMaxAmountNoRollbackFor()
    {
        try
        {
            accountManager.DoTransfer(2000000, 2000000);
            Assert.Fail("Should have thrown Arithmethic Exception");
        } catch (ArithmeticException) {
            int numCreditRecords = (int)adoTemplateCredit.ExecuteScalar(CommandType.Text, "select count(*) from Credits");
            int numDebitRecords = (int)adoTemplateDebit.ExecuteScalar(CommandType.Text, "select count(*) from Debits");
            Assert.AreEqual(1, numCreditRecords);
            Assert.AreEqual(0, numDebitRecords);
        }
    }


    private void CleanDb(IApplicationContext context)
    {
        IDbProvider dbProvider = (IDbProvider)context["DebitDbProvider"];
        adoTemplateDebit = new AdoTemplate(dbProvider);
        adoTemplateDebit.ExecuteNonQuery(CommandType.Text, "truncate table Debits");

        dbProvider = (IDbProvider)context["CreditDbProvider"];
        adoTemplateCredit = new AdoTemplate(dbProvider);
        adoTemplateCredit.ExecuteNonQuery(CommandType.Text, "truncate table Credits");

    }
}

}
1.7 system-test-local-config.xml
黄色代码,整合了被测试类bean文件。

region License

/*
* Copyright ?2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the “License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

endregion

region Imports

using System;
using System.Collections;
using System.Data;
using NUnit.Framework;
using Spring.Aop.Config;
using Spring.Context;
using Spring.Context.Support;
using Spring.Data.Common;
using Spring.Data.Config;
using Spring.Data.Core;
using Spring.Objects.Factory.Support;
using Spring.Objects.Factory.Xml;
using Spring.Transaction.Config;
using Spring.TxQuickStart.Services;
using Spring.Testing.NUnit;

endregion

namespace Spring.TxQuickStart
{
[TestFixture]
public class AccountManagerTestsTransaction : AbstractTransactionalDbProviderSpringContextTests
{
protected override string[] ConfigLocations
{
get
{
return new String[] { “assembly://Spring.TxQuickStart.Tests/Spring.TxQuickStart/system-test-local-config.xml” };
}
}
private AdoTemplate adoTemplateCredit;
private AdoTemplate adoTemplateDebit;

    private IAccountManager accountManager;

    [SetUp]
    public void SetUp()
    {    //没什么用
        //this.DefaultRollback = true;
        this.DefaultRollback = false;
        // Configure Spring programmatically
        NamespaceParserRegistry.RegisterParser(typeof(DatabaseNamespaceParser));
        NamespaceParserRegistry.RegisterParser(typeof(TxNamespaceParser));
        NamespaceParserRegistry.RegisterParser(typeof(AopNamespaceParser));

        IDictionary dict  = applicationContext.GetObjectsOfType(typeof(IAccountManager));
        accountManager = applicationContext["accountManager"] as IAccountManager;
        CleanDb(applicationContext);
    }


    [Test]
    public void TransferBelowMaxAmount()
    {
        accountManager.DoTransfer(217, 217);

        //asserts to read from db...

        int numCreditRecords = (int)adoTemplateCredit.ExecuteScalar(CommandType.Text, "select count(*) from Credits");
        int numDebitRecords =  (int)adoTemplateDebit.ExecuteScalar(CommandType.Text, "select count(*) from Debits");
        Assert.AreEqual(1, numCreditRecords);
        Assert.AreEqual(1, numDebitRecords);
    }

    [Test]
    public void TransferAboveMaxAmount()
    {
        try
        {
            accountManager.DoTransfer(2000000, 200000);
            Assert.Fail("Should have thrown Arithmethic Exception");
        } catch (ArithmeticException)
        {
            int numCreditRecords = (int)adoTemplateCredit.ExecuteScalar(CommandType.Text, "select count(*) from Credits");
            int numDebitRecords = (int)adoTemplateDebit.ExecuteScalar(CommandType.Text, "select count(*) from Debits");
            Assert.AreEqual(0, numCreditRecords);
            Assert.AreEqual(0, numDebitRecords);
        }

    }


    // Run the following test only if you have changed to the alternate implementation
    // of the method DoTransfer in AccountManager that specifies the NoRollbackFor property.
    [Test]   
    [Ignore("Change impl of AccountManager as shown before running this test")]
    public void TransferAboveMaxAmountNoRollbackFor()
    {
        try
        {
            accountManager.DoTransfer(2000000, 2000000);
            Assert.Fail("Should have thrown Arithmethic Exception");
        } catch (ArithmeticException) {
            int numCreditRecords = (int)adoTemplateCredit.ExecuteScalar(CommandType.Text, "select count(*) from Credits");
            int numDebitRecords = (int)adoTemplateDebit.ExecuteScalar(CommandType.Text, "select count(*) from Debits");
            Assert.AreEqual(1, numCreditRecords);
            Assert.AreEqual(0, numDebitRecords);
        }
    }


    private void CleanDb(IApplicationContext context)
    {
        IDbProvider dbProvider = (IDbProvider)context["DebitDbProvider"];
        adoTemplateDebit = new AdoTemplate(dbProvider);
        adoTemplateDebit.ExecuteNonQuery(CommandType.Text, "truncate table Debits");

        dbProvider = (IDbProvider)context["CreditDbProvider"];
        adoTemplateCredit = new AdoTemplate(dbProvider);
        adoTemplateCredit.ExecuteNonQuery(CommandType.Text, "truncate table Credits");

    }
}

}
1.10 使用nunit2.5.5
在vs2008中集成nunit
\vmware-host\Shared Folders\F\软件安装包\单元测试\ NUnit-2.5.5.10112.msi
在一个类库的项目新建一个类,加入如下代码:
using System;
using System.Collections.Generic;
using System.Text;

namespace Spring
{
class Program
{
static void Main(string[] args)
{
}
}
}
修改项目属性:

这里写图片描述
这里写图片描述
这里写图片描述
在VS2008选中测试项目直接启动,就可以启动nunit
这里写图片描述
设置好nunit为当前项目exe所在路径,就可以进行断点调试了。
这里写图片描述
1.11 测试效果:
这里写图片描述
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赵海燕

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值