C# – Unit Test for Void which copies data from one location to another

ctddunit testing

Still learning and getting my head around Unit Testing, (also trying to get into TDD, though I appreciate it isn't the same thing) and in many ways it is changing/improving my code. But I come across scenarios where I am unsure how to test a piece of functionality. Which leaves me wondering whether it's my code design that is the issue, or my knowledge of unit testing (plus mocking etc). It could be either here, so I'm looking for advice how to change my code or how to test it, whichever is the right thing to do.

In this case I am writing a void which takes data from one database and loads it into another (both use EF6).

So my _manager.UpdateHissOfficersFromSource() calls the source repository, which gets the data, then calls the target repository to insert the data. The only thing I can think of that might help test it is if the Insert returned a count, which I could then check in the Test.

    public void UpdateHissOfficersFromSource()
    {
        var sourceOfficers = _sourceRepository.GetAllActiveOfficers();

        List<Officer> officers = new List<Officer>(sourceOfficers
            .Select(o => new Officer
            {
                Code = o.officer_code,
                Name = o.officer_name,
                Telephone = o.officer_telephone,
                LastUpdated = DateTime.Now
            }));

        _targetRepository.Add(officers);
    }

I'm using Mock, but I doubt that matter which I'm using.

UPDATE:

So based on the replies, this is what I've done, which passes. Is it sufficient?

public void UpdateActionOfficersDataFromConfirm()
    {
        _officerManager.UpdateHissOfficersFromConfirm();
        _sourceRepository.Verify(mock => mock.GetAllActiveOfficers(), Times.Once());
        _targetRepository.Verify(mock => mock.Add(It.IsAny<List<Officer>>()), Times.Once());
    }

Best Answer

Do you inject the target repository (i.e. are you using dependency injection)

If so, you should be able to assert that _targetRepository.Add(officers) is called by querying your mocked target repository.

This is a common problem and pattern for a solution in testing. Dependency injection helps you solve this since your test can provide the mocked repository to your test class, provide results for method calls on this mock and provide assertions on methods called on this mock.

Here's how you do this in Moq:

mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

Returning the list that you've called _targetRepository with is all very well, but what guarantee do you have that you've called _targetRepository with that list

Related Topic