I am generating an extent report in specflow, I have written the code and my test execute successfully and report generating but it displays only the feature name no steps name displayed in the report.
Please suggest me what mistake I am doing in the code.
I am attaching a screenshot of my generated report, When I go to report dashboard it displays the number of steps there.
using AventStack.ExtentReports;
using AventStack.ExtentReports.Reporter;
using AventStack.ExtentReports.Reporter.Configuration;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TechTalk.SpecFlow;
namespace Extent_Report
{
[Binding]
[TestFixture]
class Hooks
{
public static ExtentReports extent;
public static ExtentHtmlReporter htmlReporter;
public static ExtentTest test;
// public static object Theme { get; private set; }
static Hooks()
{
if (extent == null)
{
BasicSetUp();
}
}
[BeforeScenario]
public static void Setup()
{
BasePage.Intitialize();
BasePage.Navigate();
test = extent.CreateTest(ScenarioContext.Current.ScenarioInfo.Title);
}
[AfterScenario]
public void TearDown()
{
if (ScenarioContext.Current.TestError != null)
{
var error = ScenarioContext.Current.TestError;
var errormessage = "<pre>" + error.Message + "</pre>";
extent.AddTestRunnerLogs(errormessage);
test.Log(Status.Error, errormessage);
test.Fail(errormessage);
}
BasePage.Quit();
}
[OneTimeSetUp]
public static void BasicSetUp()
{
string pth = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
// string pth = System.IO.Directory.GetCurrentDirectory();
string actualPath = pth.Substring(0, pth.LastIndexOf("bin"));
string projectPath = new Uri(actualPath).LocalPath;
Console.WriteLine(" -----------Project Path--------------------------------------");
Console.WriteLine(projectPath);
string reportPath = projectPath + "Reports\\TestExecutionRunReport.html";
// Console.WriteLine("Report Path is " + reportPath);
htmlReporter = new ExtentHtmlReporter(reportPath);
htmlReporter.Configuration().Theme = Theme.Dark;
htmlReporter.Configuration().DocumentTitle = "SpecFlow Test Resport Document";
htmlReporter.Configuration().ReportName = "Feature Run Results";
extent = new ExtentReports();
extent.AttachReporter(htmlReporter);
//extent.LoadConfig(projectPath + "Extent-Config.xml");
}
[AfterFeature()]
public static void EndReport()
{
extent.Flush();
}
}
}
Reference:
You need to use hook [After step] or [Before step] and add below content to it
test = test.info(ScenarioStepContext.Current.StepInfo.Text);
you can also manipulate and provide more information in it if required.
Related
I have an app which uses zxing to scan qr codes in the app. However when I build the app with these scripts in the scene the app crashes on startup. I thought it was something in the Awake() or Start() but I've wrapped those methods in a try catch, and even then I'm not getting any errors, and it doesn't crash on android and in the editor.
I don't have access to a Mac, and am using Unity Cloud Build to build it.
I also don't know how to enable permissions, I thought I did when creating the .p12 file, but I've also found that there's an info.plist file that I have to request permissions with.
Prior research I found this Unity Question about adding items to the Xcode project but not only did including the xcodeapi give me errors, but the using statements didn't work.
There are two scripts
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
public class WebCamController : MonoBehaviour {
public int desiredWidth = 1280;
public int desiredHeight = 720;
public int desiredFPS = 60;
public RawImage output;
[HideInInspector]
public WebCamTexture webcamTexture;
void Start ()
{
webcamTexture = new WebCamTexture(desiredWidth, desiredHeight, desiredFPS);
output.texture = webcamTexture;
Play();
}
public void Play()
{
webcamTexture.Play();
}
public void Pause()
{
webcamTexture.Stop();
}
}
and
using UnityEngine;
using System.Collections;
using ZXing;
using ZXing.QrCode;
using ZXing.Common;
using System;
public class CodeScanner : MonoBehaviour {
private static CodeScanner _instance;
public static CodeScanner Instance
{
get
{
if(null == _instance)
{
Debug.Log("Code Scanner Instance not found");
}
return _instance;
}
}
[Header("References")]
public WebCamController wcc;
[Header("Properties")]
private BarcodeReader codeScanner;
private string lastScanned = "";
public delegate void Found(string text, string type);
public event Found OnCodeScanned;
private bool active;
public void Awake()
{
_instance = this;
}
void Start () {
codeScanner = new BarcodeReader();
StartCoroutine(ReadCode());
wcc.Play();
}
IEnumerator ReadCode()
{
while (active)
{
try
{
var data = codeScanner.Decode(wcc.webcamTexture.GetPixels32(), wcc.webcamTexture.width, wcc.webcamTexture.height);
if (data != null)
{
//if (data.Text != lastScanned)
//{
OnCodeScanned(data.Text, data.BarcodeFormat.ToString());
//}
lastScanned = data.Text;
}
}
catch(Exception e)
{
}
yield return new WaitForSeconds(1.0f);
}
}
public void Activate()
{
wcc.Play();
active = true;
StartCoroutine(ReadCode());
}
public void Stop()
{
active = false;
wcc.Pause();
}
}
My device is added properly to the .p12 certificate I can compile and run the program without these scripts in the scene.
I am using the given code in spec flow to generate the extent report. Test execute and report generated successfully but wrong steps name displayed in the extent report, And in the extent report replace with When. Steps come under And displayed in When while in the feature file steps written in And section.
Steps written under And syntax in feature files, displaying under When in Extent report.
I am using the following code to generate extent report.
using AventStack.ExtentReports;
using AventStack.ExtentReports.Gherkin.Model;
using AventStack.ExtentReports.Reporter;
using AventStack.ExtentReports.Reporter.Configuration;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TechTalk.SpecFlow;
namespace ALD_Belgium
{
[Binding]
[TestFixture]
class Hooks
{
public static ExtentTest featureName;
public static ExtentReports extent;
public static ExtentHtmlReporter htmlReporter;
public static ExtentTest test;
// public static object Theme { get; private set; }
static Hooks()
{
if (extent == null)
{
BasicSetUp();
}
}
[BeforeFeature]
public static void BeforeFeature()
{
featureName = extent.CreateTest<Feature>(FeatureContext.Current.FeatureInfo.Title);
}
[BeforeScenario]
public static void Setup()
{
BasePage.Intitialize();
BasePage.Navigate();
// test = extent.CreateTest(ScenarioContext.Current.ScenarioInfo.Title);
test = featureName.CreateNode<Scenario>(ScenarioContext.Current.ScenarioInfo.Title);
}
[AfterScenario]
public void TearDown()
{
if (ScenarioContext.Current.TestError != null)
{
var error = ScenarioContext.Current.TestError;
var errormessage = "<pre>" + error.Message + "</pre>";
extent.AddTestRunnerLogs(errormessage);
test.Log(Status.Error, errormessage);
test.Fail(errormessage);
}
BasePage.Quit();
}
[OneTimeSetUp]
public static void BasicSetUp()
{
string pth = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
// string pth = System.IO.Directory.GetCurrentDirectory();
string actualPath = pth.Substring(0, pth.LastIndexOf("bin"));
string projectPath = new Uri(actualPath).LocalPath;
Console.WriteLine(" -----------Project Path--------------------------------------");
Console.WriteLine(projectPath);
string reportPath = projectPath + "Reports\\TestExecutionRunReport.html";
// Console.WriteLine("Report Path is " + reportPath);
htmlReporter = new ExtentHtmlReporter(reportPath);
htmlReporter.Configuration().Theme = Theme.Dark;
htmlReporter.Configuration().DocumentTitle = "SpecFlow Test Resport Document";
htmlReporter.Configuration().ReportName = "Feature Run Results";
extent = new ExtentReports();
extent.AttachReporter(htmlReporter);
//extent.LoadConfig(projectPath + "Extent-Config.xml");
}
[AfterTestRun]
public static void EndReport()
{
extent.Flush();
}
[AfterStep]
public static void InsertReportingSteps()
{
var stepType = ScenarioStepContext.Current.StepInfo.StepDefinitionType.ToString();
if (ScenarioContext.Current.TestError == null)
{
if (stepType == "Given")
test.CreateNode<Given>(ScenarioStepContext.Current.StepInfo.Text);
else if (stepType == "When")
test.CreateNode<When>(ScenarioStepContext.Current.StepInfo.Text);
else if (stepType == "And")
test.CreateNode<And>(ScenarioStepContext.Current.StepInfo.Text);
else if (stepType == "Then")
test.CreateNode<Then>(ScenarioStepContext.Current.StepInfo.Text);
}
else if (ScenarioContext.Current.TestError != null)
{
if (stepType == "Given")
test.CreateNode<Given>(ScenarioStepContext.Current.StepInfo.Text).Fail(ScenarioContext.Current.TestError.Message);
else if (stepType == "When")
test.CreateNode<When>(ScenarioStepContext.Current.StepInfo.Text).Fail(ScenarioContext.Current.TestError.Message);
else if (stepType == "And")
test.CreateNode<And>(ScenarioStepContext.Current.StepInfo.Text).Fail(ScenarioContext.Current.TestError.Message);
else if (stepType == "Then")
test.CreateNode<Then>(ScenarioStepContext.Current.StepInfo.Text).Fail(ScenarioContext.Current.TestError.Message);
}
}
}
}
enter image description here
The problem maybe because in SpecFlow main keywords are -
Given, When, Then
Can be that this report takes steps descriptions not from Features file but from code itself, where method, I think, is written with "When" keyword.
I have to write unit test case and increase the code coverage for a pre written controller.
using System.Collections.Generic;
using Newtonsoft.Json;
using System;
using System.Web.Mvc;
using TW.Data.Business;
using TW.Data.Service;
using TW.Web.Models;
using TW.Common.Utility;
namespace TW.Web.Controllers
{
[Authorize]
public class BillinInfoSearchController : Controller
{
private IBillinInfoSearch _IRepository;
private IResponseMessage _ServiceResponse;
public BillinInfoSearchController(IBillinInfoSearch irepository, IResponseMessage serviceresponse)
{
_IRepository = irepository;
_ServiceResponse = serviceresponse;
}
public ActionResult ActionMethod()
{
BillinInfoSearchViewModel viewModel = new BillinInfoSearchViewModel();
viewModel.Success = false;
try
{
if (!Sitecore.Context.PageMode.IsExperienceEditor)
{
//Getting Custom Properties
var userBillAccountNumber = Sitecore.Context.User.Profile.GetCustomProperty(UserProfileDetails.BillAccountNumber);
var userObjectIdentifier = Sitecore.Context.User.Profile.GetCustomProperty(UserProfileDetails.ObjectIdentifier);
if (!string.IsNullOrEmpty(userBillAccountNumber) && !string.IsNullOrEmpty(userObjectIdentifier))
{
viewModel.ModelList = new List<BillinInfoSearchModel>();
_ServiceResponse = _IRepository.SubmitModelDetails(userBillAccountNumber, userObjectIdentifier);
if (_ServiceResponse.Success && !string.IsNullOrEmpty(_ServiceResponse.Content) && _ServiceResponse.Content.Contains("Top_GUID")
&& !Sitecore.Context.PageMode.IsExperienceEditorEditing)
{
List<BillinInfoSearchModel> objectList = JsonConvert.DeserializeObject<List<BillinInfoSearchModel>>(_ServiceResponse.Content);
if (objectList.Count > 0)
{
viewModel.Success = true;
viewModel.ModelList = objectList;
}
}
}
}
}
catch (Exception ex)
{
Sitecore.Diagnostics.Log.Error(ex.Message, this);
}
return View("~/Views/OAM/BillinInfoSearchView.cshtml", viewModel);
}
}
}
I wrote one Unit test case and code coverage comes to 24%. If i divide the controller code into small piece of code & methods and then call those in Unit test class, coverage increasing to 65%,but code is deployed in UAT and dont want to update the deployed code.
Is there we can increasing the code coverage without modifying the existing controller
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NSubstitute;
using System.Web.Mvc;
using TW.Data.Business;
using TW.Data.Service;
using TW.Web.Controllers;
using TW.Common.Utility;
namespace TW.UnitTest.Controller
{
[TestClass]
public class BillinInfoSearchControllerTest
{
[TestMethod]
public void BillinInfoSearchControllerViewName()
{
IBillinInfoSearch _IRepository = Substitute.For<IBillinInfoSearch>();
IResponseMessage _ServiceResponse = Substitute.For<IResponseMessage>();
BillinInfoSearchController twLiveController = new BillinInfoSearchController(_IRepository, _ServiceResponse);
Sitecore.Context.User.Profile.SetCustomProperty(UserProfileDetails.BillAccountNumber, "102134");
Sitecore.Context.User.Profile.SetCustomProperty(UserProfileDetails.ObjectIdentifier, "ef84bc1c-825c-4d8c-9801-3c3fc511a40e");
ViewResult action = twLiveController.ActionMethod() as ViewResult;
Assert.AreEqual("~/Views/OAM/BillinInfoSearchView.cshtml", action.ViewName);
}
}
}
I am fetching the values from sqlite database in my iOS application. I have written a Select statement like stringquery = "Select * from tablename" and executing it using
database.Query < table > (stringquery);
and assigning the values to the properties in a class. The class has properties with the same name that the columns has in the table in sqlite database.
as the above statement executes i am getting error Object reference not set to an instance of an object
Please suggest the solution this issue.
Thanks
It sounds like you are initializing the SQLite Database incorrectly. I've added code below that shows how to implement a SQLite Database in Xamarin.Forms.
This Xamarin.Forms app, contains a fully implemented SQLite Database:
https://github.com/brminnick/InvestmentDataSampleApp
ISQLite.cs
Create this file in the Xamarin.Forms PCL. It allows us to access the iOS and Android File Systems to create our Database Connection
using SQLite;
namespace SampleApp
{
public interface ISQLite
{
SQLiteAsyncConnection GetConnection();
}
}
SQLite_Android.cs
Create this file in the Android project. It returns the Android file path for our SQLite Database Connection.
using System.IO;
using SampleApp.Droid;
using SQLite;
using Xamarin.Forms;
[assembly: Dependency(typeof(SQLite_Android))]
namespace SampleApp.Droid
{
public class SQLite_Android : ISQLite
{
#region ISQLite implementation
public SQLiteAsyncConnection GetConnection()
{
var sqliteFilename = "DatabaseFileName.db3";
string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); // Documents folder
var path = Path.Combine(documentsPath, sqliteFilename);
var conn = new SQLiteAsyncConnection(path, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create | SQLiteOpenFlags.SharedCache);
// Return the database connection
return conn;
}
#endregion
}
}
SQLite_iOS.cs
Create this file in the iOS project. It returns the iOS file path for our SQLite Database Connection.
using System;
using System.IO;
using SQLite;
using Xamarin.Forms;
using SampleApp.iOS;
[assembly: Dependency(typeof(SQLite_iOS))]
namespace SampleApp.iOS
{
public class SQLite_iOS : ISQLite
{
#region ISQLite implementation
public SQLiteAsyncConnection GetConnection()
{
var sqliteFilename = "DatabaseFileName.db3";
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // Documents folder
string libraryPath = Path.Combine(documentsPath, "..", "Library"); // Library folder
var path = Path.Combine(libraryPath, sqliteFilename);
var conn = new SQLiteAsyncConnection(path, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create | SQLiteOpenFlags.SharedCache);
// Return the database connection
return conn;
}
#endregion
}
}
SampleModelDatabase.cs
Create this file in your Xamarin.Forms PCL
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using SQLite;
using Xamarin.Forms;
namespace SampleApp
{
public static class SampleModelDatabase
{
#region Constant Fields
static readonly SQLiteAsyncConnection _database = DependencyService.Get<ISQLite>().GetConnection();
#endregion
#region Fields
static bool _isInitialized;
#endregion
#region Methods
public static async Task<IList<SampleModel>> GetAllItemsAsync()
{
if (!_isInitialized)
await Initialize();
return await _database.Table<SampleModel>().ToListAsync();
}
public static async Task<int> SaveItemAsync(SampleModel model)
{
if (!_isInitialized)
await Initialize();
return await _database.InsertOrReplaceAsync(model);
}
public static async Task<int> DeleteItemAsync(SampleModel model)
{
if (!_isInitialized)
await Initialize();
return await _database.DeleteAsync(model);
}
public static async Task<int> GetNumberOfRowsAsync()
{
if (!_isInitialized)
await Initialize();
return await _database.Table<SampleModel>().CountAsync();
}
static async Task Initialize()
{
await _database.CreateTableAsync<SampleModel>();
_isInitialized = true;
}
#endregion
}
}
I encountered the same problem as you. I found out that the point is database connection, a process that takes time, hasn't completely finished at the moment I started my query. so the solution will be something like:
await Connectdb();
// now do your query
var treatment = _database.Query<ClassName>("SELECT * FROM [TableName] WHERE ...");
where the Connectdb() is a function that does:
DependencyService.Get<IDatabaseConnection>().DbConnection();
I am trying to get a specific TestSuite using the TFS API for a TestPlan.
The TestSuite could exist anywhere within a TestSuite hierarchy, so, of course I could write a recursive function. I want something more efficient however.
Is there a method I am missing, or maybe a query that I could write?
If you already know the testSuiteId things are quite straightforward. You only need to know the name of your TeamProject teamProjectName:
using System;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.TestManagement.Client;
namespace GetTestSuite
{
class Program
{
static void Main()
{
int testSuiteId = 555;
const string teamProjectName = "myTeamProjectName";
var tpc =
TfsTeamProjectCollectionFactory.GetTeamProjectCollection(
new Uri("http://tfsURI"));
var tstService = (ITestManagementService)tpc.GetService(typeof(ITestManagementService));
var tProject = tstService.GetTeamProject(teamProjectName);
var myTestSuite = tProject.TestSuites.Find(testSuiteId);
}
}
}
If you don't, you probably need to go for a solution similar to the one presented here (it's a S.Raiten post), where recursion does come into picture. Access to a testPlanId is assumed:
using System;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.TestManagement.Client;
namespace GetTestSuite
{
class Program
{
static void Main()
{
int testPlanId = 555;
const string teamProjectName = "myTeamProjectName";
var tpc =
TfsTeamProjectCollectionFactory.GetTeamProjectCollection(
new Uri("http://tfsURI"));
var tstService = (ITestManagementService)tpc.GetService(typeof(ITestManagementService));
var tProject = tstService.GetTeamProject(teamProjectName);
var myTestPlan = tProject.TestPlans.Find(testPlanId);
GetPlanSuites(myTestPlan.RootSuite.Entries);
}
public static void GetPlanSuites(ITestSuiteEntryCollection suites)
{
foreach (ITestSuiteEntry suiteEntry in suites)
{
Console.WriteLine(suiteEntry.Id);
var suite = suiteEntry.TestSuite as IStaticTestSuite;
if (suite != null)
{
if (suite.Entries.Count > 0)
GetPlanSuites(suite.Entries);
}
}
}
}
}