0

我当前的解决方案是创建一个具有我的服务/数据业务逻辑的类,使用本地 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);
    }
}

但是由于它们是相同的,因此不需要包装函数。

我想直接测试数据服务,但由于 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);
    }
}
4

1 回答 1

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在基本构造函数中被调用,您可能必须使用静态变量并小心清除状态,但我敢打赌这可以按原样工作。

于 2013-03-24T19:51:11.130 回答