Unit Testing – How to Test Logic in CRUD Applications

unit testing

Apologies if this question has been asked before, I've seen similar questions, but nothing quite the same.

I am writing a web application which uses http calls to write and read from a back end database, as well as performing operations on the data.

All of my public methods are along the lines of:

writeToDatabase(data){
    performOperationsOnData(data)
    databaseHandler.connectToDatabase()
    databaseHandler.insertDataToDatabase(data)
}

I would like to unit test my performOperationsOnData() method logic, but this is a private method, because it never needs to be called from outside the class.

I have written integration tests, which check that the data is written correctly to the database in general, but when the logic is reasonably complicated I don't really want to be connecting to the database or a mock for every possible path through the logic.

What would be the correct way to test this logic? I am particularly interested in finding out if the structure of the method I have shown should be done differently to make it more testable, or is the answer just lots of mocking and dependency injection for the database?

Similar questions:

How can I use unit tests and TDD to test an app that relies mostly on database CRUD operations?

https://stackoverflow.com/questions/842476/applying-tdd-when-the-application-is-100-crud

Best Answer

It sounds like the logic in performOperationsOnData() could justifiably be put in its own class.

It looks like the class with the writeToDatabase(data) method is currently responsible for too much. It is orchestrating your Business Logic and Data Persistence Logic. Orchestrating is fine, as long as that is the class' only responsibility.

So, here's how I would go forward:

  • Move your Business Logic from performOperationsOnData() to a new class
  • Move your Data Persistence Logic (connectToDatabase() and insertDataToDatabase(data)) to a new class
  • Inject those new classes as dependencies into your current Orchestrator class
  • Unit test the Business Logic class
  • Integration test the Orchestrator class