Nuke Build with xUnit and .net 6.0 - .net-6.0

I was wondering if it is possible to make nuke build work with xUnit under .net 6.0
after installing the package nuke :add-package xunit.runner.console
and using from a Test Target by XunitTasks.Xunit2(assemblies); I get the following exception:
System.ArgumentException: Package executable xunit.console.exe [xunit.runner.console] requires a framework:
- net452
- net46
- net461
- net462
- net47
- net471
- net472
at Nuke.Common.Assert.True(Boolean condition, String message, String argumentExpression) in /_/source/Nuke.Common/Assert.cs:line 34
will xunit.runner.console be updated to net6.0? Are there any workarounds?
Thanks!

I think I have figured it out.
assuming the test project names end with *.Tests:
...
Target Test => _ => _
.DependsOn(Compile)
.Executes(() =>
{
var projects = Solution.GetProjects("*.Tests");
foreach (var project in projects)
{
DotNetTest(_ => _
.SetProjectFile(project.Path)
.SetConfiguration(Configuration)
.EnableNoBuild()
);
}
});
so instead of using the xUnit tool explicitly, DotNetTest function executes the same tools (xUnit, NUnit, MSTest, etc.) as if the solution/project runs it by itself, and most likely it does not matter which version of .net is used.

Related

No test is available in dll, Make sure that installed test discoverers & executors, platform & framework version

I am trying to run a test from azureDevop pipeline and I am getting the error:
Warning: No test is available in D:\data\CHT.....\myTest.dll. Make sure that installed test discoverers & executors, platform & framework version settings are appropriate and try again
Those are the nugets I use in myTest project:
This is what I have in the output directory:
In myTest.cs file I have a test method:
[TestMethod]
public void ValidateLoading()
{
driver.Navigate().GoToUrl(urlToTest);
}
I can run it locally in VS. Only when this checkbox is disable (in tools->options):
What am I missing?

Should GetEnvironmentVariable work in xUnit tests?

If I set environment variables for a .Net Core web project in Visual Studio 2017 using the project properties page, I can read the value of the variable using Environment.GetEnvironmentVariable; however, when I set the environment variable for my xUnit testing project and then debug the test, Environment.GetEnvironmentVariable always returns null. Is there something about the fact that it is a testing project that should prevent the variable from being used the same as with the web project? If so, is there a way that I can set the environment variables for a test project? Thank you.
The GetEnvironmentVariable works fine in xUnit tests. The problem is to properly set a variable. If you set the variable at Properties -> Debug page, then the variable is written to Properties\launchSettings.json and Visual Studio makes all work to launch an application with the selected profile. As you could see, launchSettings.json even isn't copied to output folder by default. It's impossible to pass this file as argument to dotnet run or dotnet test, that leads to obvious problem if tests are run automatically on a CI server. So it is not surprising that launchSettings.json isn't considered by a test runner.
Solution: there are a lot of ways to setup a test environment in xUnit:
Constructor
Base class
Fixture
For example, this collection fixture sets up all environment variables from launchSettings.json:
public class LaunchSettingsFixture : IDisposable
{
public LaunchSettingsFixture()
{
using (var file = File.OpenText("Properties\\launchSettings.json"))
{
var reader = new JsonTextReader(file);
var jObject = JObject.Load(reader);
var variables = jObject
.GetValue("profiles")
//select a proper profile here
.SelectMany(profiles => profiles.Children())
.SelectMany(profile => profile.Children<JProperty>())
.Where(prop => prop.Name == "environmentVariables")
.SelectMany(prop => prop.Value.Children<JProperty>())
.ToList();
foreach (var variable in variables)
{
Environment.SetEnvironmentVariable(variable.Name, variable.Value.ToString());
}
}
}
public void Dispose()
{
// ... clean up
}
}
Set Copy to output directory: Always for launchSettings.json to make the file accessible from tests.
A solution for using environment variables in unit tests, for either mstest or xunittest, is through the ".runsettings" file provided for the platform:
UPDATE:
This works only for mstest.
Add a file with .runsettings extension in the project:
Configure environment variables in file "xxx.runsettings" created:
<!-- File name extension must be .runsettings -->
<RunSettings>
<RunConfiguration>
<EnvironmentVariables>
<!-- List of environment variables we want to set-->
<VARIABLE_XXXX>value X</VARIABLE_XXXX>
<VARIABLE_YYYY>value Y</VARIABLE_YYYY>
</EnvironmentVariables>
</RunConfiguration>
</RunSettings>
Add RunSettingsFilePath tag in test .csproj pointing to the .runsettings file.
Important: the path is absolute.
Using $(MSBuildProjectDirectory) variable will return the absolute path to the project diretory.
Another options to use .runsettings are in link below:
https://learn.microsoft.com/pt-br/visualstudio/test/configure-unit-tests-by-using-a-dot-runsettings-file?view=vs-2019
Great thread helped me find the adapted solution for me.
I needed something that works well for local dev / tests (using VS code) JSON file works fine.
I also needed something that can be used with CI/CD and deployment; environment variables were needed.
My fixture class needs the environment variable to be able to run the tests in the different environments.
I'm using the same principle #Ilya Chumakov except with System.Text.Json (in 2022 using .NET 6...)
I thought that sharing it might help save other people some time:
if (File.Exists(Directory.GetCurrentDirectory()+"/local.settings.json")){
using var file = File.Open(Directory.GetCurrentDirectory()+ "/local.settings.json",FileMode.Open);
var document = JsonDocument.Parse(file);
var variables = document.RootElement.EnumerateObject();
foreach(var variable in variables){
Environment.SetEnvironmentVariable(variable.Name, variable.Value.ToString());
}
}
All the needed variables are at the root of the local.settings.json. adapt if you use it for a lot of things, easy to add an "env" property which contains all your environment variable and just read from it.
For those who use VS code like me. Don't forget to add to your .csproj:
<ItemGroup>
<Content Include="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
Took me also a bit of tinkering to find that out.

