我正在尝试模拟数据存储库对象但是在我的MockRepository上设置了一个期望之后,它每次都返回null。我的代码如下:
[Test]
public void GetById_NotNull()
{
Person expectedPerson = new Person() { Id = 1, Name="Jon"};
MockRepository MockRepository = new MockRepository();
var FakePersonRepository = MockRepository.StrictMock<IRepository<Person>>();
FakePersonRepository.Expect(action => action.Get(1)).IgnoreArguments().Return(expectedPerson);
PersonService PersonService = new PersonService(FakePersonRepository);
Person returnedPerson = PersonService.Get(1);
Assert.IsNotNull(returnedPerson);
}
//and inside my person service
public class PersonService
{
private IRepository<Person> _PersonRepository;
public PersonService(IRepository<Person> PersonRepository)
{
this._PersonRepository = PersonRepository;
}
public Person Get(int Id)
{
Person p = _PersonRepository.Get(Id);
return p;
}
}
[Test]
public void GetById_NotNull()
{
Person expectedPerson = new Person() { Id = 1, Name="Jon"};
MockRepository MockRepository = new MockRepository();
var FakePersonRepository = MockRepository.StrictMock<IRepository<Person>>();
FakePersonRepository.Expect(action => action.Get(1)).IgnoreArguments().Return(expectedPerson);
PersonService PersonService = new PersonService(FakePersonRepository);
Person returnedPerson = PersonService.Get(1);
Assert.IsNotNull(returnedPerson);
}
//and inside my person service
public class PersonService
{
private IRepository<Person> _PersonRepository;
public PersonService(IRepository<Person> PersonRepository)
{
this._PersonRepository = PersonRepository;
}
public Person Get(int Id)
{
Person p = _PersonRepository.Get(Id);
return p;
}
}
测试底部的断言失败,返回的人总是为空。我知道我的模拟......想法一定是做错了吗?
答案 0 :(得分:6)
尝试做
mockRepository.ReplayAll()
在您设置期望的行之后。
答案 1 :(得分:4)
正如其他人所说,我相信你需要在某处使用你正在使用的测试风格重播;作为替代方案,您可以使用newer AAA Syntax以及静态MockRepository.GenerateMock&lt;&gt;()/ MockRepository.GenerateStub&lt;&gt;()方法,这些方法不需要重播。
答案 2 :(得分:2)
我不是很熟悉RhinoMocks(我一直在使用Moq),但不能:
FakePersonRepository.Expect(action => action.Get(1)).IgnoreArguments().Return(expectedPerson);
是
FakePersonRepository.Expect(action => action.Get(1)).Return(expectedPerson);
我还认为你需要一个带RM的重播()。
答案 3 :(得分:2)
克里斯在这里有钱。 AAA语法和使用GenerateStub是最好的。
var FakePersonRepository = MockRepository.GenerateStub<<IRepository<Person>>();
FakePersonRepository.Stub(x => x.Get(1)).Returns(expectedPerson);
PersonService PersonService = new PersonService(FakePersonRepository);
Person returnedPerson = PersonService.Get(1);
答案 4 :(得分:0)
使用AAA语法和GenerateMock,您还可以验证是否使用正确的参数和正确的次数调用PersonRepository:
Person expectedPerson = new Person() { Id = 1, Name="Jon"};
MockRepository MockRepository = new MockRepository();
var FakePersonRepository = MockRepository.GenerateMock<IRepository<Person>>();
FakePersonRepository.Expect(action => action.Get(1)).Return(expectedPerson).Repeat.Once();
PersonService PersonService = new PersonService(FakePersonRepository);
Person returnedPerson = PersonService.Get(1);
Assert.IsNotNull(returnedPerson);
FakePersonRepository.VerifyAllExpectations();