0

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.

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.

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);
    }
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Alexander Zanfir
  • 544
  • 5
  • 14

1 Answers1

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.

tallseth
  • 3,635
  • 1
  • 23
  • 24
  • hmmm. That seemed like a great idea, but I tried it, and seems like CreateDataSource does not get called internally, so It never gets called when I instantiate MyDataService in my test. Must be one of the higher service classes calling CreateDataSource. Not sure what the right thing to do here is. I could just use _dataSource instead of CurrentDataSource but not sure if this breaks any principles right now. – Alexander Zanfir Mar 25 '13 at 01:40