C# Unit Test is not recognizing other classes - c#

1st - Help the community, if you give a negative mark, at least explain why, so I will not repeat it!
I am a Begginer, and I'm trying to test a simple class. But my UnitTest do not recognize the other namespace, even though I have added the Reference.
See the reference above
I can not use the "using" directive:
enter image description here
It's a .net Core 3.1 project. VS 2019 community
It probably is something really silly, but I'm stuck in it,and have tried everything I know.
The class I want to import
namespace DI.BLL
{
public class ContainerBuilder
{
private readonly IList<Type> _registration = new List<Type>();
public void Register<T>()
{
this._registration.Add(typeof(T));
}
public Container Build() => new Container(_registration);
}
}
The test code:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Xunit;
using DI.BLL;
namespace DI.Test
{
[TestClass]
public class Container
{
[Fact]
public void Should_Be_Able_To_Resolve_A_Class_Instance()
{
var builder = new ContainerBuilder();
builder.Register<Cars>();
var sut = builder.Build();
Assert.IsNotNull(instance);
}
}
}

As Geoff James said, I was using different versios of the framework
The project class was using the Core framework, while the Test project was using the .NET 4.7.
Got them into the same version and it's working perfectly

Related

I added a reference to the main project, but the testing project still doesn't see the classes of main

My solution has a project that contains all the program logic.
I created a unit test project, added a reference to the main project, but still can't use classes from it to create tests.
My code:
namespace Program
{
public class Class
{
public Class()
{
///
}
public int foo()
{
///
}
}
}
My tests code:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Program; // cs0246
namespace ProgramTests
{
[TestClass]
public class ClassTests
{
[TestMethod]
public void foo_()
{
// Arrange
Class testClass; // this code also have cs0246 error
// Act
// Assert
}
}
}
In this code, using Program; underlined in red with cs0246 error. But namespace ProgramTests have the reference to Program (there is a checkmark in the reference manager). How can i fix it?
Image of Solution Explorer
Please, check the framework version you are using. Maybe Tests library has framework which is no compatible with ClassLib Framework

OneTimeSetUp: No suitable constructor was found when using nunit and autofac

I'm trying to get nunit and autofac working together for a Selenium test framework.
I understand why I'm getting the OneTimeSetUp: No suitable constructor was found error (because nunit cannot start UnitTest1 if it has a ctor which isn't empty), but I can't figure out how I can work around this.
It seems like a chicken and egg problem; nunit requires IHomePage for the test to run, but the container isn't created because SetUp or OneTimeSetUp aren't called until the test has started running.
[TestFixture]
public class UnitTest1
{
IHomePage _homePage;
private static IContainer Container { get; set; }
[SetUp]
public void SetUp()
{
var builder = new ContainerBuilder();
builder.RegisterType<HomePage>().As<IHomePage>();
builder.RegisterType<LoginPage>().As<ILoginPage>();
Container = builder.Build();
using (var scope = Container.BeginLifetimeScope())
{
var writer = scope.Resolve<ITestRunner>();
writer.RunTest();
}
}
public UnitTest1(IHomePage homePage)
{
_homePage = homePage;
}
[Test]
public void TestMethod11()
{
// do something testing with _homePage
_homePage.ClickLogin();
}
}
public class HomePage : IHomePage
{
ILoginPage _loginPage;
public HomePage(ILoginPage loginPage)
{
_loginPage = loginPage;
}
public ILoginPage ClickLogin()
{
return _loginPage;
}
}
This will only be a partial answer, 'cause I know nothing about Autofac.
BUT from the NUnit point of view...
NUnit constructs your classes. To do that it needs either
A default constructor, OR
A non-default constructor for which you have supplied arguments.
You have a non-default constructor, but you are not telling NUnit what args to use with that constructor.
The way you tell NUnit what args to use is to supply them as arguments to the
TestFixtureAttribute or by using a TestFixtureSourceAttribute, which adds a level of indirection. Perhaps somebody else can add how Autofac interacts with NUnit in this situation.

How do I add a DbContext to an MSTest project?

