How can I isolate a data source such as DbSet?

I have several controllers that I'm testing, each of which has a repository dependency. This is how I deliver the mock repository for each test fixture:

[SetUp]
public void SetUp()
{
    var repository = RepositoryMockHelper.MockRepository();
    controller = new HomeController(repository.Object);
}

And here is a helper method MockRepositoryfor a good measure:

internal static Mock<IRepository> MockRepository()
{
    var repository = new Mock<IRepository>();

    var posts = new InMemoryDbSet<Post>()
    {
        new Post {
            ...
        },
        ...
    };

    repository.Setup(db => db.Posts).Returns(posts);

    return repository;
}
... = code removed for the sake of brevity. 

I intend to use a new instance InMemoryDbSetfor each test. I thought using an attribute SetUpwould achieve this, but obviously would not.

When I run all the tests, the results are incompatible because the tests do not seem to be isolated. One test, for example, will remove an item from the data store and claim that the counter has been lowered, but according to the whim of the test runner, another test may increase the count, which will cause both tests to fail.

? ?

+4
3

InMemoryDataSet static backing data, . . , ( ), HashSet , .

, , . , , ( SetUp), . , , Foo , , SetUp, , , . , , , @BillSambrone.

+3

@PatrickQuirk, , , InMemoryDbSet .

" ?" :

, , - IDbSet, , , . IDbSet , . IEnumerable - .

, , , Posts -. - , Get(), Add() .. , , , , , .

+2

Everything that is in your [SetUp] method will be called for each test. This is probably a behavior you don't need.

You can put the code that you have in the [SetUp] method inside each individual test, or you can create a separate private method in your unit test class that will unwind the recently ridiculed DbSet so that you save DRY stuff.

+1
source

Source: https://habr.com/ru/post/1547476/


All Articles