Reputation: 7419
I have two separate namespaces in my assembly: DataAccess
and DomainLogic
.
I need a code snippet checking that no class in DomainLogic
depends on the namespace DataAccess
.
How would you dou it?
PS: I think I saw an example for such a unit test in Mark Seemann's awesome book Dependency Injection in .Net, but I don't have it available here and can't find an example via Google.
Edit
Since all reactions so far point out that I should just split these interdependent classes into two different assemblies, I would like to point out that this is currently not an option (although this is indeed one of my main goals in the end). I'm dealing with legacy code and I just can't refactor it in one big bang right now. The separate namespaces and the test for dependencies between them are an intermediate step. As soon as that test passes, I can go ahead and move a part of the code into a different assembly.
Upvotes: 0
Views: 270
Reputation: 1921
There's a tool that does just this: checks namespace dependencies based on your rules and reports violations at build-time as warnings or errors. It's called NsDepCop, free, open-source.
The rule config would look something like this:
<NsDepCopConfig IsEnabled="True" CodeIssueKind="Warning">
<Allowed From="*" To="*" />
<Disallowed From="DomainLogic" To="DataAccess" />
</NsDepCopConfig>
Upvotes: 0
Reputation: 43264
All code within an assembly can legitimately access public and internal code throughout the rest of the assembly. So such unit tests, even if possible, would be a bad idea.
If you split the DataAccess types out into a separate project and made it all internal, then nothing would be able to access it. Clearly not what you'd want. However, by splitting it out, you can ensure that DomainAccess can access DomainLogic, but not vice versa. This presumably is what you want.
In the meantime, rather than try to develop unit tests to check that the rule of "DomainLogic must not access DomainAccess", use code reviews instead. Assuming you are using agile methods (if not, do so!), all activities will be documented as tasks. No task can be considered "done" until someone who understands and embraces your rule has reviewed the code changes for a task. Break the rule and the task fails code review and must be reworked before it's done.
Upvotes: 1