Using MVC3 and EF4, how can one adequately test functionality that relies on a round trip to the database to create IDENTITY values?
I have a scenario where the code under test inserts a record into a database, then attempts to retrieve it back from the database using its primary key.
This happens over a series of records in the same method.
I am mocking my ObjectContext and ObjectSets, so the current result is that each record "inserted" into my FakeObjectSet is given a primary key of 0.
In the case where I am only inserting a single record and asserting the record exists, this is fine...but when I am inserting multiple and my workflow requires retrieving speci开发者_运维技巧fic records by primary key, my queries return multiple results since all inserts have a primary key of 0.
Any ideas?
You can add an event to your FakeObjectSet<T>
that will be raised when AddObject
is called. Then in your test, add an event handler to set the Id
of the object being added.
For example, a simplified version of a fake object set:
public class ObjectAddedEventArgs<T> : EventArgs
{
public T Item { get; set; }
}
public class FakeObjectSet<T>
{
private List<T> _list = new List<T>();
public event EventHandler<ObjectAddedEventArgs<T>> ObjectAdded;
public void AddObject(T item)
{
_list.Add(item);
OnObjectAdded(item);
}
protected virtual void OnObjectAdded(T item)
{
EventHandler<ObjectAddedEventArgs<T>> h = AddingItem;
if (h != null)
{
h(this, new ObjectAddedEventArgs<T> { Item = item });
}
}
// other methods...
}
And in your test, when you want to set an incrementing Id
value, add a handler to your FakeObjectSet<T>
and update the object's Id
:
int id = 0;
FakeObjectSet<Foo> set = new FakeObjectSet<Foo>();
set.ObjectAdded += (s, e) => { e.Item.Id = id++; };
Your mock repository could retrieve the id from an id generator (simple counter), that increments with each consecutive call.
I should stub the return values from the database and so on I will by myself decide what primary keys each object will have.
What is your goal for the tests?
精彩评论