C# 为什么此NSSubstitute接收呼叫失败?
有问题的测试:“TestGetAllPeople()” 我在试验单元测试框架(因为我没有太多使用它们的经验),我遇到了一个错误,我看不出能解决这个问题 根据文件()(我相信)。它不应该失败,因为我通过调试器运行了它,它被调用,它检索两个人,所以我显然缺少了一些东西C# 为什么此NSSubstitute接收呼叫失败?,c#,visual-studio,unit-testing,nunit,nsubstitute,C#,Visual Studio,Unit Testing,Nunit,Nsubstitute,有问题的测试:“TestGetAllPeople()” 我在试验单元测试框架(因为我没有太多使用它们的经验),我遇到了一个错误,我看不出能解决这个问题 根据文件()(我相信)。它不应该失败,因为我通过调试器运行了它,它被调用,它检索两个人,所以我显然缺少了一些东西 VS2015 .NET 4.5.2 NSU替代3.1 NUnit 3.9和 NUnitAdapter 3.9 Person.cs public interface IPersonRepository { List<P
- VS2015
- .NET 4.5.2
- NSU替代3.1
- NUnit 3.9和
- NUnitAdapter 3.9
public interface IPersonRepository
{
List<Person> GetPeople();
Person GetPersonByID(string ID);
}
public class Person
{
public string ID;
public string FirstName;
public string LastName;
public Person(string newID, string fn, string ln)
{
ID = newID;
FirstName = fn;
LastName = ln;
}
}
public class PersonService
{
private IPersonRepository personRepo;
public PersonService(IPersonRepository repo)
{
personRepo = repo;
}
public List<Person> GetAllPeople()
{
return personRepo.GetPeople();
}
public List<Person> GetAllPeopleSorted()
{
List<Person> people = personRepo.GetPeople();
people.Sort(delegate (Person lhp, Person rhp)
{
return lhp.LastName.CompareTo(rhp.LastName);
});
return people;
}
public Person GetPerson(string ID)
{
try
{
return personRepo.GetPersonByID(ID);
}
catch(ArgumentException)
{
return null; // No person found
}
}
}
欢迎对样式/约定提出任何建议(我意识到现在测试名称并不好)
我将使用所请求的任何信息进行更新。
接收的
用于断言,而您尝试在测试方法的练习中使用它。在调用Received
时,测试中的方法还没有被调用,因此mock没有收到任何东西。因此,测试失败
考虑以下几点
[Test]
public void TestGetAllPeople() {
//Arrange
var expected = peopleList.Count;
personRepoMock.GetPeople().Returns(peopleList);
var subject = new PersonService(personRepoMock);
//Act
var actual = subject.GetAllPeople().Count;
//Assert
Assert.AreEqual(expected, actual);
personRepoMock.Received().GetPeople();
}
Received
用于在测试方法的练习中尝试使用它时的断言。在调用Received
时,测试中的方法还没有被调用,因此mock没有收到任何东西。因此,测试失败。
//System.Diagnostics.Debugger.Launch();
[Test]
public void TestGetAllPeople() {
//Arrange
var expected = peopleList.Count;
personRepoMock.GetPeople().Returns(peopleList);
var subject = new PersonService(personRepoMock);
//Act
var actual = subject.GetAllPeople().Count;
//Assert
Assert.AreEqual(expected, actual);
personRepoMock.Received().GetPeople();
}