2015-10-13 34 views
0

我是新的测试范围,我想用这个FakeItEasy写这个业务逻辑函数的测试。 在我的StudentsBusinessLogic代码我想测试功能GetOldestStudentFakeItEasy - 嘲笑函数返回列表<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初始化阶段,而是 - 嘲笑它。 有人能帮助我如何做到正确吗?

回答

1

您需要打破你的业务逻辑类和资源库,例如之间的具体相关性:

public class StudentsBusinessLogic:IStudentsBusinessLogic 
{ 
    private IStudentRepository _studentRepository; 

    public StudentsBusinessLogic(IStudentRepository studentRepository) 
    { 
     this._studentRepository = studentRepository; 
    } 
... 

现在,您可以在存储库的嘲笑实例传递到类:

var fakeStuRep = A.Fake<IStudentRepository>(); 

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}}); 

IStudentsBusinessLogic bl = new StudentsBusinessLogic(fakeStuRep); 
var res = bl.GetOldestStudent(); 

最后,你可以很好地定义,初始化你的模拟并将其传递给具有业务逻辑的具体类。

这是单元测试业务逻辑类的一种方法。您不希望(至少现在不需要)调用真实存储库或任何具体的DAL实现。

注意:您的测试应该声明来自嘲笑仓库的方法被调用。 FakeItEasy提供了几种检查方法。

+0

这很好。谢谢!还有其他方法可以做到吗?这意味着我不喜欢改变我的代码(通常...),这样我必须改变/添加ctor ... – Roni

+0

所以,还有其他方法。但是打破你的类之间的依赖关系是一个非常好的方法,我相信这是更简单的单元测试方法。否则,你需要使用静态方法/工厂,有条件的服务定位器等来破解这个依赖关系。 – gustavodidomenico