How to increase Code coverage for pre-defined Controller in c# MVC - asp.net-mvc

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);
}
}
}

Related

Steps doesn't generate in Extent Report in specflow

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.

Wrong step name displayed in Extent Report And replaced with When

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.

Decompress Action Filter before action in MVC

I wrote an action filter that does compression for the response of some actions.
I'm wanting to write a DecompressRequest attribute also. There are a request or 2 that could be fairly large from the sender that I would like to optionally compress on their end. Is there a way to like OnActionExecuted to inject some code that would detect if it is compressed -> decompress it then submit it to the normal MVC route parsing mechanisms?
I'm just trying to findout where to put my code and how to inject it into MVC, don't need anyone to write the decompression code for me.
So this is an ApiController example of what works, you'd probably have to structure it differently for a normal controller since ApiController requires the parameters to be a bit different for posts. Definitely not 'impossible' as others claimed.
using System;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using System.IO.Compression;
using System.Web.Http.Filters;
using Nito.AsyncEx.Synchronous;
using System.Collections.Generic;
using System.Web.Http.Controllers;
namespace MyProject.Models
{
public class DecompressRequestAttribute : ActionFilterAttribute
{
private bool IsRequestCompressed(HttpActionContext message)
{
foreach(var encoding in message.Request.Content.Headers.ContentEncoding)
{
if(encoding.Equals("gzip",StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
public override void OnActionExecuting(HttpActionContext actionContext)
{
if(actionContext.Request.Method.Method == "POST" && actionContext.ActionArguments.Count == 1 && IsRequestCompressed(actionContext))
{
Stream stream = actionContext.Request.Content.ReadAsStreamAsync().WaitAndUnwrapException();
if (stream != null)
{
using (MemoryStream decompressed = new MemoryStream())
{
using (GZipStream compression = new GZipStream(stream, CompressionMode.Decompress))
{
int amount;
byte[] buffer = new byte[2048];
stream.Seek(0, SeekOrigin.Begin); //Stupid stream doesn't start at beginning for some reason
while ((amount = compression.Read(buffer, 0, buffer.Length)) > 0)
decompressed.Write(buffer, 0, amount);
}
string json = Encoding.UTF8.GetString(decompressed.ToArray());
foreach (HttpParameterDescriptor parameter in actionContext.ActionDescriptor.GetParameters())
{
actionContext.ActionArguments[parameter.ParameterName] = JsonConvert.DeserializeObject(json, parameter.ParameterType);
}
}
}
}
base.OnActionExecuting(actionContext);
}
}
}

Can't create Xamarin Forms Picker custom rendere

Hi i easily created custom renderer for Forms Entry control, but when i tried to create one to Picker i get this error:
Error CS0115: `Punteam.iOS.PunteamPickerRederer.OnElementChanged(Xamarin.Forms.Platform.iOS.ElementChangedEventArgs<Xamarin.Forms.Picker>)' is marked as an override but no suitable method found to override (CS0115) (Punteam.iOS)
this is my code on Forms project:
using System;
using Xamarin.Forms;
namespace Punteam
{
public class PunteamPicker : Picker
{
}
}
on IOS Project:
using Xamarin.Forms.Platform.iOS;
using Xamarin.Forms;
using Xamarin.Forms.Platform;
using Punteam;
using Punteam.iOS;
using UIKit;
using EventKitUI;
[assembly: ExportRenderer (typeof(PunteamPicker), typeof(PunteamPickerRederer))]
namespace Punteam.iOS
{
public class PunteamPickerRederer : PunteamPicker
{
protected override void OnElementChanged (ElementChangedEventArgs<Picker> e)
{
/* base.OnElementChanged (e);
this.Control.TextAlignment = MonoTouch.UIKit.UITextAlignment.Center;
this.Control.TextColor = UIColor.White;
this.Control.BackgroundColor = UIColor.Clear;
this.Control.BorderStyle = UITextBorderStyle.RoundedRect;
this.Layer.BorderWidth = 1.0f;
this.Layer.CornerRadius = 4.0f;
this.Layer.MasksToBounds = true;
this.Layer.BorderColor = UIColor.White.CGColor;*/
}
}
}
Any body know's Why i get this error?
public class PunteamPickerRederer : PunteamPicker
should be
public class PunteamPickerRederer : PickerRenderer

Get a specific TestSuite by Id using the TFS API

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);
}
}
}
}
}

Resources