我有这个场景
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!");
因为参数是不同的对象而且不匹配。
答案 0 :(得分:1)
如果您只想验证使用给定参数调用GetSomething(paramObject),您可以编写如下所示的测试。
请注意,您的测试代码甚至不会编译MyMethodInMyController不会返回值!
Assert.AreEqual(myController.MyMethodInMyController(mockRepository), "Bye!");
您可以像下面一样验证方法 GetSomething 方法调用。
[TestMethod]
public void MyMethodInMyController_VerifyGetSomethingIsCalledWithExpectedParamaters()
{
//Arrange
var mockRepository = MockRepository.GenerateMock<IRepository>();
mockRepository
.Expect(m => m.GetSomething(Arg<ParamObject>.Matches(p => p.Prop1 == 1 && p.Prop2 == 2 && p.Prop3 == 3 && p.Prop4 == 4)))
.Return("Bye!");
var sut = new MyController();
//Act
sut.MyMethodInMyController(mockRepository);
//Assert
mockRepository.VerifyAllExpectations();
}
这不应该崩溃。