使用Moq - 问题

Nic*_*ahn 2 unit-testing moq

我刚刚开始使用Moq ver(3.1)并且我已经阅读了博客,而不是......不管怎样......我想直到你弄脏你的手你才会学到:)

好的,这是我正在测试...

  var newProduct = new Mock<IPartialPerson>();   
  newProduct.SetupGet(p => p.FirstName).Returns("FirstName");   
  newProduct.SetupGet(p => p.MiddleName).Returns("MiddleName");   
  newProduct.SetupGet(p => p.LastName).Returns("LastName");   
  newProduct.SetupGet(p => p.EmailAddress).Returns("EmailAddress@hotmail.com");   
  newProduct.SetupGet(p => p.UserID).Returns("UserID");   

  //mock Escort repository   
  var mockEscortRepository = new Mock<IEscortRepository>();     
  mockEscortRepository.Setup(p => p.LoadAllEscorts())   
      .Returns(newProduct.Object); //error  
Run Code Online (Sandbox Code Playgroud)

错误1'Moq.Language.IReturns> .Returns(System.Collections.Generic.List)'的最佳重载方法匹配有一些无效的参数


错误2参数'1':无法从'App.Model.Interface.IPartialPerson'转换为'System.Collections.Generic.List'


public interface IPartialPerson   
    {   
        string FirstName { get; }   
        string MiddleName { get; }   
        string LastName { get; }   
        string EmailAddress { get; }   
        string FullName { get; }   
        string UserID { get; }   

    }  

public interface IEscortRepository   
   {   
       List<PartialPerson> LoadAllEscorts();   
       List<PartialPerson> SelectedEscorts(List<PartialPerson> selectedEscorts);     
   }  
Run Code Online (Sandbox Code Playgroud)

我有两种方法,我想测试"LoadAllaEscorts"和"SelectedEscorts"

我将如何对这两种方法进行测试?

Jim*_*nts 5

试试这个:

mockEscortRepository
.Setup(p => p.LoadAllEscorts())
.Returns(new List<IPartialPerson>() { newProduct.Object } ); 
Run Code Online (Sandbox Code Playgroud)

当你说:

.Returns(newProduct.Object)
Run Code Online (Sandbox Code Playgroud)

您要求Moq返回一个特定对象.编译器看到您的方法返回一个列表,因此除非您提供要返回的列表,否则它将无法编译.因此,您需要创建一个包含要返回的对象的列表,然后要求Moq返回该对象.

根据您的评论,您可能还有兴趣测试包含多个项目的列表.为此,创建一个包含多个项目的列表,然后让Mock返回该项目.以下是一种可以创建包含多个项目的列表的方法:

List<PartialPerson> escorts = new List<PartialPerson>();
for (int i = 0; i < 10; i++)
{

    var escort = new Mock<IPartialPerson>();
    escort.SetupGet(p => p.FirstName).Returns("FirstName" + i);
    escort.SetupGet(p => p.MiddleName).Returns("MiddleName" + i);
    escort.SetupGet(p => p.LastName).Returns("LastName" + i);
    escort.SetupGet(p => p.EmailAddress).Returns(i + "EmailAddress@hotmail.com");
    escort.SetupGet(p => p.UserID).Returns("UserID" + i);
    escorts.Add(escort.Object);
}

mockEscortRepository
    .Setup(p => p.LoadAllEscorts())
    .Returns(escorts); 
Run Code Online (Sandbox Code Playgroud)

祝你好运,继续留在pimpin!