Search code examples
c#sqlunit-testingintegration-testing

How do I test a method which has database queries to update data?


I have a method like the following:

public void ImportDataCommand()
{
    // some data validation logic here

    if (some_criteria_is_true)
    {
        // Call to a method which uses sql queries to update some records
        UpdateRecords();
    }
    else
    {
        // Call to a method which uses sql queries to delete some records
        DeleteRecords();
    }
}
  • How can I unit test methods UpdateRecords() and DeleteRecords()? (if possible)
  • Is the current pattern that I have, a smell?
  • Is there a better way to handle, when you have some data update logic, which depends on some data validation logic and some conditional logic?

Update

I am not interested in mocking the data source here. I want to make sure if my SQL queries are correct and are doing the right updates. Sorry for the confusion, if you thought, I wanted to test my validation logic as opposed to my data update logic (SQL).

I do have experience with mocking frameworks and I did use them successfully to write unit tests for my normal application logic.


Solution

  • Your problem starts with the phrase 'as well as'.

    Don't have validation and data access in the same class - delegate the data access to another class and inject it - this way you can mock out the data source when testing your validation.

    class Bar {
    private DataAccessService service
    
    public void Foo()
    {
        // some data validation logic here
    
        if (some_criteria_is_true)
        {
            // Call to a method which uses sql queries to update some records
            service.updateBarRecords();
        }
        else
        {
            // Call to a method which uses sql queries to delete some records
            service.deleteBarRecords();
        }
    }
    
    }
    

    You can then use a mocking framework to test that the correct service methods are called.