Visual studio 2017 code analyzer unit test can't load custom attribute from external assembly - visual-studio-2017

Under visual studio 2017, creating an extension using Analyzer with code fix template. For code analyzer unit test code, it can't parse custom attribute in external DLL. It shows ErrorType NameSpace.MyCustomAttribute for attr.AttributeClass
The external DLL is targeting dot.net 4.6. I added the MetaReference through
.AddMetadataReference(projectId, ExternalDllReference);
The ExternalDLLReference is loaded through
MetadataReference.CreateFromFile(typeof(MyAttribute).Assembly.Location)
I also tried to manually load the assembly through fixed location. Same result.
The unit test c# code is pretty simple. For custom attribute defined in the unit test string, it loads correctly. It is just the attribute in the external DLL not loaded correctly.
I tried similar attribute (TestMethod defined in test framework) which has the same result so it doesn't look it is unique to my custom DLL.
var test = #"
using System;
using MyCustom.Attributes;
namespace ConsoleApplication1
{
public class Custom2Attribute : Attribute
{
}
[Custom2]
[DataSynchronizationContract(ClientSynchronizationMode.AllowClientChanges, DatabaseSynchronizationMode.Automatic)]
public class TestClass
{
[DataSynchronizationMember]
[Custom2]
public string PatientID { get; set; }
[DataSynchronizationMember(Client = ClientSynchronizationMode.DenyClientChanges, Database = DatabaseSynchronizationMode.NotSynchronized)]
public string OrderID { get; set; }
}
}";
The "Custom2Attribute" is parsed correctly. But DataSynchronizationContract and DataSynchronizationMember (defined in the external DLL) are parsed as ErrorType for attr.AttributeClass
This is the error I get:
((Microsoft.CodeAnalysis.CSharp.Symbols.NamedTypeSymbol)attr.AttributeClass).DefaultMarshallingCharSet'
threw an exception of type 'System.InvalidOperationException

Related

How to set up ServiceBusTrigger with Dependency Injection with .Net Core 6.0 Isolated

I currently have a ServiceBus Trigger in .Net Core 6.0 Isolated. Trying to figure out how to Use Dependency Injection, to set up the Trigger. Trying to figure out how to do this with .Net Core 6.0 Isolated.
I have a strongly typed model that is Bound to the appsettings.json file in the Program.cs code. That part works and has been verified. However when trying to do this with .Net Core 6 Isolated It give error about missing reference.
Here's my Config model that is bound to the appsettings.json file. I have left out the appsettings.json file for simplification
public class MyConfig
{
public string Topic { get; set; }
public string SubscriptionName { get; set; }
}
Here is the Service bus trigger class
public class ServiceBusTriggerClass
{
private readonly MyConfig _myConfig;
public ServiceBusTriggerClass(IOptions<MyConfig> config)
{
_myConfig= config.Value;
}
[Function("MySBFunction")]
public async Task MySBFunction([ServiceBusTrigger(_myConfig.Topic, _myConfig.SubscriptionName)] object myObject)
{
// Do things with the myObject thing.
}}
As of 1-13-2022 it is not possible to do this Using .Net 6 Isolated function. The function does not have access to the Host at this point.

Can not run Unitests with Xamarin

