I'm working on a tool that needs to extract the NUnit tests names that are contained in an assembly.
As I need the exact name of the tests when they are run, and NUnit's way of naming the tests is not straightforward, I use the NUnit TestEngine to explore the assembly.
Something like that :
Assembly testAssembly; //loaded somewhere else
using var testEngine = new TestEngine();
testEngine.WorkDirectory = Path.GetDirectoryName(testAssembly.Location);
var package = new TestPackage(testAssembly.Location);
using var runner = testEngine.GetRunner(package);
var testsFound = runner.Explore(new TestFilter(string.Empty));
I build the whole tool with one of our projects as test subject, and it works well.
But when I try it on other similar projects (.Net 6, NUnit test projects for a web API), I have the following error :
Unable to load one or more of the requested types.
Could not load file or assembly 'Microsoft.AspNetCore.Hosting.Abstractions, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The system cannot find the file specified.
The tests run properly inside the Visual Studio, with VS test runner or Resharper.
The current directory is set to the bin folder.
Looking at the project, it seems that this is a implicit dependency of Microsoft.AspnetCore.Hosting (referenced by AppInsight)
But :
I don't see any version 6.0.0.
I have another similar project that loads properly and have the exact same dependencies
I can't find any Nuget package that has this version (highest is 2.2.0), so I can't force the reference.
The Assembly loads properly (with Assembly.LoadFrom()), it fails in NUnit, when it tries to call LoadTests
I can't find where this reference is needed and why one solution is working and others are not, while they are very similar !
I'm out of ideas to make it work, so I'm looking for suggestions.
Have you considered simply telling NUnit to produce the list of tests for you?
The --explore option followed by a file name creates XML output but without a following name it produces a readable list of names on the console. You can redirect the output to a file if that's what you want.
nunit3-console yourtests.dll --explore
UPDATE
Make sure you use the standard .NET Framework build of NUnit3-console with the above option, not the .NET 6.0 build. The standard runner creates whatever process is needed to properly explore the test assembly.
So I'm trying to set up a project using the NDepend API for some metrics on my code (Which works nicely), however, when I attempt to run a testing framework (NUnit) over it, I'm getting TypeInitializationExceptions thrown.
Here is some code to reproduce the errors I'm getting:
Create a class library project, and reference the NDepend API dll at $NDependInstallPath$\lib\NDependAPI, setting copy local to false. Create a class as follows:
public class NDependProjectLoader
{
public void LoadAnNDependProject()
{
var provider = new NDependServicesProvider();
}
}
Create a second class library project in the solution that will be your Test class. Reference NUnit and the project you created that references the NDependAPI
[TestFixture]
public class NDependProjectLoader_Tests
{
[Test]
public void I_can_load_an_depend_project()
{
new NDependProjectLoader().LoadAnNDependProject();
}
}
Build, and run the test using your test runner of choice (I've tried Resharper's test runner and the NUnit GUI).
You will get a TypeInitializationException on the line var provider = new NDependServicesProvider();
Looking inside that TypeInitializationException shows that the root exception's message is:
"{"Could not load file or assembly 'NDepend.Platform.DotNet' or one of its dependencies. The system cannot find the file specified.":"NDepend.Platform.DotNet"}".
Adding the AssemblyResolverHelper from the NDepend.PowerTools sample project and calling it as described in the getting started guide doesn't change the behaviour.
I /assume/ that the problem is related to this statement in the NDepend API getting started guide at http://www.ndepend.com/api/NDepend.API_gettingstarted.html
"The program executable assembly must be generated into $NDependInstallPath$\"
In the case where the code is started from a test runner the executable will not be in the ndepend install path.
Calling NDependProjectLoader.LoadAnNDependProject() from a console application whose .exe is generated in $NDependInstallPath$\lib\ (note that the .exe seems to need to be generated in the \lib\ subfolder not in $NDependInstallPath$\ as stated in the getting started guide) does not produce the exception, which further points to this being the cause.
So, the question is, how does one work with the NDepend API from anything other than a console application? For example, here I want to do so from a test runner. Another obvious candidate is an IIS application. Am I missing something obvious?
Indeed the problem comes from assembly resolution.
You must tell the CLR where to find NDepend assemblies (i.e in the dir $NDependInstallPath$\Lib)
You have 2 choices to do this. Suppose $NDependInstallPath$ is "C:\NDepend" just for example:
Either edit AssemblyResolverHelper to resolve assemblies in "C:\NDepend\Lib"
Either create a App.Config file for your exe, add a <probing> element that refers to "C:\NDepend\Lib". When the CLR won't resolve an assembly, then it'll look at dir in such element
I am testing that I am using the correct dll interface for a ThirdParty.dll but using a mocked unmanaged dll in some unit tests. The ThirdParty.dll is imported using DllImport("ThirdParty.dll") inside the production code. The mock dll is placed in the same directory as the NUnit test code, the working directory of the command line set to the same directory as the Test Dll and mock dll, and then NUnit is called with a full path.
Example:
TestDirectory contains:
Test.dll
nunit.framework.dll
pnunit.framework.dll
ThirdParty.dll
and some other dependencies.
and the following is called:
C:\TestDirectory>ProgFiles\NUnit\nunit-console-x86.exe Test.dll /config:Release /framework:net-4.0
On our development machines the mock version of ThirdParty.dll is picked up fine and our tests pass but when we put the same code and directory structure on the customer computer it picks up the real installed version of the dll instead, which we also have installed on our dev machines but gets blocked by the mock one during unit tests.
I'm aware of the Search Order used by Windows, but I think that in both instances the DLL should be found in step 1 "The directory from which the application loaded.". I'm also aware of picking up the same name DLL if it is in memory, but I believe this applies if it is in the same process memory, which it should not be.
Does anyone have any ideas on what I could check or what might be causing this?
Thanks
The search order for dynamic link libraries can be found here. It's always the same, but it does depend on operating system settings, so with two different machines with different settings, you may get different results.
Use the fusion log viewer to get a more detailed view into how your assembly is being found. The viewer will list all paths your application is searching to load an assembly and where they were found. This always give me an answer when I have unexpected DLL dependency problems.
My question is relevant to this question, but I've somehow moved a step further and implemented a test framework using nunit.
When I run the test framework addin inside Revit, the testing framework somehow locks the test assemblies making it impossible to recompile the test assemblies. To get around it, I tried making a shadow copy so the nunit test runner runs on the copied assemblies. But once I run the tests for the first time, the subsequent test runs does not work on updated copies. It is like the test runner caches the dlls and always tries to run tests on cached copy.
So each time the test assembly is updated, I need to close-reopen Revit to run the tests which is a real pain. The main reason I implemented the testing framework for Revit was to be able to do BDD/TDD using Revit API.
This is a code snippet of how I run the tests:
TestPackage theTestPackage = new TestPackage(testDll);
RemoteTestRunner testRunner = new RemoteTestRunner();
testRunner.Load(theTestPackage);
TestResult testResult = testRunner.Run(new NullListener());
Does anyone have any idea how to solve this?
You can try loading the assemby for testing with the Assembly.Load(byte[]) method. I'm not sure if your test runner can handle this, but this will give you an assembly to work on that is loaded from a byte stream in memory. Therefore the original assembly file can be recompiled anytime and you can have as many concurrent versions of this assembly loaded as you like. They are all separate, with separate types.
I use a similar strategy with the RevitPythonShell script loadplugin.py for loading plugins at runtime and then exercising them for testing. This seems to work quite well except for WPF controls defined in XAML. I suspect the XAML parser and loader keeps a cache of the types, but haven't been able to look into this yet due to time constraints.
To preface, I've been working with C# for a few months, but I'm completely unfamiliar with concepts like deployment and assemblies, etc. My questions are many and varied, although I'm furiously Googling and reading about them to no avail (I currently have Pro C# 2008 and the .NET 3.5 Platform in front of me).
We have this process and it's composed of three components: an engine, a filter, and logic for the process. We love this process so much we want it reused in other projects. So now I'm starting to explore the space beyond one solution, one project.
Does this sound correct? One huge Solution:
Process A, exe
Process B, exe
Process C, exe
Filter, dll
Engine, dll
The engine is shared code for all of the processes, so I'm assuming that can be a shared assembly? If a shared assembly is in the same solution as a project that consumes it, how does it get consumed if it's supposed to be in the GAC? I've read something about a post build event. Does that mean the engine.dll has to be reployed on every build?
Also, the principle reason we separated the filter from the process (only one process uses it) is so that we can deploy the filter independently from the process so that the process executable doesn't need to be updated. Regardless of if that's best practice, let's just roll with it. Is this possible? I've read that assemblies link to specific versions of other assemblies, so if I update the DLL only, it's actually considered tampering. How can I update the DLL without changing the EXE? Is that what a publisher policy is for?
By the way, is any of this stuff Google-able or Amazon-able? What should I look for? I see lots of books about C# and .NET, but none about deployment or building or testing or things not related to the language itself.
I agree with Aequitarum's analysis. Just a couple additional points:
The engine is shared code for all of the processes, so I'm assuming that can be a shared assembly?
That seems reasonable.
If a shared assembly is in the same solution as a project that consumes it, how does it get consumed if it's supposed to be in the GAC?
Magic.
OK, its not magic. Let's suppose that in your solution your process project has a reference to the engine project. When you build the solution, you'll produce a project assembly that has a reference to the engine assembly. Visual Studio then copies the various files to the right directories. When you execute the process assembly, the runtime loader knows to look in the current directory for the engine assembly. If it cannot find it there, it looks in the global assembly cache. (This is a highly simplified view of loading policy; the real policy is considerably more complex than that.)
Stuff in the GAC should be truly global code; code that you reasonably expect large numbers of disparate projects to use.
Does that mean the engine.dll has to be reployed on every build?
I'm not sure what you mean by "redeployed". Like I said, if you have a project-to-project reference, the build system will automatically copy the files around to the right places.
the principle reason we separated the filter from the process (only one process uses it) is so that we can deploy the filter independently from the process so that the process executable doesn't need to be updated
I question whether that's actually valuable. Scenario one: no filter assembly, all filter code is in project.exe. You wish to update the filter code; you update project.exe. Scenario two: filter.dll, project.exe. You wish to update the filter code; you update filter.dll. How is scenario two cheaper or easier than scenario one? In both scenarios you're updating a file; why does it matter what the name of the file is?
However, perhaps it really is cheaper and easier for your particular scenario. The key thing to understand about assemblies is assemblies are the smallest unit of independently versionable and redistributable code. If you have two things and it makes sense to version and ship them independently of each other, then they should be in different assemblies; if it does not make sense to do that, then they should be in the same assembly.
I've read that assemblies link to specific versions of other assemblies, so if I update the DLL only, it's actually considered tampering. How can I update the DLL without changing the EXE? Is that what a publisher policy is for?
An assembly may be given a "strong name". When you name your assembly Foo.DLL, and you write Bar.EXE to say "Bar.EXE depends on Foo.DLL", then the runtime will load anything that happens to be named Foo.DLL; file names are not strong. If an evil hacker gets their own version of Foo.DLL onto the client machine, the loader will load it. A strong name lets Bar.EXE say "Bar.exe version 1.2 written by Bar Corporation depends on Foo.DLL version 1.4 written by Foo Corporation", and all the verifications are done against the cryptographically strong keys associated with Foo Corp and Bar Corp.
So yes, an assembly may be configured to bind only against a specific version from a specific company, to prevent tampering. What you can do to update an assembly to use a newer version is create a little XML file that tells the loader "you know how I said I wanted Foo.DLL v1.4? Well, actually if 1.5 is available, its OK to use that too."
What should I look for? I see lots of books about C# and .NET, but none about deployment or building or testing or things not related to the language itself.
Deployment is frequently neglected in books, I agree.
I would start by searching for "ClickOnce" if you're interested in deployment of managed Windows applications.
Projects can reference assemblies or projects.
When you reference another assembly/project, you are allowed to use all the public classes/enums/structs etc in the referenced assembly.
You do not need to have all of them in one solution. You can have three solutions, one for each Process, and all three solutions can load Engine and Filter.
Also, you could have Process B and Process C reference the compiled assemblies (the .dll's) of the Engine and Filter and have similar effect.
As long as you don't set the property in the reference to an assembly to require a specific version, you can freely update DLLs without much concern, providing the only code changes were to the DLL.
Also, the principle reason we
separated the filter from the process
(only one process uses it) is so that
we can deploy the filter independently
from the process so that the process
executable doesn't need to be updated.
Regardless of if that's best practice,
let's just roll with it. Is this
possible?
I actually prefer this method of updating. Less overhead to update only files that changed rather than everything everytime.
As for using the GAC, whole other level of complexity I won't get into.
Tamper proofing your assemblies can be done by signing them, which is required to use the GAC in the first place, but you should still be fine so long as a specific version is not required.
My recommendation is to read a book about the .NET framework. This will really help you understand the CLR and what you're doing.
Applied Microsoft .NET Framework Programming was a book I really enjoyed reading.
You mention the engine is shared code, which is why you put it in a separate project under your solution. There's nothing wrong with doing it this way, and it's not necessary to add this DLL to the GAC. During your development phase, you can just add a reference to your engine project, and you'll be able to call the code from that assembly. When you want to deploy this application, you can either deploy the engine DLL with it, or you can add the engine DLL to the GAC (which is another ball of wax in and of itself). I tend to lean against GAC deployments unless it's truly necessary. One of the best features of .NET is the ability to deploy everything you need to run your application in one folder without having to copy stuff to system folders (i.e. the GAC).
If you want to achieve something like dynamically loading DLL's and calling member methods from your processor without caring about specific version, you can go a couple of routes. The easiest route is to just set the Specific Version property to False when you add the reference. This will give you the liberty of changing the DLL later, and as long as you don't mess with method signatures, it shouldn't be a problem. The second option is the MEF (which uses Reflection and will be part of the framework in .NET 4.0). The idea with the MEF is that you can scan a "plugins" style folder for DLL's that implement specific functionality and then call them dynamically. This gives you some additional flexibility in that you can add new assemblies later without the need to modify your references.
Another thing to note is that there are Setup and Deployment project templates built into Visual Studio that you can use to generate MSI packages for deploying your projects. MSDN has lots of documentation related to this subject that you can check out, here:
http://msdn.microsoft.com/en-us/library/ybshs20f%28VS.80%29.aspx
Do not use the GAC on your build machine, it is a deployment detail. Visual Studio automatically copies the DLL into build directory of your application when you reference the DLL. That ensures that you'll run and debug with the expected version of the DLL.
When you deploy, you've got a choice. You can ship the DLL along with the application that uses it, stored in the EXE installation folder. Nothing special is needed, the CLR can always find the DLL and you don't have to worry about strong names or versions. A bug fix update is deployed simply by copying the new DLL into the EXE folder.
When you have several installed apps with a dependency on the DLL then deploying bug fix updates can start to get awkward. Since you have to copy to the DLL repeatedly, once for each app. And you can get into trouble when you update some apps but not others. Especially so when there's a breaking change in the DLL interface that requires the app to be recompiled. That's DLL Hell knocking, the GAC can solve that.
We found some guidance on this issue at MSDN. We started with two separate solution with no shared code, and then abstracted the commonalities to a shared assemblies. We struggled with ways to isolate changes in the shared code to impact only the projects that were ready for it. We were terrible at Open/Close.
We tried
branching the shared code for each project that used it and including it in the solution
copying the shared assembly from the shared solution when we made changes
coding pre-build events to build the shared code solution and copy the assembly
Everything was a real pain. We ended up using one large solution with all the projects in it. We branch each project as we want to stage features closer to production. This branches the shared code as well. It's simplified things a lot and we get a better idea of what tests fail across all projects, as the common code changes.
As far as deployment, our build scripts are setup to build the code and copy only the files that have changed, including the assemblies, to our environments.
By default, you have a hardcoded version number in your project (1.0.0.0). As long as you don't change it, you can use all Filter builds with the Process assembly (it only knows it should use the 1.0.0.0 version). This is not the best solution, however, because how do you distinguish between various builds yourself?
Another option is use different versions of the Filter by the same Process. You should add an app.config file to the Process project, and include a bindingRedirect element (see the docs). Whenever the Runtime looks for a particular version of the Filter, it's "redirected" to a version indicated in the config. Unfortunately, this means that although you don't have to update the Process assembly, you'll have to update the config file with the new version.
Whenever you encounter versioning problems, you can use Fuslogvw.exe (fusion log viewer) to troubleshoot these.
Have fun!
ulu