'Cannot find module' TypeScript after VS 2015 Update 3

I have two TypeScript files in my project
In first file I wrote
import moduleB = require('moduleB');
class ModuleA {
//some logic
}
In second file
/// <amd-module name="moduleB" />
class ModuleB {
//some logic
}
export = ModuleB
I build my ts files via gulp
gulp.src('./JScripts/**/*.ts')
.pipe(srcmaps.init())
.pipe(ts({
noImplicitAny: false,
target: 'ES5',
module: 'amd'
})).js
All works fine, and intellisense was fine in VS 2015 Update 2. After update on VS 2015 Update 3 all works same - fine, but intellisense goes crazy.
There is an error 'Cannot find module 'moduleB'' for first file
As far as I can understand I should check my .tslint file because I don't use VS Typescript Build (I use Gulp instead)
How can I fix this error?

sonar c# eco system: how to specify diffent binaries folder

I am actually evaluate sonar (sonarsource.org) for using it with c#.
Is it possible to specify a different binaries folder (MsBuild OutDir Property) for csharp projects? I use a custom OutDir on our build server to have the binaries/Buildoutput of every csharp project in one place.
Tried (with java runner and sonar-project.properties)
binaries=Binaries
And
sonar.gendarme.assemblies=Binaries/*.*
sonar.fxcop.assemblies=Binaries/*.*
BTW: how to specify search paths for gallio code coverage? My test assemblies are also not in bin/Debug.
Any Ideas?
Found out that wild cards aren't possible. But: should the path to the assembly be relative or absolute? Relative...
File basedir = (vsProject == null) ? solution.getSolutionDir() : vsProject.getDirectory();
...
File file = new File(basedir, filePath);
But still no success with
sonar.fxcop.assemblies=../Binaries/Assembly1.dll;../Binaries/Assembly2.dll

Sort Visual Studio build log in "Build Order" style

There is a "Show output from" dropdown list in Visual Studio 2008 "Output" window, which allows viewing build events ordered by thread (Build Order). This is very useful when building big solutions on multi-core machines, as the log entries from those come unsynchronized.
Our organization has the automated build process, where solution(s) are compiled in a batch mode, using something like:
devenv Solution.sln /USEENV /build Release /out buildlog.txt
This will load Solution.sln, buld it in Release configuration and output build log into buildlog.txt.
Problem is: buildlog.txt is an output resembling "Build" output, not "Build Order", and therefore, it is pretty hard to read. Is there a command-line filter or something, which would convert output to "Build Order" format?
Use simple filter, something like that:
static void Main(string[] args)
{
var lines = new Dictionary<int, StringBuilder>();
var line = Console.In.ReadLine();
while (line != null)
{
int process = 0;
var re = new Regex(#"^(?<process>\d+)\>.*$");
if (re.IsMatch(line))
{
var match = re.Match(line);
process = Convert.ToInt32(match.Groups["process"].Value);
}
if (!lines.ContainsKey(process))
{
lines[process] = new StringBuilder();
}
lines[process].AppendLine(line);
line = Console.In.ReadLine();
}
foreach (var i in lines.Keys)
{
Console.Write(lines[i]);
}
}
I don't know whether this will solve the formatting issue, but you could try using msbuild instead of devenv, with a command line such as:
msbuild Solution.sln /p:Configuration=Release /logger:XMLLogger,C:\Loggers\MyLogger.dll;OutputAsHTML
See the documentation for msbuild for information on the logging options. You may find that this will give you the ability to have a more sensible output.
I don't think Walter's answer works for all the situation, because I've seen the problem when building C# projects and VS prints the Compile results withouth any process ID! such as
1>------ Build started: Project: MyProj, Configuration: Debug Any CPU ------
Compile complete -- 1 errors, 0 warnings
Please note that I removed most of other outputs but imagine you're building a lot of projects and Compile complete line is not inserted right after the correct project, how would you find which project Compile complete belongs?

Resources