Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could model unit tests be truly independent and how [ASP.NET MVC]

I am new to the whole unit testing stuff, so please excuse my lack of experience. I've read a lot of materials saying that no test should depend on others to do, i.e unit tests be completely independent form each other. Can you really do that in reality? I am having the following example: I have a few entity classes depending on each other, based on a certain database schema (I am using Linq- to SQL to generate them) Now, if I want to test each model class I have to build an object of the model class , build a test object of each of its dependencies, assign them to the object's properties and then persist the object before checking the context and asserting that it actually works.

This obviously makes it much harder to make tests that do not depend on each other, or do not run in a specific sequence (I do not an instance of type Content to be created before I have at least one instance of type ContentType) Dependency, at least on a model level is present and cannot be avoided.

Please, criticize me a lot, if you think that I am wrong. I want to learn.

P.S. Just to mention that I am working on an ASP.NET MVC app and testing with NUnit if that makes sense

like image 952
xantrus Avatar asked Oct 15 '22 08:10

xantrus


2 Answers

Yes, you can really do this in reality.

The key to be able to isolate each unit is in writing loosely coupled code. Taking a dependency on LINQ to SQL (L2S) classes is not loosely coupled, which explains your problems.

You would be better off defining a set of interfaces behind which you can hide your L2S code. The Domain Model then works on those interfaces instead of directly on the L2S classes.

like image 127
Mark Seemann Avatar answered Oct 19 '22 01:10

Mark Seemann


Yes, unit test should (and can) be independent. The problem you describe is about dependency. Dependency should be resolved using Dependency Injection frameworks (see AutoFac, Ninject projects).

The other thing is that your Database should be mocked using mock objects (see Moq, Rhino Mocks projects). You need to test all your code even if you database is disconected.

Other thing is that Unit test should test only one functionality not all your process.

like image 42
Dariusz Avatar answered Oct 19 '22 02:10

Dariusz