C# selenium - SetUp - test name - c#

Trying to get the name of the test in SetUp, I get: "AdhocTestMethod"...
[SetUp]
public void SetUpFunc()
{
var asd = TestContext.CurrentContext.Test.Name;
}
[Test(Description = "testingSetup")]
public void TestName123()
{
Assert.IsTrue(false);
}
I'm using NUnit 2.6.3

A new answer has just been posted regarding "AdhocTestMethod" search for customattribute adhoctestmethod

I think you've got some problem with your setup. It works fine for me.
using NUnit.Framework;
using System;
namespace UnitTestProject1
{
public class Tests
{
[SetUp]
public void SetUpFunc()
{
var asd = TestContext.CurrentContext.Test.Name;
Console.WriteLine($"Setup: {asd}");
}
[Test(Description = "testingSetup")]
public void TestName123()
{
var asd = TestContext.CurrentContext.Test.Name;
Console.WriteLine($"Test: {asd}");
Assert.IsTrue(false);
}
}
}
It prints
Setup: TestName123
Test: TestName123
I have NUnit 2.6.3 and NUnitTestAdapter 2.1.1 installed.

Related

Does AutoFixture support `DateOnly` for .NET6?

I'm getting exception on constructing DateOnly variables/fields with AutoFixture.
(constructing of TimeOnly works fine)
AutoFixture.ObjectCreationExceptionWithPath : AutoFixture was unable to create an instance from System.DateOnly because creation unexpectedly failed with exception. Please refer to the inner exception to investigate the root cause of the failure.
AutoFixture, AutoFixture.NUnit3 nugets version: 4.17.0
using AutoFixture;
using AutoFixture.NUnit3;
using NUnit.Framework;
namespace UnitTests
{
[TestFixture]
public class AutoFixtureCreateTests
{
private readonly Fixture fixture = new();
[SetUp]
public void Setup()
{
var date = fixture.Create<DateOnly>(); //fails
var time = fixture.Create<TimeOnly>(); //works fine
}
[Test, AutoData]
public void CreateString(string str) { } //works fine
[Test, AutoData]
public void CreateDateOnly(DateOnly date) { } //fails
[Test, AutoData]
public void CreateTimeOnly(TimeOnly time) { } //works fine
}
}
The answer: at the moment does not.
There is a pull request: https://github.com/AutoFixture/AutoFixture/pull/1305
(however it's in open state almost for a year, without any milestones)
But there is a workaround.
My temporary solution is to create AutoFixture customization (CustomFixture.cs) file and include it to the project:
using AutoFixture;
using AutoFixture.NUnit3;
namespace UnitTests
{
public class CustomFixture
{
public static Fixture Create()
{
var fixture = new Fixture();
fixture.Customize<DateOnly>(composer => composer.FromFactory<DateTime>(DateOnly.FromDateTime));
return fixture;
}
}
public class CustomAutoDataAttribute : AutoDataAttribute
{
public CustomAutoDataAttribute()
: base(()=>CustomFixture.Create())
{}
}
}
After it include customization in the test code:
using AutoFixture;
using AutoFixture.NUnit3;
using NUnit.Framework;
namespace UnitTests
{
[TestFixture]
public class AutoFixtureCreateTests
{
private readonly Fixture fixture =
CustomFixture.Create(); //custom factory
[SetUp]
public void Setup()
{
var date = fixture.Create<DateOnly>(); //now works
var time = fixture.Create<TimeOnly>();
}
[Test, AutoData]
public void CreateString(string str) { }
[Test, CustomAutoData] //custom attribute
public void CreateDateOnly(DateOnly date) { } //now works
[Test, AutoData]
public void CreateTimeOnly(TimeOnly time) { }
}
}

Servicestack Test: Method not found: 'Int32 ServiceStack.DataAnnotations.CustomFieldAttribute.get_Order()

Trying to build integration test with connection to db in ServiceStack.
My ServiceStack app is working fine, but when I run simple test I got this error message in line:22
System.MissingMethodException: 'Method not found: 'Int32 ServiceStack.DataAnnotations.CustomFieldAttribute.get_Order()'.'
There is a lite cod:
using ServiceStack;
using ServiceStack.OrmLite;
using ServiceStack.Data;
using NUnit.Framework;
using ServiceStack.DataAnnotations;
using System.Collections.Generic;
namespace oth.Tests.IntegrationTests
{
public class AppHost2 : AppSelfHostBase
{
public AppHost2() : base("Customer REST Example", typeof(CustomerService).Assembly) { }
public override void Configure(Container container)
{
var connectionString = "Host=localhost;Port=5432;Database=test_1234;Username=postgres;Password=local";
container.Register<IDbConnectionFactory>(c =>
new OrmLiteConnectionFactory(connectionString, PostgreSqlDialect.Provider));
using var db = container.Resolve<IDbConnectionFactory>().Open();
db.CreateTableIfNotExists<Customer>();
}
}
public class Customer
{
[AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
}
[Route("/customers", "GET")]
public class GetCustomers : IReturn<GetCustomersResponse> { }
public class GetCustomersResponse
{
public List<Customer> Results { get; set; }
}
public class CustomerService : Service
{
public object Get(GetCustomers request)
{
return new GetCustomersResponse { Results = Db.Select<Customer>() };
}
}
public class CustomerRestExample
{
const string BaseUri = "http://localhost:2000/";
ServiceStackHost appHost;
public CustomerRestExample()
{
//Start your AppHost on TestFixture SetUp
appHost = new AppHost2()
.Init()
.Start(BaseUri);
}
[OneTimeTearDown]
public void OneTimeTearDown() => appHost.Dispose();
/* Write your Integration Tests against the self-host instance */
[Test]
public void Run_Customer_REST_Example()
{
var client = new JsonServiceClient(BaseUri);
var all = client.Get(new GetCustomers());
Assert.That(all.Results.Count, Is.EqualTo(0));
}
}
}
Anytime you see a missing type or missing method exceptions when using the MyGet pre-release packages it means you have a dirty installation (i.e. using pre-release packages from different build times).
In which case you'd need to Clear your Nuget packages cache and download the latest packages again, which ensures all your packages are from the latest same build:
$ dotnet nuget locals all -clear

How to output result when invoked by xUnit?

For example, there is a class to be tested.
public class ToBeTested
{
public static void Method1()
{
Debug.WriteLine("....for debugging....");
}
}
And It's invoked by xUnit test method
[Fact]
public void Test1()
{
ToBeTested.Method1();
}
However, the line Debug.WriteLine("....for debugging...."); didn't write anything in Visual Studio debug output?
The line Debug.WriteLine("....for debugging...."); will write the output to the Debug Output window of visual studio only when the tests are ran in Debug mode. Instead of "Run Tests" you can use "Debug Tests" and can see the output in window.
But if you are trying to output results while running XUnit tests, then it is better to use ITestOutputHelper in namespace Xunit.Abstractions.
Code sample is available in : https://xunit.github.io/docs/capturing-output.html
using Xunit;
using Xunit.Abstractions;
public class MyTestClass
{
private readonly ITestOutputHelper output;
public MyTestClass(ITestOutputHelper output)
{
this.output = output;
}
[Fact]
public void MyTest()
{
var temp = "my class!";
output.WriteLine("This is output from {0}", temp);
}
}

C# extent reports when running a test the html report file is not being generated

I am trying out ExtentReports in Visual Studio C#. When i run a test case the html report file is not being generated. I am not sure what is wrong in my code.
I think the path to my reports folder is correct.
In Solution Explorer I created a folder called "Reports" and I would like the report file to be created here.
My code snippet is:
using NUnit.Framework;
using RelevantCodes.ExtentReports;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExtentReportsDemo
{
[TestFixture]
public class BasicReport
{
public ExtentReports extent;
public ExtentTest test;
[OneTimeSetUp]
public void StartReport()
{
string pth = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
string actualPath = pth.Substring(0, pth.LastIndexOf("bin"));
string projectPath = new Uri(actualPath).LocalPath; // project path of your solution
string reportPath = projectPath + "Reports\\testreport.html";
// true if you want to append data to the report. Replace existing report with new report. False to create new report each time
extent = new ExtentReports(reportPath, false);
extent.AddSystemInfo("Host Name", "localhost")
.AddSystemInfo("Environment", "QA")
.AddSystemInfo("User Name", "testUser");
extent.LoadConfig(projectPath + "extent-config.xml");
}
[Test]
public void DemoReportPass()
{
test = extent.StartTest("DemoReportPass");
Assert.IsTrue(true);
test.Log(LogStatus.Pass, "Assert Pass as consition is true");
}
[Test]
public void DemoReportFail()
{
test = extent.StartTest("DemoReportPass");
Assert.IsTrue(false);
test.Log(LogStatus.Fail, "Assert Pass as condition is false");
}
[TearDown]
public void GetResult()
{
var status = TestContext.CurrentContext.Result.Outcome.Status;
var stackTrace = "<pre>"+TestContext.CurrentContext.Result.StackTrace+"</pre>";
var errorMessage = TestContext.CurrentContext.Result.Message;
if (status == NUnit.Framework.Interfaces.TestStatus.Failed)
{
test.Log(LogStatus.Fail, stackTrace + errorMessage);
}
extent.EndTest(test);
}
[OneTimeTearDown]
public void EndReport()
{
extent.Flush();
extent.Close();
}
}
}
There are no errors when I build the solution. The test runs fine but the testreport.html is not being generated.
I have used NuGet to install extentReports and installed Nunit.
Thanks, Riaz
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RelevantCodes.ExtentReports;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
namespace testingExtentReports
{
[TestClass]
public class UnitTest1
{
public ExtentReports extent;
public ExtentTest test;
IWebDriver driver;
[SetUp]
public void StartReport()
{
string reportPath = #"D:\\TestReport.html";
extent = new ExtentReports(reportPath, true);
extent.AddSystemInfo("Host Name", "Your Host Name")
.AddSystemInfo("Environment", "YourQAEnvironment")
.AddSystemInfo("Username", "Your User Name");
string xmlPath = #"D:\\ExtentConfig.xml";
extent.LoadConfig(xmlPath);
}
[Test]
public void OpenTest1()
{
test = extent.StartTest("OpenTest1", "test Started");
test.Log(LogStatus.Pass, "Website is open properly");
test.Log(LogStatus.Pass, "Successfully Login into agency Portal");
test.Log(LogStatus.Info, "Click on UI button link");
test.Log(LogStatus.Fail, "Error Occurred while creating document");
test.Log(LogStatus.Pass, "Task Released Succssfully");
test.Log(LogStatus.Warning, "Workflow saved with warning");
test.Log(LogStatus.Error, "Error occurred while releasing task.");
test.Log(LogStatus.Unknown, "Dont know what is happning.");
test.Log(LogStatus.Fatal, "Unhandled exception occured.");
extent.EndTest(test);
extent.Flush();
extent.Close();
}
}
}
You just need to Put the ExtentConfig.xml file to your specific folder, TestReport.html automatically generated on a specific path.Copy xml from given link extentReports.xml

why isn't TestInitialize getting called automatically?

I'm using Microsoft.VisualStudio.TestTools.UnitTesting; but the method I marked as [TestInitialize] isn't getting called before the test. I've never used this particular testing framework before but in every other framework there is always a way of registering a Setup and TearDown method that will auto run before and after every single test. Is this not the case with the visual studio testing tools unit testing framework?
[TestClass]
public class RepoTest
{
private const string TestConnectionString = #"Server=localhost\SQL2014EXPRESS64; Database=RepoTest; Trusted_Connection=True;";
private const string MasterConnectionString = #"Server=localhost\SQL2014EXPRESS64; Database=master; Trusted_Connection=True;";
[TestInitialize]
private void Initialize()
{
using(var connection = new SqlConnection(MasterConnectionString))
using(var command = new SqlCommand(Resources.Initialize, connection))
{
command.ExecuteNonQuery();
}
}
[TestCleanup]
private void Cleanup()
{
using (var connection = new SqlConnection(MasterConnectionString))
using (var command = new SqlCommand(Resources.Cleanup, connection))
{
command.ExecuteNonQuery();
}
}
[TestMethod]
public void CreateARepo()
{
var repo = new Repo(TestConnectionString);
}
}
Make Initialize and Cleanup public. You can also check, that at msdn all examples have public accessor.
In order to reproduce, make such test class:
[TestClass]
public class Tests
{
[TestInitialize]
public void Initialize()
{
Console.WriteLine("initialize");
}
[TestCleanup]
public void Cleanup()
{
Console.WriteLine("cleanup");
}
[TestMethod]
public void Test()
{
Console.WriteLine("test body");
}
}
That test will produce the following results:
Making Initialize and Cleanup private, you'll see only test body being printed to the console:
Used Microsoft.VisualStudio.QualityTools.UnitTestFramework assembly as unit testing framework version 10.1.0.0 and ReSharper 8.2 as a test runner.

Categories