[英]c# How to mock a list of objects
In C#, How do I go about mocking a list of objects? 在C#中,我该如何模拟对象列表?
I am attempting an exercise and it specifies that in the arrange section of my unit test that I need to "mock a List of Book
objects". 我正在尝试一个练习,它指定了在单元测试的“安排”部分中需要“模拟
Book
对象列表”。
What is the syntax for creating a mock list of Book objects? 创建Book对象的模拟列表的语法是什么? I have tried creating mock Book objects and adding them to a list of books but this didn't work.
我尝试创建模拟Book对象并将其添加到书籍列表中,但这没有用。
public void Test_GetAllBooks_ReturnsListOfBooksItReceivesFromReadAllMethodOfReadItemCommand_WhenCalled()
{
//Arrange
Mock<ReadItemCommand> mockReadItemCommand = new Mock<ReadItemCommand>();
Catalogue catalogue = new Catalogue(mockReadItemCommand.Object);
Mock<Book> mockBook1 = new Mock<Book>();
Mock<Book> mockBook2 = new Mock<Book>();
List<Book> mockBookList = new List<Book>();
mockBookList.Add(mockBook1);
mockBookList.Add(mockBook2);
mockReadItemCommand.Setup(r => r.ReadAll()).Returns(mockBookList);
//Act
List<Book> actual = catalogue.GetAllBooks();
//Assert
Assert.AreSame(mockBookList, actual);
}
This is giving me 2 compilation errors, both CS1503, on the two lines where I have tried to add the mock books to my list of type Book. 在试图将模拟书籍添加到Book类型列表的两行中,这给了我2个编译错误,均为CS1503。
Just create a list of books to represent fake/mocked data to be returned when exercising the method under test. 只需创建一本书籍清单,以表示在执行被测方法时将要返回的伪造/模拟数据。 No need to use Moq for the fake data.
无需将Moq用于伪造数据。 Use Moq to mock the dependencies (
ReadItemCommand
) of the system under test ( Catalogue
) 使用Moq来模拟
ReadItemCommand
系统( Catalogue
)的依赖项( ReadItemCommand
)
public void Test_GetAllBooks_ReturnsListOfBooksItReceivesFromReadAllMethodOfReadItemCommand_WhenCalled()
{
//Arrange
var mockReadItemCommand = new Mock<ReadItemCommand>();
var catalogue = new Catalogue(mockReadItemCommand.Object);
var expected = new List<Book>(){
new Book {
Title = "Book1",
//populate other properties
},
new Book {
Title = "Book2",
//populate other properties
}
};
mockReadItemCommand
.Setup(_ => _.ReadAll())
.Returns(expected);
//Act
var actual = catalogue.GetAllBooks();
//Assert
Assert.AreSame(expected, actual);
}
if i got you right,you can clone the list: for example as shown here: 如果我答对了,您可以克隆列表:例如,如下所示:
How do I clone a generic list in C#? 如何在C#中克隆通用列表?
you can clone it in the same way,or instead you can copy the list yourself by creating a new list and add a copy of each element from the source list. 您可以用相同的方法克隆它,或者您可以通过创建新列表自己复制列表,并从源列表中添加每个元素的副本。 hope it helps.
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.