NMock
NMock 官方网址:http://nmock.org/
在进行单元测试的时侯,有些测试功能会对其它类或接口等等有依赖,这时我们就需要用模拟对象来代替被依赖的类进行测试,然而自己写模拟对象是比较麻烦的事情,NMock就是专门用来实现模拟对象的。
下面是在VS2005.NET单元测试中使用NMock的例子:
using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NMock2;
namespace TestProject1
{
public interface IBankAccount
{
string BankName { get;}
decimal GetAmount();
}
public class Person
{
private string _name;
private IBankAccount _bankAccount;
public IBankAccount BankAccount
{
get { return _bankAccount; }
}
public Person(string name, IBankAccount bankAccount)
{
this._name = name;
this._bankAccount = bankAccount;
}
}
/// <summary>
/// UnitTest1 的摘要说明
/// </summary>
[TestClass]
public class UnitTest1
{
public UnitTest1()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
其他测试属性
[TestMethod]
public void TestMethod1()
{
Mockery mocks = new Mockery();
IBankAccount mockBankAccount = (IBankAccount)mocks.NewMock(typeof(IBankAccount));
Expect.Once.On(mockBankAccount).GetProperty("BankName").Will(Return.Value("Bank of China"));
Expect.Once.On(mockBankAccount).Method("GetAmount").Will(Return.Value(5000.00M));
Person person = new Person("netflu", mockBankAccount);
Assert.AreEqual("Bank of China", person.BankAccount.BankName);
Assert.AreEqual(5000.00M, person.BankAccount.GetAmount());
mocks.VerifyAllExpectationsHaveBeenMet();
}
}
}
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NMock2;
namespace TestProject1
{
public interface IBankAccount
{
string BankName { get;}
decimal GetAmount();
}
public class Person
{
private string _name;
private IBankAccount _bankAccount;
public IBankAccount BankAccount
{
get { return _bankAccount; }
}
public Person(string name, IBankAccount bankAccount)
{
this._name = name;
this._bankAccount = bankAccount;
}
}
/// <summary>
/// UnitTest1 的摘要说明
/// </summary>
[TestClass]
public class UnitTest1
{
public UnitTest1()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
其他测试属性
[TestMethod]
public void TestMethod1()
{
Mockery mocks = new Mockery();
IBankAccount mockBankAccount = (IBankAccount)mocks.NewMock(typeof(IBankAccount));
Expect.Once.On(mockBankAccount).GetProperty("BankName").Will(Return.Value("Bank of China"));
Expect.Once.On(mockBankAccount).Method("GetAmount").Will(Return.Value(5000.00M));
Person person = new Person("netflu", mockBankAccount);
Assert.AreEqual("Bank of China", person.BankAccount.BankName);
Assert.AreEqual(5000.00M, person.BankAccount.GetAmount());
mocks.VerifyAllExpectationsHaveBeenMet();
}
}
}