我是新的测试范围,我想用这个FakeItEasy写这个业务逻辑函数的测试。 在我的StudentsBusinessLogic
代码我想测试功能GetOldestStudent
。FakeItEasy - 嘲笑函数返回列表<T>由其他函数调用
- 列表项
代码:
public class StudentsBusinessLogic:IStudentsBusinessLogic
{
private IStudentRepository _studentRepository;
public StudentsBusinessLogic()
{
this._studentRepository = new DalConcreteFactory().GetStudentsRepository();
}
//I want to test this function
public Student GetOldestStudent()
{
var q1 = from students in this._studentRepository.AllStudents()
where students.Age >= ((from oldest in this._studentRepository.AllStudents()
select oldest.Age).Max())
select students;
Student result = q1.First();
Console.WriteLine(result.Age);
return result;
}
}
现在,我有嘲笑那个代码片段:this._studentRepository.AllStudents()
, ,因为我不喜欢用this._studentRepository.AllStudents()
(即使用原始分贝)。 我的问题是:如何测试GetOldestStudent
与嘲笑studentRepository.AllStudents()
调用。 我试图写的测试是:
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
// Arrange
var fakeStuRep = A.Fake<IStudentRepository>();
var fakeFactory = A.Fake<DalAbstractFactory>();
A.CallTo(() => fakeStuRep.AllStudents()).Returns(new System.Collections.Generic.List<BE.Student> { new BE.Student { ID = 1, Age = 7 }, new BE.Student {ID = 2, Age = 55}});
A.CallTo(() => fakeFactory.GetStudentsRepository()).Returns(null);
// Act
IStudentsBusinessLogic bl = new StudentsBusinessLogic(true);
var res = bl.GetOldestStudent();
// Assert
Assert.AreEqual(55, res.Age);
}
}
不幸的是,测试导致运行时异常由于IStudentRepository
构造函数问题(特定的问题,不涉及此范围内)。但我试图做的是跳过IStudentRepository
初始化阶段,而是 - 嘲笑它。 有人能帮助我如何做到正确吗?
这很好。谢谢!还有其他方法可以做到吗?这意味着我不喜欢改变我的代码(通常...),这样我必须改变/添加ctor ... – Roni
所以,还有其他方法。但是打破你的类之间的依赖关系是一个非常好的方法,我相信这是更简单的单元测试方法。否则,你需要使用静态方法/工厂,有条件的服务定位器等来破解这个依赖关系。 – gustavodidomenico