0

I used test as below. I have one big method for initialize whole dbcontext (it is larger than pasted below, it is similar, but with more models and acces to each dbsets for MoQ Verify) something like fake db. Next I inject it to service and call method that using it.

Is it correct way for testing services (that using dbcontext) with unit tests? And if it is not correct, what is good way for testing services like this (maybe only write test that connect to real db)?

My Test:

[Test]
public void ExampleServiceTest()
{
    var mock = InitializeMockContext();

    var service = new TagsService(mock.Object);
    var result = service.GetTags(2);
    var expectection = 2;

    Assert.AreEqual(expectection, result.Id);
}

Method that create mocked DBContext:

public Mock<MyDBContext> InitializeMockContext()
{
    var mock = new Mock<MyDBContext>();
    var mockDataTags = new List<Tags> {
        new Tags { Id = 1, Count = 3 },
        new Tags { Id = 2, Count = 2} }.AsQueryable();
    var mockSet = new Mock<DbSet<Tags>>();
    mockSet.As<IQueryable<Tags>>().Setup(m => m.Provider).Returns(mockDataTags.Provider);
    mockSet.As<IQueryable<Tags>>().Setup(m => m.Expression).Returns(mockDataTags.Expression);
    mockSet.As<IQueryable<Tags>>().Setup(m => m.ElementType).Returns(mockDataTags.ElementType);
    mockSet.As<IQueryable<Tags>>().Setup(m => m.GetEnumerator()).Returns(mockDataTags.GetEnumerator());
    mock.Setup(x => x.Tags).Returns(mockSet.Object);
    //I have more than just one model here
    return mock;
    }

MyService:

public class TagsService
{
    private readonly MyDBContext _ctx;
    public TagsService(MyDBContext ctx)
    {
        _ctx = ctx;
    }
    public Tags GetTags(int count)
    {
        using (var db = _ctx)
        {
            return db.Tags.First(x => x.Count == count);
        }
    }
}
Wojciech Rak
  • 540
  • 3
  • 17
  • Possible duplicate of [What's the difference between unit tests and integration tests?](https://stackoverflow.com/questions/5357601/whats-the-difference-between-unit-tests-and-integration-tests) – Hasan Dec 30 '18 at 20:10
  • Ok, I it's probably unit tests, or mixed. But it's not the most important in this question, the most important part is, is it correct way? – Wojciech Rak Dec 31 '18 at 07:32
  • Actually it is up to you and what you wanna make sure with unit or integration tests. If you wanna make sure some piece of your code works as you expected and output is also is expected, unit test is the correct decision. On the other hand if you wanna make sure a scenario in your program works properly (like updating db and evaluating new output) with a few parts of your code combined, integration test is way to go. In my opinion, you should write integration tests to ensure what you described in your question, bc you wanna make sure that db is initialized correctly in server not in run time. – Hasan Dec 31 '18 at 08:37

0 Answers0