Unit test for MVVM with EntityFramework and Effort
I recently started to add unit tests to my application (EF5, MVVM Light,
.NET4.5), and Effort works really nice for testing the Model. But I don't
really know how to test the ViewModel with the fake DBConnection.
My context currently looks like this:
public partial class DataContext : DBContext
{
// Gets used by the ViewModels
public TraceContext() : base("name=DataContext") { }
// Gets used by Effort for unit testing
public TraceContext(EntityConnection connection) : base(connection,
true) { }
}
In my ViewModel it's used (simplyfied) in this way:
public IEnumerable<Measurement> Measurements { get { ... } set { ... } }
public void LoadData()
{
// Get data always from a fresh context on reload,
// to have most recent data from the database
using (var context = new TraceContext())
{
Measurements = context.Measurements.ToList();
}
}
And now the problem is that I don't really know how I should test the code
above, with using the fake database.
[Setup]
public void SetUp()
{
_viewModel = new MeasurementViewModel();
// Only uses the DataContext connection string for EF magic
// not to acctually connect to the database
var connection =
Effort.EntityConnectionFactory.CreateTransient("name=DataContext");
_context = new DataContext(connection);
// Insert test data
...
_context.SaveChanges();
}
[Test]
public void TestLoadData()
{
// Here comes the tricky part, how to tell the ViewModel
// to use the fake Context?
_viewModel.LoadData();
Assert.IsNotEmtpy(_viewModel.Measurements);
}
Is there a good way to handle this without refactoring to much of my code?
No comments:
Post a Comment