My current solution is to create a class that has my service/data business logic, test that with a local db (mdf) and then wrap that class with identical functions from the data service class.
我现在的解决方案是创建一个具有服务/数据业务逻辑的类,用本地db (mdf)测试,然后用数据服务类的相同函数包装这个类。
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);
}
}
But since they are identical, there should be no need for the wrapper functions.
但是由于它们是相同的,因此不需要包装器函数。
I would like to test the data services directly, but there is no way for me to set the DataSource since CreateDataSource is protected.
我想直接测试数据服务,但是因为CreateDataSource受到保护,所以我无法设置数据源。
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);
}
}
1 个解决方案
#1
0
You can write your class in such a way that allows you to inject your datasource, like so:
您可以以这样一种方式编写您的类,它允许您注入您的数据源,比如:
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);
}
}
If CreateDataSource
gets called in the base constructor, you may have to use a static and be careful about clearing state, but I bet this works as is.
如果在基本构造函数中调用CreateDataSource,您可能需要使用静态方法,并且要注意清理状态,但是我打赌这是正确的。
#1
0
You can write your class in such a way that allows you to inject your datasource, like so:
您可以以这样一种方式编写您的类,它允许您注入您的数据源,比如:
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);
}
}
If CreateDataSource
gets called in the base constructor, you may have to use a static and be careful about clearing state, but I bet this works as is.
如果在基本构造函数中调用CreateDataSource,您可能需要使用静态方法,并且要注意清理状态,但是我打赌这是正确的。