I am currently working with Visual Studio Enterprise 2015 Version 14.0.25431.01 Update 3 and have used an MS c# example program to test the built-in unit test and code coverage function. The unit test is working perfectly fine, but everytime I try to start code coverage after the test finished, I get an error message saying:
"Empty results generated: No binaries were instrumented. Make sure the tests ran, required binaries were loaded, had matching symbol files, and were not excluded through custom settings. For more information see: http://go.microsoft.com/fwlink/?LinkID=253731.".
Of course, I checked the link for troubleshooting and worked through all listed issues there, but without any success. I also tried several solutions which should have worked in earlier versions (use command promp to instrument binary or to run code coverage, deleting test results Folder and the VS Solution User Option .suo file, etc.), but still haven't found anything useful working for my case.
Does anybody face the same problem or knows a possible solution for it?
Thank you very much in advance!
Best,
Steve
PS: I am using the standard settings, but with all optimizations turned off. My test project is located in the same solution as my source project I want to test. Here is the code for the example program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace codecoverage
{
public class Program
{
static void Main(string[] args)
{
Program prog = new Program();
prog.TestFunction(0);
}
public int TestFunction(int input)
{
if (input > 0)
{
return 1;
}
else
{
return 0;
}
}
}
}
The Test Class is defined as followed:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using codecoverage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace codecoverage.Tests
{
[TestClass()]
public class ProgramTests
{
[TestMethod()]
public void TestFunctionTest2()
{
Program target = new Program();
int input = 1;
int expected = 1;
int actual;
actual = target.TestFunction(input);
Assert.AreEqual(expected, actual, "CodeCoverage.Program.TestFunction did not return the expected value.");
}
}
}
i have been looking for the solution. and found that it's actually a PDB file problem. all you need to do is to go to this linker tab->debugging. and set option "Generate full program database file" to Yes. this is due to the change VS2015 introduced for /Debug:FASTLINK. setting it to 'yes' would override it.
Related
I've been wrestling with Source Generators but there's a lack of tutorials and information that are hurting.
I want to generate some C# classes from a database. Using a T4 template to do this is difficult and problematic, because of issues I'm having with using SQL in T4 templates and similar.
The description of Source Generator is that "The generator can create new C# source files on the fly that are added to the user's compilation. In this way, you have code that runs during compilation. It inspects your program to produce additional source files that are compiled together with the rest of your code." which seems to match what I want.
This seems significantly more promising.
I've created a project, and put a [Generator] into it using this tutorial.
Full source:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace x
{
[Generator]
internal class TestGenerator : ISourceGenerator
{
public void Execute(GeneratorExecutionContext context)
{
File.Create(#"C:\temp\ITRUNS.TXT");
var sourceBuilder = new StringBuilder(#"
using System;
namespace HelloWorldGenerated
{
public static class HelloWorld
{
public static void SayHello()
{
Console.WriteLine(""Hello from generated code!"");
Console.WriteLine(""The following syntax trees existed in the compilation that created this program:"");
");
Debugger.Launch();
// using the context, get a list of syntax trees in the users compilation
var syntaxTrees = context.Compilation.SyntaxTrees;
// add the filepath of each tree to the class we're building
foreach (SyntaxTree tree in syntaxTrees)
{
sourceBuilder.AppendLine($#"Console.WriteLine(#"" - {tree.FilePath}"");");
}
// finish creating the source to inject
sourceBuilder.Append(#"
}
}
}");
// inject the created source into the users compilation
context.AddSource("helloWorldGenerator", SourceText.From(sourceBuilder.ToString(), Encoding.UTF8));
}
public void Initialize(GeneratorInitializationContext context)
{
}
}
}
I want this to run when I build the solution and create some .cs files
However, it does not run. I put some code in the execute method to create a file, and it does not create the file.
The tutorial says:
Add the source generator from a project as an analyzer and add preview to the LangVersion to the project file like this:
I don't really know what this means. Which project? I tried to download the samples as suggested, but I can't get them to build.
When I examine the code, it's quite hard to understand what they've done that is different.
And what they say in the tutorial about adding the analyzer, doesn't seem to present anywhere in the sample code!
I tried adding the project reference in the csproj that it said to add, however that didn't work - it did create an item within Analyzers but it just has a red - and says 'Ignored' on the tooltip.
I honestly don't know what else I can do to figure out how to get this to work.
I also don't know for sure if it will do what I want - autogenerate a bunch of .cs files with code in that I can use.
I'm going to give it one more go then I'll just write a console application to do it manually instead. Any ideas are welcome.
I am using vs 2019 Community and have created a Class Library (.NET Framework) project named TestDLL.
The project contains a single file "TestDLL.cs" which has TestDLL as a namespace, a public class named MyDll and a single method
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestDLL
{
public class MyDLL
{
static bool Opposite(bool input)
{
return !input;
}
}
}
To the solution I added Unit Test Project (.NET Framework) named UnitTest, added TinyLib_dll.dll as a reference, and created the very simple test.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTest
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
bool start = true;
bool result = MyDLL.Opposite(start);
Assert.AreNotEqual(start, result, "MyDll.Opposite failed");
}
}
}
When I try to run the test, the dll file compiles successfully, but the UnitTest fails with "Error CS0103 The name 'MyDLL' does not exist in the current context UnitTest".
It appears that although I have referenced the dll as a reference it is not being loaded into the test project.
Can someone help me out?
You appear to be missing a TestDLL namespace in the test in order for the test to recognize the subject class
either add a using namespace
using TestDLL;
//...
or use the full name of the type
//...
bool result = TestDLL.MyDLL.Opposite(start);
//...
In my haste to resolve my problem i submitted code samples with simple compilation errors. Correcting these errors resolved my stated problem. However I now have a new issue with the same project, but for clarity I will submit a new question. I offer thanks to Nkosi for his assistance.
I have an NUnit test project dedicated for unit testing which has a Target Framework of .Net Core 2.1. This test project has references of two other Projects one of which is a Windows Form based application and the other is a Class Library based application for database interactions. Both of these projects has a target framework of .Net Framework 4.6.1
I am writing a test for testing a method of the Class Library based application to test the output of the method. But it's showing the following error,
'System.IO.FileNotFoundException : Could not load file or assembly 'System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. The system cannot find the file specified.'
I have tried the following fixes and none of them worked.
Removing the project references and adding them again
Changing build platform target from AnyCPU to X86 and x64
Adding dependant assemblies tag inside a .config file. (Interesting things is .NET Core 2.1 doesn't provide with a .config file)
This is the test class (Test_DataClasses.cs),
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using System.Data.SQLite;
using SharedDataClasses;
using MantechAutomationControl;
using System.IO;
using System.Reflection;
namespace MAC_Testing
{
[TestFixture]
class Test_DataClasses
{
#region Tests
[Test]
public void t_m_initializeDatabase()
{
//Assign
string v_dbLocation = Path.Combine("M:\\For_Jabed\\MAC\\MAC\\MantechAutomationControl\\bin\\Debug\\", "DB.sqlite");
//Act
DataClasses_v2.m_initializeDatabase();
//Assert
Assert.That(new FileInfo(v_dbLocation), Does.Exist);
}
#endregion
}
}
And this is the method the above test is trying to validate,
public static class DataClasses_v2
{
#region Variables
#endregion
#region Methods
public static void m_initializeDatabase()
{
string v_executableLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string v_dbLocation = Path.Combine(v_executableLocation, "DB.sqlite");
if (!File.Exists(v_dbLocation))
{
DialogResult o_createDBFileDialogBox = MessageBox.Show("Could not find the database in the expected location:\n" + v_dbLocation + "\n\nWould you like to create a new blank database file?", "Warning", MessageBoxButtons.YesNo);
if (o_createDBFileDialogBox == DialogResult.Yes)
{
SQLiteConnection.CreateFile(v_dbLocation);
using (SQLiteConnection o_dbConnection = new SQLiteConnection(#"DataSource=" + v_dbLocation + ";Version=3;"))
{
o_dbConnection.Open();
}
}
else
return;
}
}
I don't really understand whats going on here. Although point to be noted I actually was working towards to use Nunit Form dll to work with Forms (DialogBox) as the method to be tested had a DialogBox to work with.
In the test project there is another class and the tests written inside those class works fine for the Same target 'Class Library' based project to validate a different function.
Hopefully someone will be able to explain whats going on here.
So I have two dlls, Algorithms.dll and Data_Structures.dll (I made these from projects I found on GitHub). Using the browse feature I have managed to add both of the DLL files as references to my Visual Studio 2017 console project. The problem is I can't do anything else with them. Whenever I try to reference something within either file, it simply cannot be found. The only thing that is recognized is the namespace, but nothing inside of that.
What do I need to do to get VS to find the classes these DLLs contain so I can use them? I am aware I need to use Algorithms.Sorting for the example but I can't call anything so I used this as an example.
P.S. If you need more info, please ask. I'm not sure what's relevant to this issue.
EDIT: Ok, it was misleading to have that kind of example. Corrected but please read the question.
EDIT: I tried this on Monodevelop and get the same issue. Maybe it's not the IDE that's the problem?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Algorithms.Sorting; // Error, Sorting cannot be found, and neither can the file container Sorting
using Data_Structures; //Perfectly ok, can find the namespace
namespace CS_HW2_Testing_App
{
class Program
{
static void Main(string[] args)
{
// I'd like to call MergeSort and so forth here. What am I missing?!
}
}
}
Here's the top piece of the file containing MergeSort if it helps
using System;
using System.Collections.Generic;
using Algorithms.Common;
namespace Algorithms.Sorting
{
public static class MergeSorter
{
//
// Public merge-sort API
public static List<T> MergeSort<T>(this List<T> collection, Comparer<T> comparer = null)
{
comparer = comparer ?? Comparer<T>.Default;
return InternalMergeSort(collection, 0, collection.Count - 1, comparer);
}
...
In the first code block, you're importing the wrong namespace: using Algorithms.MergeSort should be using Algorithms.Sorting. Then you can use MergeSorter.MergeSort<T>(...) in your code!
You need to reference the namespace not the class.
using Algorithms.Sorting; //instead of using Algorithms.MergeSort;
Plus make sure the classes are public
I was trying to write an analyser to get information about some methods using the roslyn syntax tree. The problem is: The analyser that I am writing, needs to be in the same solution as the solution that I want to analyse.
So, this is my code:
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
public static class Main
{
public static Solution solution { get; set; } = null;
public static string GetMethodInfo(string methodToFind)
{
Task<Solution> GetSolutionTask = null;
string namespaceToFind, classToFind, methodToFind, invocationToFind;
if (solution == null)
{
var workspace = Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create();
GetSolutionTask = workspace.OpenSolutionAsync(Config.SolutionPath);
}
if (GetSolutionTask != null) solution = GetSolutionTask.Result;
foreach (Project proj in solution.Projects)
{
Compilation compilation = proj.GetCompilationAsync().Result;
foreach (var tree in compilation.SyntaxTrees)
{
findMethodAndProcessIt()...
}
}
return String.Empty;
}
}
The problem I get is that no compilation has any syntax tree. I tried this same code by opening other solutions and it works. So clearly the problem here is to be trying to open the solution that the visual studio is using.
I have already tried to run this code with visual studio closed, only running the .exe , but the problem persists.
Do you have any idea on how to solve this?
You are using MSBuildWorkspace to open a solution. Typically, when use of MSBuildWorkspace leads to projects not being loaded correctly, no source files, etc, there has been a failure during msbuild processing. This usually happens when your application does not have the same binding redirects in its app.config file that msbuild uses (in msbuild.exe.config), which causes some custom tasks/extensions to fail to load due to versioning mismatch.
You'll want to copy the <assemblyBinding> section into your app.config.