简体   繁体   中英

How can I detect if an NUnit test is running from within TeamCity?

I need to run some code only if I'm running from within the TeamCity test launcher. What's the easiest way to detect this?

Check if TEAMCITY_VERSION environment variable is defined.

Another approach is to use NUnit categories.

Based on the comment below this code should be able to check if the test is being run by teamcity:

private static bool IsOnTeamCity() 
{ 
    string environmentVariableValue = Environment.GetEnvironmentVariable("TEAMCITY_VERSION"); 
    if (!string.IsNullOrEmpty(environmentVariableValue)) 
    { 
         return true; 
    } 
    return false; 
} 

I'm basically doing that with the following property. It get's the directory name via code base of the calling assembly and if it contains parts of your TeamCity build agent directory it is running within TeamCity.

public static bool IsTeamCity
{
    get
    {
        // the Assembly.GetExecutingAssembly().Location property gives funny results when using 
        // NUnit (where assemblies run from a temporary folder), so the use of CodeBase is preferred.
        string codeBase = Assembly.GetCallingAssembly().CodeBase;
        string assemblyFullPath = Uri.UnescapeDataString(new UriBuilder(codeBase).Path);
        string assemblyDirectory = Path.GetDirectoryName(assemblyFullPath);

        // a full TeamCity build directory would be e.g. 'D:\TeamCity\buildAgent\work\de796548775cea8e\build\Compile'
        return assemblyDirectory.ToLowerInvariant().Contains("buildagent\\work");
    }
}

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