Visual Studio 2022 not running XUnit tests - c#

I've created a EntityFramework ASP.NET solution and i'm trying to create a XUnit test project to test my differents classes i've created.
I've created a TestClass for my Activity Class :
using LADS_Model;
using LADS_WebUI.Controllers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using Xunit;
using Assert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert;
namespace LADS_XUnit
{
public class UnitTest_Activity
{
[TestClass]
public class ActivityController
{
private List<Activity> GetTestActivities()
{
var testActivities = new List<Activity>();
testActivities.Add(new Activity { Id = 1, Name = "Chaussure" });
testActivities.Add(new Activity { Id = 2, Name = "Crevettes" });
testActivities.Add(new Activity { Id = 3, Name = "Sandwich" });
return testActivities;
}
[TestMethod]
public void GetAllActivities_ShouldReturnAllActivities()
{
var testActivities = GetTestActivities();
var controller = new ActivityController();
var result = controller.GetTestActivities();
Assert.Equals(testActivities.Count, result.Count);
}
}
}
}
The problem is that when I launch my testClass, I do have the Test showing up in the test Explorer but VS tells me that the test did not execute and I have no idea why because it's not showing any errors or any messages to explain why it didnt execute
Output of Tests :

You're using the wrong method attributes for xUnit, so the xUnit Runner won't discover your tests:
You're using [TestClass] and [TestMethod], but xUnit uses [Fact] (and [Theory], and others) only on methods, and doesn't use any attributes on test class` types.
xUnit's website has a table that matches and compares NUnit's, xUnit's, and MSTest's attributes.
So remove all [TestClass] attributes and change all [TestMethod] attributes to [Fact].
I see you have this:
using Assert = Microsoft.VisualStudio.TestTools.UnitTesting.Assert;
...so I assume you're porting existing MSTest code to xUnit, in which case rather than changing the attributes in your code-base, you could alias MSTest's attributes to xUnit:
using TestClassAttribute = SomeDummyAttribute;
using TestMethodAttribute = Xunit.FactAttribute;
internal sealed class SomeDummyAttribute : Attribute {}
If you're using C# 10.0 or later you can use global using which will be shared by all source-files in the same project.
Also, consider using Shouldly or Fluent Assertions instead of the Assert/Asserts classes.

Related

Visual Studio 2017 not discovering NUnit tests when tests class inherits from a class that implements NHibernate

I'm having this issue that can't resolve, I'm upgrading from NUnit 2.6.4 to 3.9.0, my test project have multiple test class, and when I change NUnit version, some of my tests weren't discovered by test explorer, after some research, all tests missing inherits or somehow implement NHibernate and Spring NUnit testing nuget package. When I remove inheritance, tests are discover. No solution works for this.
Nuget packages version:
Spring.Testing.NUnit
2.0.1 NUnit 3.9.0
NHibernate 3.3.3.4
NUnitTestAdapter 3.9
This is my NHibernate class:
using System;
using NHibernate;
using Spring.Data.NHibernate.Generic;
using Spring.Data.NHibernate.Support;
using Spring.Testing.NUnit;
namespace Testproject{
public class NHibernateTestClass : AbstractTransactionalSpringContextTests
{
//Some methods here
}
}
This is my test class:
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
namespace Testproject{
public class TestClass: NhibernateTestClass{
//Some test methods here
}
}
I have tried referencing NUnit framework in my NHibernateTestClass but, with no result.
Edit:
Forgot to add that my Hibernate test class was inheriting from that spring test class.
Just install NUnit3TestAdapter via nuget.
And add NUnit attributes([TestFixture],[Test]) before class and method declaring.
Well i have simmilar problem but with visual studio 2015 (community)
I have 2 test classes one is:
namespace WarehouseTemplate.Tests
{
[TestFixture]
public class Test1
{
[SetUp]
public void Init()
{
}
[Test()]
public void Can_generate_schema()
{
var cfg = new Configuration();
cfg.Configure();
new SchemaExport(cfg).Execute(true, true, false);
}
}
}
With can be found in test explorer, and then i have this one
namespace WarehouseTemplate.Tests
{
[TestFixture]
public class TestDao : AbstractDaoIntegrationTests
{
private IProductDao productDao;
private ISessionFactory sessionFactory;
// These properties will be injected based on type
public IProductDao ProductDao
{
set { productDao = value; }
}
public ISessionFactory SessionFactory
{
set { sessionFactory = value; }
}
[SetUp]
public void Init()
{
}
[Test()]
public void CustomerDaoTests()
{//logic here
}
}
}
where AbstractDaoIntegrationTests looks
namespace WarehouseTemplate.Tests
{
[TestFixture]
public class AbstractDaoIntegrationTests : AbstractTransactionalDbProviderSpringContextTests
{
protected override string[] ConfigLocations
{
get
{
return new string[]
{
"referenceString"
};
}
}
}
}
But i cant find this test only first one:
NUnit Adapter 3.9.0.0: Test execution started
Running all tests in E:\Zabava\C# programy\WarehouseTemplate\WarehouseTemplate\bin\Debug\WarehouseTemplate.exe
NUnit3TestExecutor converted 1 of 1 NUnit test cases
NUnit Adapter 3.9.0.0: Test execution complete
So far any tip for possible problem is that spring NET has different NUNIT version which needs scpeficy reference or NUnit Adapter
I found Answer and solution
I just instale NUnit 2.6.3 )i manually choose older one, and propriet Adapter version now i can see my tests

Unity, Moq, and NUnit - Controller Constructor with Parameters Not Recognized in Tests

I am very new to unit testing, so I apologize if this is not a very good question.
I have a main web project, and an accompanying NUnit tests library. I am using Unity to inject interfaces into my controller within the main project. For example:
public class EquipmentController : Controller
{
private readonly ILocationRepository locationContext = null;
private readonly IRepository<EquipmentCategory> categoryContext = null;
private readonly IEquipmentRepository equipmentContext = null;
private readonly IRecordRepository recordContext = null;
public EquipmentController(ILocationRepository locationRepo, IRepository<EquipmentCategory> categoryRepo, IEquipmentRepository equipmentRepo, IRecordRepository recordRepo)
{
this.locationContext = locationRepo;
this.categoryContext = categoryRepo;
this.equipmentContext = equipmentRepo;
this.recordContext = recordRepo;
}
The web application itself actually works as expected. However, I am encountering issues while trying to write test cases. For example, in test library, I have the following:
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Unity.Mvc;
using Microsoft.Practices.Unity.ObjectBuilder;
using Microsoft.Practices.Unity.StaticFactory;
using Moq;
using ITEquipmentDatabase;
using ITEquipmentDatabase.Models;
using ITEquipmentDatabase.Controllers;
namespace ITEquipmentDatabase.Tests
{
[TestFixture]
public class EquipmentController
{
[Test]
public void TestMethod()
{
var equipRepo = new Mock<IEquipmentRepository>();
var categoryRepo = new Mock<IRepository<EquipmentCategory>>();
var locationRepo = new Mock<ILocationRepository>();
var recordRepo = new Mock<IRecordRepository>();
EquipmentController controller = new EquipmentController(locationRepo.Object, categoryRepo.Object, equipRepo.Object, recordRepo.Object);
}
}
}
However, I am receiving the following error:
Error 1 'ITEquipmentDatabase.Tests.EquipmentController' does not contain a constructor that takes 4 arguments C:\Users\Khandokar\Documents\Visual Studio 2013\Projects\IT Equipment Log\ITEquipmentDatabase.Tests\EquipmentController.cs 27 46 ITEquipmentDatabase.Tests
I have Unity referenced in my tests project and even added Bootstrapper.cs (not sure if it was necessary, but I was trying to resolve the above issue). I am quite sure I am doing something very wrong, but I am just starting to venture into unit testing and am having a bit of a difficult time.
Thanks for any advice.
Your test class is named EquipmentController and so is your class under test.
Rename your test class to EquipmentControllerTests or some such.
(The error message was the clue; note that it refers to Tests.EquipmentController).

How to define a Controller context when testing an ActionResult

I have an ActionResult which works consistently in an MVC 5 project with EntityFramework and Epplus. Clicking an Action link on the View triggers this ActionResult, which sends the selected model to a fresh Excel document.
I am learning to do unit testing my MVC code in Visual Studio 2013 (using the Nuget Xunit package) and figured I'd start small, by doing the equivalent of a hello world test on the ActionResult by asserting that the ActionResult is not null.
The test failed with this response: "System.InvalidOperationException : No connection string named 'StudentContext' could be found in the application config file."
I understand what the error message means, but my question is how I properly define the Controller context in a Testing project. Am I missing something simple and obvious, like defining a context variable, or am I going about this completely the wrong way?
This is the block of code I am using to test my ActionResult.
using StudentProject.Controllers;
using System.Web.Mvc;
using Xunit;
namespace StudentProject.Tests.Controllers
{
public class StudentRosterControllerTest
{
[Fact]
public void ExportToExcel_IsNotNull()
{
// Arrange
StudentRostersController controller = new StudentRostersController();
ActionResult ExcelExport;
// Act
ExcelExport = controller.ExportToExcel();
// Assert
Assert.NotNull(ExcelExport);
}
}
}
This is the code I am testing. It is is an auto-scaffolded controller, with the auto-generated crud methods hidden and the single method to be tested shown.
using OfficeOpenXml;
using StudentProject.Models;
using System.Collections;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web.Mvc;
namespace StudentProject.Controllers
{
public class StudentRostersController : Controller
{
private StudentContext db = new StudentContext();
// Auto-scaffolded CRUD methods not shown
// This ActionResult exports the StudentRoster model
// to a fresh Excel file.
public ActionResult ExportToExcel()
{
IEnumerable<StudentRoster> query = db.StudentRosters.AsEnumerable();
using (var excelFile = new ExcelPackage())
{
ExcelWorksheet worksheet =
excelFile.Workbook.Worksheets.Add("Sheet1");
worksheet.Cells["A1"].LoadFromCollection(Collection: query,
PrintHeaders: true);
// Results in file downloaded to user's default
// "My Downloads" folder.
return File(excelFile.GetAsByteArray(),
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"Export.xlsx");
}
}
}
}
System.InvalidOperationException : No connection string named
'StudentContext' could be found in the application config file."
make sure the app.config file for the Test project has the proper connection string settings for your EF.
Test project app.config
<connectionStrings>
<add name="StudentContext" connectionString="..." providerName="System.Data.EntityClient" />
</connectionStrings>
how I properly define the Controller context in a Testing project
Your test should try to replicate the run time environment. Provided the minimum needed to test the SUT.
namespace StudentProject.Tests.Controllers
{
public class StudentRosterControllerTest
{
[Fact]
public void ExportToExcel_IsNotNull()
{
// Arrange
StudentRostersController controller = new StudentRostersController();
controller.ControllerContext = new ControllerContext() {
Controller = controller,
//...other properties needed for test
};
// Act
var actionResult = controller.ExportToExcel();
// Assert
Assert.NotNull(actionResult);
}
}
}
Given that you are connecting to your actual database then this would be considered more of an integration test.
I would suggest abstracting your data access so that you can mock it in unit tests.

Tests not appearing in Visual Studio test explorer

I'm having issues setting up my tests. I have tried using a console c# file for my selenium tests which runs the test however it doesn't appear in the test explorer. When I create a unit test c# project it doesn't run or show up in the test explorer. What have done wrong?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace SeleniumTests1
{
[TestClass]
class SeleniumTest
{
[TestMethod]
static void Main(string[] args)
{
IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://www.bing.com/");
driver.Manage().Window.Maximize();
IWebElement searchInput = driver.FindElement(By.Id("sb_form_q"));
searchInput.SendKeys("Hello World");
searchInput.SendKeys(Keys.Enter);
searchInput = driver.FindElement(By.Id("sb_form_q"));
string actualvalue = searchInput.GetAttribute("value");
Assert.AreEqual(actualvalue, "Hello World");
driver.Close();
}
}
}
This may work. I think your TestMethod needs to be public and non-static in order for it to appear in Test Explorer.
namespace SeleniumTests1
{
[TestClass]
public class SeleniumTest
{
[TestMethod]
public void Main()
{
You're making a Main method the test method?
Make a separate test project, then reference the project you're testing and move your code to that instead e.g.
namespace Tests
{
[TestClass]
public class MyProjTests
{
[TestMethod]
public void Test{
//your code
}
}
}
Although this one's a rather obvious and straightforward answer, but, looking at the code posted originally by Peter and my own silly mistake I realized that one more place where we can go wrong is by not making our outer test class public without which they would default to internal and the contained tests would not show up in the test explorer. So, the final form of a unit test code would begin with something like this
namespace SeleniumTests1
{
[TestClass]
public class SeleniumTest
{
[TestMethod]
public void testMethod(string[] args)
{
I think I may have managed to resolve the issue in this instance by importing the 4 dlls from the net40 file from the selenium website.

How to distinguish between testsuite and testcase on the report

Using Selenium C# web driver with NUnit for automation. I am generating Allure report using command line and my report gets fantastically created but I need help on the following issue:
I have the following structure using Page object model (2 Test and 1 Page). Now when I see the report it shows at the top Test run (2 testsuites, 2 testcases) and each testcase is a testsuite. I want it to say 1 testsuites, 2 testcases. How do I do that?
namespace ApplicationName.TestCases
{
[TestFixture]
class VerifyCreateOrder
{
IWebDriver driver;
[SetUp]
public void Initialize()
{
driver = new FirefoxDriver();
}
[TestCase]
public void doCreateOrder()
{
LoginPage loginPage = new LoginPage();
//some Assertion
}
}
}
namespace ApplicationName.TestCases
{
[TestFixture]
class SearchOrder
{
IWebDriver driver;
[SetUp]
public void Initialize()
{
driver = new FirefoxDriver();
}
[TestCase]
public void doSearchOrder()
{
LoginPage loginPage = new LoginPage();
//some Assertion
}
}
}
The below is my LoginPage Page object:
namespace ApplicationName.Pages
{
class LoginPage
{
public void doLogin(IWebDriver driver, String username, String password)
{
driver.Navigate().GoToUrl("http://www.myxyzsite.com");
driver.FindElement(By.Id("xyz")).SendKeys(username);
driver.FindElement(By.Id("xyz")).SendKeys(password);
driver.FindElement(By.Id("xyz")).Click();
}
}
}
I read about the NUnit suite attribute at http://www.nunit.org/index.php?p=suite&r=2.5.5 and created a c# class with enumerator as described but how do i call it/wire it? What changes do I need to make for my test classes?
namespace NUnit.Tests
{
public class MyTestSuite
{
[Suite]
public static IEnumerable Suite
{
get
{
ArrayList suite = new ArrayList();
suite.Add(new VerifyCreateOrder());
suite.Add(new SearchOrder());
return suite;
}
}
}
}
I want it to say 1 testsuites, 2 testcases. How do I do that?
Without adding a Suite or similar, you could put both Test cases into the same TestFixture, since that's what the testsuite output is built from. You may be able to do that using a partial class, or you can simply conflate the two classes. However, your Suite solution is a better choice.
What changes do I need to make for my test classes?
Call NUnit with the option /fixture:NUnit.Tests.MyTestSuite.
Note that all of this has changed with NUnit 3 and the Suite attribute is gone. I can't see any way to do what you want in NUnit 3 short of reorganizing your test cases.
If it's very important to merge tests into suites, you can use XSLT. The NUnit test result schema is quite straightforward and easy to manipulate using XSLT.

Categories

Resources