2013-03-23 64 views
0

我目前的解決方案是創建一個具有我的服務/數據業務邏輯的類,使用本地數據庫(mdf)進行測試,然後使用相同的函數數據服務類。如何使用.Net數據服務和服務操作進行TDD

public class MyDataService : DataService<MyEntities> 
{ 
    [WebGet] 
    [SingleResult] 
    public Team GetTeam(string name) 
    { 
     return _serviceBusinessLogic.GetTeam(name); 
    } 
} 

//seam here to make this testable 
public class ServiceBusinessLogic 
{ 
    public Team GetTeam(string name) 
    { 
     return _dbContext.Teams.SingleOrDefault(p => p.Name == name); 
    } 
} 

但由於它們是相同的,應該不需要包裝函數。

我想直接測試數據服務,但是由於CreateDataSource受保護,因此我無法設置DataSource。

public class MyDataService : DataService<MyEntities> 
{ 
    [WebGet] 
    [SingleResult] 
    public Team GetTeam(string name) 
    { 
     //problem is CurrentDataSource is not settable, so cant set it in test 
     return CurrentDataSource.Teams.SingleOrDefault(p => p.Name == name); 
    } 
} 

回答

0

你可以寫你的類以這樣的方式,可以讓你注入你的數據源,像這樣:

public class MyDataService : DataService<MyEntities> 
{ 
    private MyEntities _dataSource; 

    public MyDataService() : this(new MyEntities()){} 

    public MyDataService(MyEntities dataSource) 
    { 
     _dataSource = dataSource; 
    } 

    protected override MyEntities CreateDataSource() 
    { 
     return _dataSource; 
    } 

    [WebGet] 
    [SingleResult] 
    public Team GetTeam(string name) 
    { 
     return CurrentDataSource.Teams.SingleOrDefault(p => p.Name == name); 
    } 
} 

如果CreateDataSource被稱爲在基礎構造,你可能必須使用一個靜態並注意清理狀態,但我敢打賭,這是按原樣工作的。

+0

嗯。這似乎是一個好主意,但我試過了,似乎CreateDataSource並沒有在內部調用,所以當我在我的測試中實例化MyDataService時,它永遠不會被調用。必須是調用CreateDataSource的更高級的服務類之一。不確定這裏要做的是正確的事情。我可以使用_dataSource而不是CurrentDataSource,但不確定這是否違反任何原則。 – 2013-03-25 01:40:39

相關問題