2014-09-19 86 views
-1

我試圖建立一種使用一些虛擬數據來測試我的服務層(&存儲庫)的方法。我以前在Generic Repositories中見過這方面的例子,但我在使用DatabaseFactory時努力工作。NUnit - 模擬存儲庫和虛擬數據測試

當我從repository.Object調用GetPhrase方法時,我每次都會返回null。

我正在使用NUnit和Moq。任何關於我要去哪裏的錯誤的指針將不勝感激,或者讓我知道,如果我最好走下另一條路 連接到本地數據庫進行測試(SQL CE等)

這裏是代碼的主要組成部分:在您的測試調用phraseRepository.Object.GetPhrase("H300")總是返回null,除非你將它設置爲返回不同的東西

public class PhraseRepository : RepositoryBase<Phrase>, IPhraseRepository 
{ 
    public PhraseRepository(IDatabaseFactory databaseFactory) 
     : base(databaseFactory) 
    { 
    } 

    public string GetPhrase(string phraseCode) 
    { 
     return this.GetMany(p => p.PhraseCode == phraseCode).First().Descript; 
    } 

} 

public interface IPhraseRepository : IRepository<Phrase> 
{ 
    string GetPhrase(string phraseCode); 
} 

public class CLPRiskPhraseService : ICLPRiskPhraseService 
{ 
    private readonly IPhraseRepository phraseRepository; 

    public string GetPhrase(string phraseCode) 
    { 
     return phraseRepository.GetPhrase(phraseCode); 
    } 
} 


[Test] 
public void GetPhrase() 
{ 
    var phrases = new FakePhraseData().GetPhrases(); 
    phraseRepository.Setup(m => m.GetMany(It.IsAny<Expression<Func<Phrase, bool>>>())).Returns(phrases); 

    var result = phraseRepository.Object.GetPhrase("H300"); 
    // Assert 
    NUnit.Framework.Assert.IsNotNull(phraseRepository.Object); 
    NUnit.Framework.Assert.AreEqual("Description0", result); 
} 

回答

0

我想你誤以爲這調用GetPhrase將調用GetMany像混凝土PhraseRepository,但你要記住,它只是一個接口IPhraseRepository的模擬。除非使用Setup來更改該方法的行爲,否則模擬對象上的方法將始終返回返回類型的默認值(在此例中爲string)。