I trying to test some code that uses Entity Framework, but I can't figure out how to reference the EF Context classes from the separate MSTest project. Both projects are in the same solution.
Cannot convert lambda expression to type 'DbContextOptions' because it is not a delegate type
In my Test case:
[TestClass]
public class GreenCardUserTest
{
[TestMethod]
public void TestAddUser()
{
// REFERENCE TO OTHER PROJECT. WORKS FINE
AppUserViewModel a = new AppUserViewModel();
//LIKELY INCORRECT attempt to duplicate code from Startup.cs in other project
using (GreenCardContext _gc = new GreenCardContext(options => options.UseSqlServer(Configuration.GetConnectionString("MyConnection"))))
{
new GCLandingUserModel().AddUser(a,_gc);
}
}
}
Excerpt from main project Startup.cs (which works fine):
services.AddDbContext<GreenCardContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyConnection")));
I would suggest using InMemoryDatabase. In your test class, use [TestInitialize] to setup your dummy database:
[TestClass]
public class GreenCardUserTest
{
private readonly context;
[TestInitialize]
public Setup()
{
DbContextOptions<GreenCardContext> options;
var builder = new DbContextOptionsBuilder<GreenCardContext>();
builder.UseInMemoryDatabase();
var options = builder.Options;
context = new GreenCardContext(options);
}
[TestMethod]
public void TestAddUser()
{
// user context here...
}
}
What you have to do is:
1) Add a reference in your test project to your context's project (if you haven't already)
2) Add references to Entity Framework to your test project
3) Add an appconfig to your test project and set entity framework config on it. Your test will read the configuration from it's own config, not your app's. Very useful as you can, by example, use dblocal and codefirst in tests and sqlserver when on running :)
You have done some of this, I think the point you are missing is the third :)
The code that you have from Startup.cs is using a delegate to tell your application how to build your DbContext at runtime.
However in your test, you need to actually provide an instance of DbContextOptions, not just a delegate. To do this, you can use DbContextOptionsBuilder:
var options = new DbContextOptionsBuilder<GreenCardContext>()
.UseSqlServer(Configuration.GetConnectionString("MyConnection"))
.Options;
using (GreenCardContext _gc = new GreenCardContext(options))
{
new GCLandingUserModel().AddUser(a,_gc);
}
Also, if you do insist on unit testing your DbConext, you may want to look into using InMemoryDatabase so that you don't need an open SQL connection in your tests. See this document for more details.

Unit tests missing output in VS2017

EDIT:
I might have found a possible lead.
Checking my Test Runs it would seem as if I have 0 completed runs (even though all my 15 tests complete). Any clues?
I've got a technical interview coming up where testing will be the main focus. I've got rather limited exposure to testing in Visual Studio and can't seem to figure out why my version (VS2017) won't display the output button when I run tests.
Since my limited exposure I've been following along a few PluralSight courses on the subject and have found a decent one covering both LINQ and VS's own unit testing framework.
This is where it should be on VS2015 (I think?):
And this is how it looks for me:
As you can see I'm missing the output button for some god forsaken reason. I've looked in multiple windows (output's debug and tests), but simply cannot see the output.
My unit test follows the instructor's structure with some small changes (like how I set up my TestContext, which follows the structure of this answer to a similar question..
This is my unit test:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ACM.Library.Test
{
[TestClass]
public class BuilderTest
{
private TestContext _testContextInstance;
public TestContext TestContext
{
get { return _testContextInstance; }
set { _testContextInstance = value; }
}
public Builder listBuilder { get; set; }
[TestInitialize]
public void TestInitialize ()
{
this.listBuilder = new Builder();
}
[TestMethod]
public void TestBuildIntegerSequence()
{
var result = listBuilder.BuildIntegerSequence();
foreach(var item in result)
{
TestContext.WriteLine(item.ToString());
}
Assert.IsNotNull(result);
}
}
}
EDIT:
Here is the function I'm testing...
public IEnumerable<int> BuildIntegerSequence()
{
var integers = Enumerable.Range(0, 10);
return integers;
}

In a Visual Studio package, can I simulate (DTE) GetService(typeof (DTE)) for tests?

In my package I am using (DTE) GetService(typeof (DTE)) to get information about the currently opened solution. Is there a way to simulate this for a test, particularly so that I can build using dte.Solution.SolutionBuild?
Code in main package class:
var solutionModel = new SolutionModel(((DTE) GetService(typeof (DTE))).Solution);
SolutionModel class (stripped back):
public class SolutionModel
{
private readonly Solution _packageSolution;
public SolutionModel(Solution solution)
{
_packageSolution = solution;
}
public SolutionModel() {} // This constructor is used for tests so _packageSolution will be null
public bool Build()
{
if (_packageSolution != null)
{
var buildObject = _packageSolution.SolutionBuild;
buildObject.Build(true);
return buildObject.LastBuildInfo == 0;
}
return ManualCleanAndBuild(); // current messy alternative way of doing the build for tests
}
}
So I want to be able to use the _packageSolution build rather than ManualCleanAndBuild() in my tests.
Assuming that you are referring to integration tests (and not to unit tests) where you need to load your package in a real Visual Studio instance, it depends on the testing framework that you are using. If you are using MSTest with the VSIDE Host Adapter (the integration test project that the package wizard creates if you mark the checkbox in the last page of the wizard) there is a Utils.cs file that uses the static VsIdeTestHostContext class to get the DTE instance or services:
public static class VsIdeTestHostContext
{
[CLSCompliant(false)]
public static DTE Dte { get; }
public static IServiceProvider ServiceProvider { get; set; }
}
If you want to learn the inners of the VS IDE Host Adapter I think that the VS 2008 SDK was the last SDK that provided the source code and the documentation (http://msdn.microsoft.com/en-us/library/bb286982%28v=vs.90%29.aspx)
The way I ended up 'solving' this was to mock EnvDTE.Solution instead (seems like it can only be done in the Package_IntegrationTests project which is created for you - you can't reference EnvDTE in any other project). I couldn't figure out how to use the methods in Utils.cs as suggested by Carlos below to open my existing solutions.

Categories