简体   繁体   中英

How to unit test that a project does not reference a specific assembly

We separate some interfaces in a library of its own and do not want that the libraries with the implementation are referenced directy in the calling project.

A: calling code project. B: interface project. C: implementation project

A should reference B but not C

We want to ensure this with a unit test.

What would a unit test look like with NUnit?

Can't say I've ever done this. You could try using Assembly.GetReferencedAssemblies ?

This answer is just to remember the unit test for my own usage. But feel free to upvote :-)

[Test]
public void ShouldNotReferenceServiceProjectDirectly()
{
    var assembly = GetAssemblyContainingType<RouteConfig>();
    var referencedAssemblies = assembly.GetReferencedAssemblies();

    var implementationAssembly = referencedAssemblies
        .FirstOrDefault(x => x.Name == "MyNamespace.Service");

    var interfaceAssembly = referencedAssemblies
        .FirstOrDefault(x => x.Name == "MyNamespace.Service.Interfaces");

    Assert.That(implementationAssembly, Is.Null);
    Assert.That(interfaceAssembly, Is.Not.Null);
}

private static Assembly GetAssemblyContainingType<T>()
{
    return (typeof(T).Assembly);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM