I am really new to unit testing, and I can't figure out the proper way to do it for my case, though I spent crazy amount of time on research.
My code base is huge (~3 years of work), very coupled unfortunately, hard to test and no unit testing has ever been done on it.
So for instance, when trying to test a collection class ProductCollection
, more specifically, the bool MoveElementAtIndex(Product productToMove, int newIndex)
of it, I am encountering the following problems:
- first I have to initialize this
new ProductCollection()
- the constructor initializes another hand made class:
new KeyedList<ID, Product>
. I suppose this should not be called within this constructor, since I'm not testingKeyedList
. - next, I am trying to add 3 products to this
ProductCollection
. - I am then first creating these 3
new Product()
. - But the constructor of
Product
class does several things - It computes a unique ID for the newly created product:
this.ID = IDUtils.ComputeNewIDBasedOnTheMoonPhase()
. I suppose I should not test this neither, since it's not my scope. How should I avoid such calls at this level of deepness? - The same Product constructor assigns some default properties for this product:
this.Properties = new ProductProperties(folderPathToDefaultProperties)
. This should not be called from my simpleFieldCollection.MoveElementAtIndex
test, right? - Let's say I finally have my product objects now, and I'm trying to add them to my collection.
- But the
ProductCollection.Add(MyProduct)
checks if the underlyingKeyedList
already contains the product. This is also business logic that I should avoid, not being related to my test. The question is how? - Also, in this
Add
method, some events are raised, notifying the system about several things (e.g., that a new product was added to the collection). These should also not be fired at all I suppose. - And then finally, when I have my products added, I'm calling the desired SUT: the move elements method.
- But this method also has logic that can be out of scope for my test: it verifies that the underlying
KeyedList
actually contains those fields, it callsKeyedList.Remove()
,KeyedList.Insert()
for its moving logic, and it fires events likeCollectionModified
.
If you could just explain me how to do this unit test properly, how to avoid underlying objects from being called, I would really appreciate it.
I am thinking of Microsoft's Moles framework (VS2010), since I have the impression that it does not require me to refactor everything, as this is absolutely not an option. But having tried it already, still can't find a proper way to use it.
Also, I have the impression that this concrete example will help many in my situation, because this is how code in real world usually is.
Any thoughts?