2016-01-15 74 views
0

我正在嘗試編寫單元測試。這是我第一次使用存儲庫和依賴注入來做這件事。使用mocks的單元測試代碼庫

我的單元測試看起來如下:

[TestClass()] 
public class PersonRepositoryTests 
{ 
    Mock<PersonRepository> persoonRepository; 
    IEnumerable<Person> personen; 

    [TestInitialize()] 
    public void Initialize() 
    { 
     persoonRepository = new Moq.Mock<PersonRepository >(); 
     personen = new List<Person>() { new Person { ID = 1, Name = "Bart Schelkens", GewerkteDagen = 200, Leeftijd = 52, Type = "1" }, 
             new Person { ID = 2, Name = "Yoram Kerckhofs", GewerkteDagen = 190, Leeftijd = 52, Type = "1" }}; 

     persoonRepository.Setup(x => x.GetAll()).Returns(personen); 

    } 

    [TestMethod()] 
    public void GetAll() 
    { 
     var result = persoonRepository.Object.GetAll(); 
    } 
} 

我的資料庫:

public class PersonRepository 
{ 
    DatabaseContext DbContext { get; } 

    public PersonRepository(DatabaseContext dbContext) 
    { 
     this.DbContext = dbContext; 
    } 

    public virtual IEnumerable<Person> GetAll() 
    { 
     return DbContext.Persons.ToList(); 
    } 

} 

現在,當我跑我的測試,我得到以下錯誤:

「無法實例的代理class:CoBen.Dossier.DataAccess.Repository.PersonRepository。 找不到無參數的構造函數。「

所以我做錯了什麼,但我沒有看到它。 任何人都可以幫助我嗎?

+0

閱讀錯誤消息... – Steve

+0

@Steve:我知道它說了什麼,我只是沒有成功添加數據庫上下文 –

+0

請記住,當您嘲笑版本庫時,版本庫中的代碼永遠不會被調用,因爲模擬「攔截」呼叫並返回您指定的值。所以你可以將存儲庫方法提取到一個接口,然後模擬它。 – stuartd

回答

1

你測試(SUT)嘲笑你的系統中,PersonRepository,在那裏爲你需要模擬的是它的依存關係:

[TestMethod] 
public void GetAll() 
{ 
    // *Arrange* 
    var mockSet = new Mock<DbSet<Person>>(); 

    var mockContext = new Mock<DatabaseContext>(); 
    mockContext.Setup(m => m.Person).Returns(mockSet.Object); 

    // Configure the context to return something meaningful 

    var sut = new PersonRepository(mockContext.Object); 

    // *Act* 
    var result = sut.GetAll() 

    // *Assert* that the result was as expected 
} 

這是一個有點「空碼」爲你問題沒有關於如何配置DbContext位的詳細信息。

MSDN上有一個worked example

0

試加一個參數的構造函數:)

public PersonRepository(){} 
+0

但是如果我想要帶參數的構造函數呢?我將如何注入databasecontext? –

2

該錯誤是在你的單元測試,因爲存在的你是模擬倉庫裏面存儲庫類似乎對DataContext的依賴。

您需要添加在你的倉庫默認的構造器不具備的datacontext作爲依賴按如下:

公共PersonRepository()

或嘲笑的datacontext。希望幫助

+0

如果我想模擬datacontext呢? –

+0

我會建議,例如使用您的databasecontext標記接口。 –

+0

如果您正在模擬datacontext,那麼您將不得** **模擬存儲庫,因爲datacontext模擬不會被模擬存儲庫調用。 – stuartd