What is the best way to unit test heavily database dependant .NET middleware? E.g. a process which reads data from multiple databases, manipulates it, and then combines and writes it to other databases?
Should the databases be filled with static data which is somehow reset on each unit test run? Should the whole SQL Server access be somehow mocked? Is it not feasible to unit test such an application in the real world?
Unit tests shouldn't depend on infrastructureThere's no way to test this function without a database connection available at the time of testing. If a new developer clones the project they will need to set up a database before they can successfully run the unit tests.
xUnit is a free, open-source, community-focused unit testing tool for . NET. The original inventor of NUnit v2 wrote xUnit.net. xUnit.net is the latest technology for unit testing .
The Assert. Equal() method is a quick way to check whether an expected result is equal to a returned result. If they are equal, the test method will pass. Otherwise, the test will fail.
Unit tests should never connect to a database. By definition, they should test a single unit of code each (a method) in total isolation from the rest of your system. If they don't, then they are not a unit test.
The answer is mocking
However the way to do this I have found is as follows.
Separate the DAL into 2 layers. The bottom simply performs atomic read and writes to the databases - these objects all implement a set of interfaces IReadFromDB and IWriteToDB.
Then you can create your read and write business logic in a higher DAL level but rather than reference the objects that will read and write to the database reference the interfaces and use properties to be able to substitute functionality. I tend to include the desired functional objects in the constructors so that things work 'out of the box' so to speak.
This will make it a cinch to 'swap out' the functionality and so to unit test the business logic.
As for testing the DB read and writes ... I haven't found a way that doesn't involve work. I usually use a different connection string to a copy of the database and then write data generation and cleanup code for unit tests to leave the state of the db the same as before and after.
Yes, its time consuming ... however it doesn't risk alienating a client. It depends on your priorities.
Someone else mentioned performance testing. I would not consider this to be part of a unit test. I usually do this with a test harness in combination with debug code simply because performance of small parts is often misleading - when you move to the big picture the parts that are actually casing problems are often not the parts that localised testing would flag in my experience.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With