Getting local path during unit testing

I am creating a C # class (Class.cs) that should look for a file (FileINeedToFind.cs) by name from a local directory. The directory is in another directory from the class file.

Folder structure

:

  Root  
    -> ClassFolder

       -> Class.cs

    -> FileFolder

       -> FileINeedToFind.cs

When I run a test for a class, it always returns with the result of the test results.

How can I get a class to get its own local path, rather than assembling test results?

+4
source share
2 answers

In MSTest, tests (by default) are run in a different folder than the folder containing your code through a test deployment . You can configure the deployment, but I tend to agree with @Jacob that this is not what you usually want to do.

However, I am different @Jacob on how to get the current directory in the test. In MSTest, the correct way to do this is TestContext.DeploymentDirectory .

+3
source

When the program starts, you must assume that the object is not aware of the source code that generated it. The code is compiled into the assembly, and this assembly is loaded when the program starts, so by default the "current" directory is the location of the executing assembly.

In short, this is not something you can do cleanly. Best of all, if your code does not rely on the concept of directories related to the source. This can help you achieve your goals if you change the build action for the file you are looking for to copy it to the output directory. Then this relative file path at run time should reflect the relative path in the project folder.

To get the path to the executing assembly (the "current" path can be changed by any other executable code, so itโ€™s better not to rely on this), use this code:

System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().CodeBase); 
+2
source

Source: https://habr.com/ru/post/1384177/


All Articles