Rhino Mocks是款单元测试工具,它功能非常强大。用它能轻松构建出测试需要的类或接口,而不需要编写繁琐的测试代码,咱们来看看它的效果吧!
测试代码
public abstract class People
{
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual int Age { get; set; }
public virtual bool Sex { get; set; }
public IExtensionAction favoriteSport;
public void IntroduceMyself()
{
Console.WriteLine(string.Format("Hello My Name is {0} {1}. I'm a {2} and {3} years old now. Nice to meet you! ", LastName, FirstName,this.Sex?"boy":"girl",Age.ToString()));
}
//which thing i can do
public abstract void Do();
public virtual void ExtensionDo()
{
if (favoriteSport != null)
{
Console.WriteLine(favoriteSport.Introduce());
}
else
{
Console.WriteLine("I just like sleeping in my free time.");
}
}
public virtual string Bomb(string arg1, string arg2)
{
return "nothing!";
}
public abstract string AbstractMethod();
}
public class Student:People
{
public override void Do()
{
Console.WriteLine("I'm a student, i still study in school.");
}
public virtual string IntroduceMajor()
{
return "";
}
public override string AbstractMethod()
{
throw new NotImplementedException();
}
}
public interface IExtensionAction
{
string Introduce();
string SportType { get; set; }
}
Mock代码1
//模仿Student类中的虚拟方法IntroduceMajor
Student jim = MockRepository.GenerateMock<Student>();
jim.Stub(x => x.IntroduceMajor()).Return("My major is software engineering.");
Console.WriteLine(jim.IntroduceMajor());
Mock代码2
//模仿Student类中的抽象方法AbstractMethod
Student jim = MockRepository.GenerateMock<Student>();
jim.Stub(x => x.AbstractMethod()).Return("This is a abstract method");
Console.WriteLine(jim.AbstractMethod());
Mock代码3
//根据输入的参数值来决定模仿方法的返回值
People clark = MockRepository.GenerateMock<People>();
clark.Stub(x => x.Bomb(Arg<string>.Is.Anything, Arg<string>.Is.Anything)).Return("You can input any parameters");
Console.WriteLine(clark.Bomb(null, null));
People Bank = MockRepository.GenerateMock<People>();
Bank.Stub(x => x.Bomb(Arg<string>.Matches(a1 => a1.StartsWith("B") && a1.EndsWith("K")), Arg<String>.Is.Equal("Super"))).Return("You must input special parameters");
Console.WriteLine(Bank.Bomb("BanK", "Super"));
Mock代码4
//替换调用模仿的方法
People joe = MockRepository.GenerateMock<People>();
joe.Stub(x => x.ExtensionDo()).Do(new Action(() => Console.WriteLine("I'm not ExtensionDo method!")));
joe.ExtensionDo();
Mock代码5
//重装模拟方法
People king = MockRepository.GenerateMock<People>();
king.Stub(x => x.Do()).Do(new Action(() => Console.WriteLine("Go!")));
king.Stub(x => x.Do()).Do(new Action(() => Console.WriteLine("Reload!")));
king.Do();
king.Do();
king.BackToRecord(BackToRecordOptions.All);//重装模拟方法
king.Replay();
king.Stub(x => x.Do()).Do(new Action(() => Console.WriteLine("Reload!")));
king.Do();
Rhino Mocks下载