I want to check my Xamarin project code (Cookbook) with unit tests. I've created a Unitest for Xamarin project from Visual Studio (UITest1). When I try to run it the linker writes the following error:
Error NU1201 Project Cookbook is not compatible with net461 (.NETFramework,Version=v4.6.1) / win-x64. Project Cookbook supports: monoandroid81 (MonoAndroid,Version=v8.1) UITest1
What am i doing wrong? Tried to Google but with no luck.
This is the Uinitests code if it helps:
using System;
using System.IO;
using System.Linq;
using Cookbook;
using NUnit.Framework;
using Xamarin.UITest;
using Xamarin.UITest.Queries;
namespace UITest1
{
[TestFixture(Platform.Android)]
[TestFixture(Platform.iOS)]
public class Tests
{
IApp app;
Platform platform;
private Ingredient ingr;
public Tests(Platform platform)
{
this.platform = platform;
}
[SetUp]
public void BeforeEachTest()
{
//app = AppInitializer.StartApp(platform);
ingr = new Ingredient();
}
[Test]
public void WelcomeTextIsDisplayed()
{
AppResult[] results = app.WaitForElement(c => c.Marked("Welcome to Xamarin.Forms!"));
app.Screenshot("Welcome screen.");
Assert.IsTrue(results.Any());
}
[Test]
public void ParseFromString()
{
Ingredient ingr = new Ingredient();
ingr.TryToParseFromString("Ingredients");
Assert.AreEqual(0, ingr.Amount, "amount problem");
Assert.AreEqual(null, ingr.Item, "item problem");
Assert.AreEqual(null, ingr.Units, "units problem");
Assert.AreEqual("Ingredients", ingr.Unparsed, "unparsed problem");
}
I see that you're mixing up the concept of unit tests and UI tests since you have both in your test project. What you should do is create two separate projects, for example Cookbook.UITests and Cookbook.UnitTests. The reason is that UI Tests are meant to emulate user behavior while being run on an emulator, real device or perhaps a cloud testing service. Unit tests, on the other hand, should test stuff like the business logic of your code application (to put it simply).
What I would suggest you to do is the following:
Create the two separate projects Cookbook.UITests and Cookbook.UnitTests
Follow the great guidance by SushiHangover on how to set up the unit test project.
Follow the official documentation by Microsoft to set up the UITest project.

NUnit Test Adapter: Group by Class broken with named test cases (VS 2012)

Consider the following test fixture:
using System;
using System.Collections.Generic;
using NUnit.Framework;
namespace NUnitDemo
{
[TestFixture]
public class FooTests
{
public IEnumerable<TestCaseData> FooTestCases
{
get
{
yield return new TestCaseData(1).SetName("Once");
yield return new TestCaseData(2).SetName("Twice");
yield return new TestCaseData(3).SetName("Thrice");
yield return new TestCaseData(19140101).SetName("1914.01.02");
}
}
[TestCaseSource("FooTestCases")]
public void FooTest(int v)
{
}
}
}
With the NUnit Test Adapter (2.6) on Visual Studio 2012, Test Explorer grouped by class displays the following:
A little experimentation shows that this odd behaviour is invoked when the test name contains more than one dot. In this case, the class name is incorrectly replaced with the second-last section of the test-name, split on dot.
Is there any way to work around this issue?
I have 582 test cases in my project - most of them are named, parametrised tests.
To be honest, what I really want is the ability to organise my tests by fully-qualified class and method name, then by test-case name. The NUnit GUI does this in a rather clunky way but I am looking for integration into Visual Studio.

Visual Studio 2012 auto create unit test - WP8 application

So, I was also surprised that the "create unit test" is not available from the context menu when right clicking over a method, as opposed to Visual Studio 2010.
The work arounds suggested was to create the unit tests in VS2010 and then import it back to VS2012.
Then i found this post http://dl.my/2013/enable-create-unit-tests-on-visual-studio-2012/
and that indeed worked!
But now, after i click the "create unit test" over a method, the generated class only contains a TestContext property, without the test methods that was chosed in the wizard previously.
This is the generated class:
/// <summary>
///This is a test class for XXXTest and is intended
///to contain all XXXTest Unit Tests
///</summary>
[TestClass()]
public class XXXTest
{
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
//You can use the following additional attributes as you write your tests:
//
//Use ClassInitialize to run code before running the first test in the class
//[ClassInitialize()]
//public static void MyClassInitialize(TestContext testContext)
//{
//}
//
//Use ClassCleanup to run code after all tests in a class have run
//[ClassCleanup()]
//public static void MyClassCleanup()
//{
//}
//
//Use TestInitialize to run code before running each test
//[TestInitialize()]
//public void MyTestInitialize()
//{
//}
//
//Use TestCleanup to run code after each test has run
//[TestCleanup()]
//public void MyTestCleanup()
//{
//}
//
#endregion
}
I have searched the web with no results..
Does anybody know what's the issue here?
Apparently, it is not possible to use "Generate Unit Tests..." wizard for Windows Phone projects.
As you try to use the wizard, the following error will be prompted:
While trying to generate your tests, the following errors occurred:
You can only add WinMD references to a project targeting Windows 8.0 or higher. To learn how to retarget your project to a different version of Windows, please see the 'Core subgroup' section underneath the 'Windows tab' section in the 'How to: add or remove references by using the Reference Manager' help page: http://msdn.microsoft.com/library/hh708954(v=vs.110).aspx.
The best you can do now is by creating it manually.

Run unit tests on dynamically created DLL

I am thinking on how to implement this , and seems like my knowledge is too poor to understand the implementation.
I have a code that compiles source code to DLL.
Then I need somehow to run Unit test on this Dll , and check 3-4 methods inside.
I am trying to run unit tests this way.
CompilerResults compileResults = codeProvider.CompileAssemblyFromSource(compilerParameters, new string[] { sourceCode });
Assembly myAssembly = compileResults.CompiledAssembly;
TestPackage testPackage = new TestPackage(#"TestingProject.dll");
testPackage.Assemblies.Add(myAssembly);
RemoteTestRunner remoteTestRunner = new RemoteTestRunner();
remoteTestRunner.Load(testPackage);
TestResult testResult = remoteTestRunner.Run(new NullListener(),TestFilter.Empty,false,LoggingThreshold.All);
And this for example Test
[Test]
public void AddTest(IDynamicScript s)
{
Assert.AreEqual(10, s.Add(5,5));
Assert.AreNotEqual(10,s.Add(4,5));
}
Since Assembly is compiled dynamically , I can't reference it to unit test Project , and it will not compile , any suggestions please on how to implement this please
Your code works just fine after a few modifications. These are the required changes:
The test code needs to be wrapped in a class with appropriate namespace imports, you can't compile standalone methods with the C# compiler
You need to inform the compiler about the assembly references of the code you're compiling, in this case I supplied the path to the nunit.framework.dll assembly, which I got from the location of the copy loaded in the main AppDomain, but you can also reference it from the file system without loading it. Usually you will also need to supply the paths of the assemblies containing the code you're testing
The constructor of the TestPackage class takes an absolute path in its constructor, in this case I supplied the location of the generated assembly
This is the code with the corrections:
var sourceCode = #"
using NUnit.Framework;
public class Fixture
{
[Test]
public void AddTest()
{
Assert.AreEqual(10, 5+5);
}
}";
var provider = new CSharpCodeProvider();
CompilerResults compileResults = provider.CompileAssemblyFromSource(
new CompilerParameters(new[]{ typeof(TestAttribute).Assembly.Location }),
new[]{ sourceCode });
var assembly = compileResults.CompiledAssembly;
var package = new TestPackage(assembly.Location);
var runner = new RemoteTestRunner();
runner.Load(package);
var result = runner.Run(new NullListener(),
TestFilter.Empty,
false,
LoggingThreshold.All);