I wrote a desktop application which basically is a front end for database. It is used for create, read, update operations of different linked objects and performs some simple calculation and data aggregation. The MVVM pattern was followed in order to simplify testing.
This morning I tried writing the first test and realized it was not simple as expected.
Unit tests are great for checking the result of a single operation, but unfortunately I have to deal with complex objects which are linked together.
I will try to explain my problems better.
1) I can create and test an object of class A. If I repeat the test 100 times my database becomes polluted. I need automatic procedures to clean it.
2) Objects of class B needs an object of class A for some operations. I don’t think it is a good idea to write a test where both objects A and B are created. what I supposed to be the right way is to use the object created at point 1 as a prerequisites for this test.
I switched to visual studio 2012 express because it has basic support for unit tests but I need some guidelines on how to better use it for my special needs.
Thanks
Filippo
Writing unit tests for ‘legacy’ code (code without unit tests) can be really hard.
The problem is that unit testing is all about testing single classes in complete isolation without any dependencies on other code.
For example:
This small code example is impossible to unit tests because it depends on a real database being accessible. These kind of tests are called integration tests. They are important and definitely have their uses but they are not unit tests.
One of the big patterns that you can use to improve code for testability is Inversion Of Control. This means that you inject dependencies into a class by using some container object that manages the lifetime of these dependencies.
In your Unit Test you can use tools like Moq to fake those dependencies and make them easily testable.
I wrote an article about this some time ago which goes into more depth. Maybe it can help: Unit Testing, hell or heaven?