0

Consider this simple method.

    public async Task AddItem(TodoItem item) {
        if(item.DueAt < DateTime.Today) {
            item.ValidationMessages.Add( "The date is missing!" );
            return;
        }

        var mappedVersion = _mapper.Map<TodoItemDto>( item );

        await _todoRepository.Insert( mappedVersion );
    }

How would I test whether the mapped properties (on mappedVersion) act as I assume they should ? I cannot come up with any good solution for this.

This is a very common scenario to be fair.

1
  • did you consider adding a member dueTimeSupplier to object that contains AddItem? You could set it to lambda returning DateTime.Today in main code and to whatever you like in unit tests
    – gnat
    Sep 5, 2017 at 10:34

2 Answers 2

1

With repositories you have an extra output to test. The database.

Its generally not worth trying to insert an extra mockable datalayer between the db and the repo. Instead you have a number of options.

1: Add the Item to the repo and then retrieve it from the repo. check the item is as expected.

This is the simplest approach. You are testing the fundamental requirement of the repository. That it can store items. You don't care how it manages it

2: Hit the database directly in the test to check what was written.

You may have additional requirements, such as the data must be in a particular table, or be encrypted etc. You can use a standard db client to retrieve and check the written database rows after adding the item to the repo.

3: Extract the mapping logic.

If the repo has a dependency on IObjectMapper which is injected. then you can test you mapper class separately from the repo

1

How would I test whether the mapped properties (on mappedVersion) act as I assume they should ? I cannot come up with any good solution for this.

IMO, you should have unit tests for you mapper class. Those tests will validate all possible mapping behaviors on your app.

Also, for the method you provided as example, you could extract its body into another method (not async), which would use the _todoRepository and _mapper as usual, but then you could create unit tests the mock the repository and validate the rest. You could, for instance, provide a dummy mock for the repository, and in the unit test you inspect the content of this dummy repo object in order to check if its info are valid.

Does this approach help you?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.