2011-01-10 87 views
0

由於標題暗示我試圖測試一種方法,不幸的是我似乎在某個地方出錯了。該方法只應返回有客戶ID = 1測試存儲庫方法

這裏是我的測試

 [TestMethod] 
     public void Returns_Correct_Number_Of_Workout_Dates_For_Valid_UserId() 
     { 

     //Arrange 
     List<GymSession> gymSessions = new List<GymSession>(); 

     Customer cust = new Customer(); 

     cust.CustomerId = 1; 

     gymSessions.Add(new GymSession() { Customer = cust, SessionId = 1, Date = new DateTime(2010, 1, 1) }); 
     gymSessions.Add(new GymSession() { Customer = cust, SessionId = 2, Date = new DateTime(2010, 1, 2) }); 
     gymSessions.Add(new GymSession() { SessionId = 3, Date = new DateTime(2010, 1, 3) }); 
     gymSessions.Add(new GymSession() { Customer = cust, SessionId = 4, Date = new DateTime(2010, 1, 4) }); 

     var mockRepos = new Moq.Mock<IGymSessionRepository>(); 
     mockRepos.Setup(g => g.GymSession()).Returns(gymSessions.AsQueryable()); 

     //Act 
     var result = mockRepos.Object.GetWorkoutDatesByCustomerId(1); 

     //Assert 
     Assert.AreEqual(3, result.Count()); 
     } 

這裏是倉庫的方法,我試圖測試

 public IQueryable<GymSession> GetWorkoutDatesByCustomerId(int userId) 
    { 
     var gymSess = db.GymSessions.Where<GymSession>(g => g.Customer.CustomerId == userId); 

     return gymSess; 
    } 

的想法是,設置擁有所有客戶,然後該方法將對它們進行過濾。計數似乎從未應用過濾器。有任何想法嗎?

+0

'GymSession`是否有默認客戶?如果`GymSession.Customer`爲null,謂詞不會拋出嗎? – 2011-01-10 17:43:26

+0

它沒有默認客戶。結果總是4.我是新來測試,所以我懷疑我要麼安裝錯誤,要麼錯誤地分配結果變量。但是,我不知道。 – hoakey 2011-01-10 17:52:46

回答

1

看來您確實想要將電話存根db.GymSessions,並且您應該測試一個具體的GymSessionRepository實例。傳統上,有兩種方法可以執行此操作(除了使用面向方面編程攔截調用外):

1)爲您的存儲庫明確依賴db並在存儲庫構造器中要求它。這裏就是我的意思是,當我使用IDatabase表示db

public class GymSessionRepository: IGymSessionRepository { 
    private IDatabase db; 
    public GymSessionRepository(IDatabase db) { 
     this.db = db; 
    } 
} 

// Then in your test ... 
var mockDb = new Moq.Mock<IDatabase>(); 
mockDb.Setup(d => d.GymSessions()).Returns(gymSessions.AsQueryable()); 

GymSessionRepository repository = new GymSessionRepository(mockDb); 
// ... and so on 

2)(不太理想,但有時是必要的),會使您想存根作爲虛擬部件的製造方法,模擬具體的對象,你」重新測試,並且直接短截線的行爲的類下測試:

public class GymSessionRepository { 
    // Because this is virtual, you can override it in your mock object 
    protected virtual List<GymSession> GymSessions() { 
     return this.db.GymSessions.AsQueryable(); 
    } 
} 

// In your test code here: notice the mock object is your concrete class, 
// because your test targets another method on that class, not a method 
// on an arbitrary implementation (like a mock based on its interface) 
var mockRepos = new Moq.Mock<GymSessionRepository>(); 

// Override its virtual method; take control for your test 
mockRepos.Setup(g => g.GymSessions()).Returns(gymSessions.AsQueryable()); 

根據模擬框架,第二技術被稱爲使用transparentpartial模擬。如果你經常使用它,這可能表明你的代碼是過度耦合的(並且它可能會很快地混淆)。