我是Moq的新手,并希望不仅在单元测试中使用它,我似乎主要是在代码中获取它.
鉴于此实体:
namespace TestBed.Domain.Entities
{
public class Person
{
public string LastName { get; set; }
public string FirstName { get; set; }
public string PhoneNumber { get; set; }
public string JobTitle { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
这个抽象的存储库:
using TestBed.Domain.Entities;
namespace TestBed.Domain.Abstract
{
public interface IPersonRepository
{
Person GetPerson();
}
}
Run Code Online (Sandbox Code Playgroud)
我想使用Moq填充一个虚拟人(!)并将该填充的"对象"传递给Repository方法.我该怎么做呢?
using TestBed.Domain.Abstract;
using TestBed.Domain.Entities;
using Moq;
namespace TestBed.Domain.Concrete
{
public class MockPersonReqpository
{
Person GetPerson()
{
Mock<IPersonRepository> mock = new Mock<IPersonRepository>();
mock.Setup(m => m.GetPerson()).Returns(new Person()
{
FirstName = "Joe",
LastName = "Smith",
PhoneNumber = "555-555-5555"
});
return mock.Object // NO
}
}
}
Run Code Online (Sandbox Code Playgroud)
And*_*ker 10
根据您对@ Daniel的回答的评论,您似乎只需要模拟存储库本身.您仍然希望返回一个正确的Person对象,您只是不关心存储库实际上是否为了您的测试而检索该人.
除了单元测试之外,我也不理解你在其他地方使用Moq的评论.Moq的全部意义在于你可以伪造一个实际的对象用于测试目的(可能更好地说,但这是要点).
由于我不知道你要测试的是什么,我将给出一个简单的例子:
[TestMethod]
public void WhenValidRequest_ThenReturnSuccess()
{
Mock<IPersonRepository> personRepository = new Mock<IPersonRepository>();
personRepository.Setup(r => r.GetPerson()).Returns(
new Person()
{
FirstName = "Joe",
LastName = "Smith"
/*...*/
});
Foo objectUnderTest = new Foo(personRepository.Object);
bool result = objectUnderTest.MakeRequest();
// Call method using the person repository that you want to test.
// You don't actually care how the repository works, you just want to return a success
// boolean when a person exists for that request.
Assert.IsTrue(result);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17313 次 |
| 最近记录: |