【发布时间】:2013-11-20 08:25:09
【问题描述】:
我有这种情况
public class ParamObject
{
public int Prop1 {get; set}
public int Prop2 {get; set}
public int Prop3 {get; set}
public int Prop4 {get; set}
}
public class Respository: IRepository
{
public string GetSomething(ParamObject myParameter)
{
return string.Format("Hello {0}, {1}, {2}, {3}}!", myParameter.Prop1, myParameter.Prop2, myParameter.Prop3, myParameter.Prop4) ;
}
}
public class MyController
{
public void MyMethodInMyController(IRepository myRepo)
{
ParamObject paramObject = new ParamObject();
paramObject.Prop1 = 1;
paramObject.Prop2 = 2;
paramObject.Prop3 = 3;
paramObject.Prop4 = 4;
Console.WriteLine(myRepo.GetSomething(paramObject));
}
}
[TestMethod]
public void Testing()
{
mocker = new MockRepository();
mockRepository = mocker.DynamicMock<IRepository>();
mockRepository
.Expect(m => m.GetSomething(Arg<ParamObject>.Matches(p => p.Prop1 == 1 && p.Prop2 == 2 && p.Prop3 == 3 && p.Prop4 == 4)))
.Return("Bye!");
mocker.ReplyAll();
MyController myController = new MyController();
Assert.AreEqual(myController.MyMethodInMyController(mockRepository), "Bye!");
}
如您所见,我想测试 MyMethodInMyController 但它需要调用一个以复杂对象为参数的方法
我的测试不起作用,也没有返回异常,只是在从 MyMethodInMyController
调用调用中的方法时停止我如何模拟这种需要 complez 对象作为参数的方法?
提前致谢!
注意我不能模拟
mockRepository
.Expect(new ParamObect(value1, value2, ....)
.Return("Bye!");
因为参数是不同的对象,不匹配。
【问题讨论】:
-
到目前为止对我来说看起来还不错。只是一些建议:使用 AAA 语法(没有 MockRepository 的实例,没有 ReplayAll 之类的东西)。使用 Stub 而不是 Expect。不要调用您的模拟 mockRepository,这非常令人困惑! (为什么不使用 repositoryMock?)
-
测试的最后一行不起作用。 MyMethodInMyController 没有返回值。它在哪条线上“停止”? “停止”是什么意思?
-
它在 Console.WriteLine(myRepo.GetSomething(paramObject));并且停止意味着程序在此之后不会继续
-
非常感谢您的评论。我现在要改了
-
@Patraix 您提到“我想测试 MyMethodInMyController”但不清楚您真正想要测试的内容。您尝试在单元测试中测试的确切行为是什么?测试方法名称“Testing”什么都不是。
标签: .net unit-testing rhino-mocks