Unit testing legacy code without DI

We are trying to add unit testing to our business layer. The technology stack is asp.net web forms, WCF, calling ADO.Net stored procedures). The business class calls static methods on the data classes, so it makes it difficult to implement DI without making big changes.

This may not be the usual way to do this, but I am thinking of keeping the DB in a unit test (dependencies) but using it as a test Db ... either using an existing frozen db or having mocked data in tables. I was curious about the possibility of using a test db where stored procedures are used as Mocks. Instead of duplicating the entire db, just create table names named by the stored procedure. The stored procedure will just call one table and return static data ... essentially trying to emulate Mocking data functionality with something like Moq, but from a DB perspective.

Can anyone recommend any projects that will include DBs in testing that are still deterministic?

+3


source to share


2 answers


if you want to use a DB in tests and everything needs to be deterministic then you need each test to have its own DB, which means creating (and potentially populating) a new db for each test.

Depending on how your DB tier creates its connection, this is possible. I did a similar thing by creating a DB using localDb in a test setup with a GUID for the name, then deleting the DB again at the end of the test on break.



As a result, it becomes quite slow (not surprisingly), but with this the databases created on the disk with the disk were created.

This worked fine for empty dbs, then it had schemas generated by EF, but if you want a fixed dataset in the DB, you may need to restore it from a backup when setting up the test

+1


source


It seems to me that there will be a lot of work to set up your stored procedures to do what you want them to do when they are called for each test and you still run into the speed issues that databases are always present.I would recommend you do one or both of the following:

  • Use TypeMock , which has a powerful isolator tool. This basically changes your compilation to make it so that your unit test can mock even static methods.
  • Instead of just unit tests, try creating "acceptance tests" that focus on mimicking the full user experience: log in, create an object, view object (check that the object looks correct), update the object, view the object again (same) delete object ( check that the object is deleted). Start each of these tests by setting up all the objects you need for that particular test, and end them by deleting them so that other tests can run based on their assumed initial state.


The first approach gives you the speed and mockery of true "unit" tests, while the second allows you to execute a lot more of your code, increasing the likelihood that you will catch errors, even in things like stored procedures.

0


source







All Articles