Подтвердить что ты не робот

Как получить каталог во время работы unit test

Привет при запуске my unit test Я хочу получить каталог, в котором работает мой проект, для извлечения файла.

Скажем, у меня есть тестовый проект с именем MyProject. Тест, который я запускаю:

AppDomain.CurrentDomain.SetupInformation.ApplicationBase

и я получаю "C:\\Source\\MyProject.Test\\bin\\Debug".

Это близко к тому, что мне нужно. Мне не нужна часть bin\\Debug.

Кто-нибудь знает, как вместо этого я мог бы получить "C:\\Source\\MyProject.Test\\"?

4b9b3361

Ответ 1

Я бы сделал это по-другому.

Я предлагаю сделать этот файл частью решения/проекта. Затем щелкните правой кнопкой мыши → Свойства → Копировать в вывод = Копировать всегда.

Затем этот файл будет скопирован в любой выходной каталог (например, C:\Source\MyProject.Test\bin\Debug).

Edit: Copy To Output = Copy, если Newer - лучший вариант

Ответ 2

Обычно вы получаете каталог решения (или каталог проекта, в зависимости от структуры решения) следующим образом:

string solution_dir = Path.GetDirectoryName( Path.GetDirectoryName(
    TestContext.CurrentContext.TestDirectory ) );

Это даст вам родительский каталог папки "TestResults", созданной в ходе тестирования проектов.

Ответ 3

Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;

Это даст вам каталог, который вам нужен.

а

AppDomain.CurrentDomain.SetupInformation.ApplicationBase 

ничего не дает, кроме

Directory.GetCurrentDirectory().

У вас есть ссылка на эту ссылку

http://msdn.microsoft.com/en-us/library/system.appdomain.currentdomain.aspx

Ответ 4

В дополнение к комментарию @abhilash.

Это работает в моих EXE файлах, DLL и при тестировании из другого проекта UnitTest в режимах отладки или выпуска:

var dirName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location.Replace("bin\\Debug", string.Empty));

Ответ 5

/// <summary>
/// Testing various directory sources in a Unit Test project
/// </summary>
/// <remarks>
/// I want to mimic the web app App_Data folder in a Unit Test project:
/// A) Using Copy to Output Directory on each data file
/// D) Without having to set Copy to Output Directory on each data file
/// </remarks>
[TestMethod]
public void UT_PathsExist()
{
    // Gets bin\Release or bin\Debug depending on mode
    string baseA = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
    Console.WriteLine(string.Format("Dir A:{0}", baseA));
    Assert.IsTrue(System.IO.Directory.Exists(baseA));

    // Gets bin\Release or bin\Debug depending on mode
    string baseB = AppDomain.CurrentDomain.BaseDirectory;
    Console.WriteLine(string.Format("Dir B:{0}", baseB));
    Assert.IsTrue(System.IO.Directory.Exists(baseB));

    // Returns empty string (or exception if you use .ToString()
    string baseC = (string)AppDomain.CurrentDomain.GetData("DataDirectory");
    Console.WriteLine(string.Format("Dir C:{0}", baseC));
    Assert.IsFalse(System.IO.Directory.Exists(baseC));


    // Move up two levels
    string baseD = System.IO.Directory.GetParent(baseA).Parent.FullName;
    Console.WriteLine(string.Format("Dir D:{0}", baseD));
    Assert.IsTrue(System.IO.Directory.Exists(baseD));


    // You need to set the Copy to Output Directory on each data file
    var appPathA = System.IO.Path.Combine(baseA, "App_Data");
    Console.WriteLine(string.Format("Dir A/App_Data:{0}", appPathA));
    // C:/solution/UnitTestProject/bin/Debug/App_Data
    Assert.IsTrue(System.IO.Directory.Exists(appPathA));

    // You can work with data files in the project directory App_Data folder (or any other test data folder) 
    var appPathD = System.IO.Path.Combine(baseD, "App_Data");
    Console.WriteLine(string.Format("Dir D/App_Data:{0}", appPathD));
    // C:/solution/UnitTestProject/App_Data
    Assert.IsTrue(System.IO.Directory.Exists(appPathD));
}

Ответ 6

Я обычно делаю это так, а затем просто добавляю "..\..\" к пути, чтобы перейти к нужной директории.

Итак, что вы можете сделать, это следующее:

var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"..\..\";

Ответ 7

Для NUnit это то, что я делаю:

// Get the executing directory of the tests 
string dir = NUnit.Framework.TestContext.CurrentContext.TestDirectory;

// Infer the project directory from there...2 levels up (depending on project type - for asp.net omit the latter Parent for a single level up)
dir = System.IO.Directory.GetParent(dir).Parent.FullName;

При необходимости вы можете оттуда вернуться обратно в другие каталоги, если это необходимо:

dir = Path.Combine(dir, "MySubDir");

Ответ 9

Лучшее решение, которое я нашел, это поместить файл в качестве встроенного ресурса в тестовый проект и получить его из моего unit test. С этим решением мне не нужно заботиться о путях файлов.

Ответ 10

Обычно вы можете использовать это независимо от того, используете ли вы тестовое или консольное приложение или веб-приложение:

// returns the absolute path of assembly, file://C:/.../MyAssembly.dll
var codeBase = Assembly.GetExecutingAssembly().CodeBase;    
// returns the absolute path of assembly, i.e: C:\...\MyAssembly.dll
var location = Assembly.GetExecutingAssembly().Location;

Если вы используете NUnit, то:

// return the absolute path of directory, i.e. C:\...\
var testDirectory = TestContext.CurrentContext.TestDirectory;

Ответ 11

Мой подход основан на получении местоположения узла модульного тестирования и последующем движении вверх. В следующем фрагменте переменная folderProjectLevel даст вам путь к проекту модульного теста.

string pathAssembly = System.Reflection.Assembly.GetExecutingAssembly().Location;
string folderAssembly = System.IO.Path.GetDirectoryName(pathAssembly);
if (folderAssembly.EndsWith("\\") == false) {
    folderAssembly = folderAssembly + "\\";
}
string folderProjectLevel = System.IO.Path.GetFullPath(folderAssembly + "..\\..\\");

Ответ 12

Вы можете сделать это так:

using System.IO;

Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, @"..\..\"));