![](/img/trans.png)
[英]Cannot retrieve MethodInfo from rhino mocked interface during testing
[英]How to handle methods that cannot be mocked during unit testing
我想知道我們如何處理在編寫單元測試時無法模擬的方法。
我們有 class 稱為學生,它有一組用於操作學生數據的方法。 我們還有一些用於進一步處理的擴展方法(在 C# 中)。 現在我們的業務邏輯包括學生class方法的使用和擴展方法。
例子:
class Student
{
// fields
filter()
check()
...
}
BusinessLogic()
{
// get list of students
return students.Where(filter()).someExtensionMethod().FirstOrDefault().check();
}
現在,如果我們想測試 BusinessLogic 方法,我們不能模擬方法 filter()、check() 和 someExtensionMethod()。 如果我們通過常規方法 go,我們將設置測試數據,以便我們可以測試每個方法的 output,並確保這些方法被調用。 如果我們有這樣的 2 或 3 個方法調用,這樣做是可以的。 但是我想知道如果有很多這樣的方法調用並且該方法涉及復雜的邏輯,這使得我們的測試數據設置更加復雜,該怎么辦?
編輯:這里我對學生 class 中定義的函數感興趣。 例如,我有功能可以檢查學生的分數是否超過 33。就像 IsPass()。 我將其稱為 student.IsPass()。 但問題是在實際項目中,此類方法的數量可能很大。 而我們的業務邏輯可以是這些方法的組合
我會將負責在單獨的 class 中檢索學生數據的邏輯分開,例如“ StudentRepository
”。 然后為此 class 創建一個接口,並將其用作 BusinessLogic 中的依賴項。
public interface IStudentRepository
{
IEnumerable<Student> GetStudents();
}
IStudentRepository
的實現取決於您的數據存儲。
在 BusinessLogic class 中,您將有一個“IStudentRepository”依賴項:
public BusinessLogic(IStudentRepository studentRepository)
{
// get list of students
var students = studentRepository.GetStudents();
// perform business logic on students
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.