why "Visual wizard" doesn't see (find) my instances? - instance

using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
public List<test> testL_I_A;
// doesn't see "testL_I_A" instance name
te = new List();
public enum TypeE{
pistol, shotgun, sword
}
static void Main()
{
Console.WriteLine("Hello World!");
}
public class test {
TypeE tpEI;
public Action activateA;
}
}
it also doesn't see instance's name of classes "program" or "test" if i'm creating them

Related

Can't run tests for a controller doing Entity Framework Core operations in xUnit

I can't run tests for a controller doing Entity Framework Core operations in xUnit. I am using in-memory database and the error I am getting is:
**A test class may only define a single public constructor.**
The test class is:
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MyAppT.Controllers;
using MyAppT.Models;
using Xunit;
namespace TestingProject
{
public class TestRegistration
{
#region Seeding
protected TestRegistration(DbContextOptions<AppDbContext> contextOptions)
{
ContextOptions = contextOptions;
Seed();
}
protected DbContextOptions<AppDbContext> ContextOptions { get; }
private void Seed()
{
using (var context = new AppDbContext(ContextOptions))
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var one = new Register()
{
Name = "Test One",
Age = 40
};
var two = new Register()
{
Name = "Test Two",
Age = 50
};
var three = new Register()
{
Name = "Test Three",
Age = 60
};
context.AddRange(one, two, three);
context.SaveChanges();
}
}
#endregion
[Fact]
public void Test_Create_GET_ReturnsViewResultNullModel()
{
using (var context = new AppDbContext(ContextOptions))
{
// Arrange
var controller = new RegistrationController(context);
// Act
var result = controller.Create();
// Assert
var viewResult = Assert.IsType<ViewResult>(result);
Assert.Null(viewResult.ViewData.Model);
}
}
}
}
The controller that is doing EF core operations is:
using Microsoft.AspNetCore.Mvc;
using MyAppT.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MyAppT.Controllers
{
public class RegistrationController : Controller
{
private AppDbContext context;
public RegistrationController(AppDbContext appDbContext)
{
context = appDbContext;
}
public IActionResult Create()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Create(Register register)
{
if (ModelState.IsValid)
{
context.Add(register);
await context.SaveChangesAsync();
return RedirectToAction("Read");
}
else
return View();
}
}
}
The strange error while running the test shows up in Test Explorer - A test class may only define a single public constructor.
I could not find anything about it on stackoverflow. Please help in fixing it?
Your constructor needs to be parameterless for this to work, unless you're using some DI framework within your testing project, which is something that you generally shouldn't be doing.
Instead, try creating the DBContextOptions within the constructor and assigning it to your class variable. You can then use it when you seed the database, and when you test against it.
Try this instead. You will need to add the Microsoft.EntityFrameworkCore.InMemory package into your test project if you don't have this in there already.
public class TestRegistration
{
#region Seeding
public TestRegistration()
{
ContextOptions = new DbContextOptionsBuilder<AppDbContext>()
.UseInMemoryDatabase(databaseName: "Test")
.Options;
Seed();
}

Multiple browser instance launch when i execute my test

I an new in specflow i am implementing framework. When i create one feature file with multiple scenario and execute my test than it open one browser instance and run successful when i add one more feature file with multiple scenario and execute my test than it launch multiple browser instance one instance for each scenario can anyone help me out what's wrong in my code
Start.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TechTalk.SpecFlow;
namespace Orange_HRM
{
class Start : SeleniumDriver
{
[BeforeScenarioBlock]
public void Setup()
{
Intitialize();
WebDriver.Navigate().GoToUrl(BaseAddress);
}
[AfterScenarioBlock]
public void TearDown()
{
Close();
}
}
}
SeleniumDriver.cs
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Orange_HRM
{
class SeleniumDriver
{
public static IWebDriver WebDriver;
public static string BaseAddress
{
get { return Constants.Url; }
}
public static void Intitialize()
{
WebDriver = new ChromeDriver();
WebDriver.Manage().Window.Maximize();
TurnOnWait();
}
public static void Navigate()
{
WebDriver.Navigate().GoToUrl(BaseAddress);
}
public static void Close()
{
WebDriver.Close();
}
public static void Quit()
{
WebDriver.Quit();
}
private static void TurnOnWait()
{
WebDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
WebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromMinutes(2);
}
}
}
You are using SpecFlow of techtalk.
Concept name is Hooks.
to perform automatic logic operations at specific timings.So, hooks are event bindings.
running tests in multiple threads with SpecFlow+ Runner.
So, you can put orders,
class Start : SeleniumDriver
{
[BeforeScenario(Order = 0)]
public void Setup()
{
Intitialize();
WebDriver.Navigate().GoToUrl(BaseAddress);
}
[BeforeScenario(Order = 1)]
public void TearDown()
{
Close();
}
}
i like to suggest you dont use them, Bindings Class without Hooks.
i.e. [BeforeTestRun] [AfterTestRun] use them instead.
[AfterScenario]
public void CleanUp()
{
if (seleniumDriver != null)
{
SeleniumDriver.Dispose();
seleniumDriver = null;
}
}
You can initialise and close the driver at Test Run level instead of scenario level. And maintain the url navigation alone at Scenario level. So that the driver will be initiated before test starts and quit after the test completes. Also the page will get refreshed before each scenario run.
namespace Orange_HRM
{
class Start : SeleniumDriver
{
[BeforeTestRun]
public static void Setup()
{
Intitialize();
}
[AfterTestRun]
public static void TearDown()
{
Quit();
}
[AfterScenarioBlock]
public void navigateToUrl()
{
WebDriver.Navigate().GoToUrl(BaseAddress);
}
}
}
Also you have used WebDriver.Close() instead WebDriver.Quit(). If we use WebDriver.Close() for the main window, then session will be terminated. Then if we try to access the same webdriver object again, it will throw No such session error.
WebDriver.Close() is meant for closing child window if we are working with mulitple windows. So to close main window, we have to use WebDriver.Quit() directly.

Issue in Login in Page Object Model

I have a use case which denotes below steps
I am trying to implement it using POM in Nunit.
Open Login Form
Feed the data in the username and password fields using Excel.
3a. If the credentials are correct
a)Log the test case as passed
b)Click on Log Off link
4.Close the remaining browser window
3b.If the credentials are incorrect
a) Log the test case as failed
b) Clear the username and password textboxes
c) No need to close the browser window.
Now the issue is already driver is instantiated in [Setup] in Main Class.
How do we instantiate the browser window again in case the login is successful.
I am adding the below code
Login Object Class
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using SeleniumExtras.PageObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PracticePrograms.PageObjectsWithPageFactory
{
public class VSSLoginObjects
{
[FindsBy(How = How.Id, Using = "userNameOldLook")]
public IWebElement Userid { get; set; }
[FindsBy(How = How.XPath, Using = "//input[#type='password']")]
public IWebElement Password { get; set; }
[FindsBy(How = How.XPath, Using = "//a[contains(text(),'login')]")]
public IWebElement Btn_Login { get; set; }
[FindsBy(How = How.XPath, Using = "//li[contains(text(),'Login failed')]")]
public IWebElement Lbl_Login_Failed { get; set; }
[FindsBy(How = How.XPath, Using = "//a[contains(text(),'Logoff')]")]
public IWebElement lnk_logoff;
public VSSLoginObjects()
{
PageFactory.InitElements(DriverInstance.driver, this);
}
public void Login_QAPortal()
{
Userid.SendKeys("v0c1344");
Wait.UntilElementDisplayed(DriverInstance.driver, Password);
Password.SendKeys("welcome5");
Btn_Login.Click();
//return new QAPortal_LandingPage_Objects();
}
public void Test_Login_QA_Portal()
{
String Excel = #"C:\\Selenium Files\\TestData.xlsx";
int length = ExcelClassTemp.GetRowCount(Excel, 3);
for (int i = 2; i <= length; i++)
{
String data = ExcelClassTemp.ReadExcel(Excel, 3, i, 1);
String upper_data = data.ToUpper();
Userid.SendKeys(upper_data);
Password.SendKeys("Welcome567");
Btn_Login.Click();
if (DriverInstance.driver.PageSource.Contains("Trucks Portal"))
{
Console.WriteLine("User Credentials" + upper_data + "Passed");
lnk_logoff.Click();
DriverInstance.driver.Close();
}
else
{
Console.WriteLine("User Credentials" + upper_data + "Failed");
Userid.Clear();
Password.Clear();
}
}
}
}
}
Adding the Main Class
Main Class
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using OpenQA.Selenium.Chrome;
namespace PracticePrograms.PageObjectsWithPageFactory
{
public class Tests
{
[SetUp]
public void setup()
{
DriverInstance.driver = new ChromeDriver();
DriverInstance.driver.Navigate().GoToUrl("Go to Url");
DriverInstance.driver.Manage().Window.Maximize();
}
[Test]
public void Perform_VSS_Login()
{
VSSLoginObjects login = new VSSLoginObjects();
login.Test_Login_QA_Portal();
}
}
}
Make few changes :
the reference DriverInstance.driver declare this as global.
and when you are creating object of VSSLoginObjects in your Test method like :
VSSLoginObjects login = new VSSLoginObjects();
Pass the reference of DriverInstance.driver in new VSSLoginObjects();
Something like : VSSLoginObjects(reference of driver object) .
Explanation : When you create the object of any class and pass the reference , a parameterized constructor will be called.
I believe this constructor will be called:
public VSSLoginObjects()
{
PageFactory.InitElements(DriverInstance.driver, this);
}

How to use the `Ninject.Extensions.Factory` to dynamically generate factories for internals classes?

I need to use the Ninject.Extensions.Factory to generate the constructor of internal classes. Follow one example:
using Ninject.Extensions.Conventions;
using Ninject.Modules;
using Ninject.Extensions.Factory;
namespace ClassLibrary
{
using System;
namespace ClassLibrary
{
internal class Class1
{
public void Print(string message)
{
Console.WriteLine(message);
}
}
internal interface IClass1Factory
{
Class1 Create();
}
public interface IInterface2
{
void PrintMessage();
}
internal class Class2 : IInterface2
{
private readonly IClass1Factory _class1Factory;
public Class2(IClass1Factory class1Factory)
{
_class1Factory = class1Factory;
}
public void PrintMessage()
{
Class1 class1 = _class1Factory.Create();
class1.Print("Class2's IInterface2 'PrintMessage' implementation.");
}
}
public class MyNinjectModule : NinjectModule
{
public override void Load()
{
Kernel.Bind(r => r
.FromThisAssembly()
.IncludingNonePublicTypes()
.SelectAllClasses()
.BindAllInterfaces());
Kernel.Bind<IClass1Factory>().ToFactory();
}
}
}
}
Application using the library:
using ClassLibrary.ClassLibrary;
using Ninject;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
IKernel kernel = new StandardKernel();
kernel.Load<MyNinjectModule>();
IInterface2 interface2 = kernel.Get<IInterface2>();
interface2.PrintMessage();
}
}
}
Even after include [assembly: InternalsVisibleTo(InternalsVisible.ToDynamicProxyGenAssembly2)] I'm getting the following run tine error:
{"Type 'Castle.Proxies.IClass1FactoryProxy' from assembly
'DynamicProxyGenAssembly2, Version=0.0.0.0, Culture=neutral,
PublicKeyToken=null' is attempting to implement an inaccessible
interface.":""}
Any idea how to fix this?

Ninject Interception not working with MVC 5

I am trying to implement an InterceptAttribute which should intercept any method I add the attribute to. I have it working in a WebAPI solution, however, I cannot get it to work in an MVC 5 application. The code is the same in both projects. The following code is the attribute I created.
using Ninject;
using Ninject.Extensions.Interception;
using Ninject.Extensions.Interception.Attributes;
using Ninject.Extensions.Interception.Request;
namespace Questionnaire.Common.InterceptAttributes
{
public class InterceptCacheAttribute : InterceptAttribute
{
public double TimeOut { get; set; }
public override IInterceptor CreateInterceptor(IProxyRequest request)
{
var cacheInterceptor = request.Kernel.Get<CacheInterceptor>();
cacheInterceptor.TimeOut = TimeOut;
return cacheInterceptor;
}
}
}
The CacheInterceptor code is as follows:
using System;
using System.Text;
using Ninject;
using Ninject.Extensions.Interception;
using Ninject.Extensions.Interception.Request;
namespace Questionnaire.Common.Interceptors
{
public class CacheInterceptor : IInterceptor
{
[Inject]
public ICaching Cache { get; set; }
public double TimeOut { get; set; }
public void Intercept(IInvocation invocation)
{
var minutes = Cache.TimeOutMinutes;
if (Math.Abs(TimeOut - default(double)) > 0)
{
minutes = TimeOut;
}
invocation.ReturnValue = Cache.Get(GenerateCacheKey(invocation.Request), minutes, delegate
{
invocation.Proceed();
return invocation.ReturnValue;
});
}
private static string GenerateCacheKey(IProxyRequest request)
{
var sb = new StringBuilder(request.Method.Name).Append(".");
foreach (var argument in request.Arguments)
{
if (argument == null)
{
sb.Append("null");
}
else if (argument is string && argument.ToString().Length < 50)
{
sb.Append((string)argument);
}
else
{
sb.Append(argument.GetHashCode());
}
sb.Append(".");
}
sb.Remove(sb.Length - 1, 1);
return sb.ToString();
}
}
}
Finally I added the attribute to the following method.
using System.Configuration;
using Questionnaire.Common.InterceptAttributes;
namespace Questionnaire.Common.Utility
{
public class ConfigurationUtilities
{
[InterceptCache(TimeOut = 1440)]
public virtual string GetEnvironmentConnectionString(string name)
{
var connectionStringSettings = ConfigurationManager.ConnectionStrings[name + "_" + HostEnvironment];
return connectionStringSettings != null ? connectionStringSettings.ConnectionString : null;
}
}
}
Code execution never enters into the InterceptCacheAttribute class. I have put debug points within that class and the CacheInterceptor class and the debug points are never hit. The method the attribute is on executes just fine, but, I want it to be intercepted and that is not happening. I have the same code in a different project. That project is a WebAPI project which works great. The methods are intercepted and everything functions as it should. Can someone explain to me why I can't get it to work in the MVC 5 application? I would greatly appreciate it.
answer to BatteryBackupUnit's question:
The answer is I can't. The following is my NinjectWebCommon.cs class.
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(Mayo.Questionnaire.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(Mayo.Questionnaire.App_Start.NinjectWebCommon), "Stop")]
namespace Questionnaire.App_Start
{
using System;
using System.Web;
using System.Web.Http;
using System.Linq;
using ApplicationExtensions;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
public static void Stop()
{
bootstrapper.ShutDown();
}
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
RegisterServices(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
private static void RegisterServices(IKernel kernel)
{
foreach (var module in from assembly in AppDomain.CurrentDomain.GetAssemblies()
select assembly.GetNinjectModules()
into modules
from module in modules
where !kernel.GetModules().Any(m => m.Name.Equals(module.Name))
select module)
{
kernel.Load(module);
}
}
}
}
Inside the RegisterServices method every assembly in the application is iterated over and any classes that inherit from NinjectModule are loaded. However, I can't verify that it is working because I can't debug it. I have tried, but, execution is never stopped within the class. I know that the class is being instantiated and that the modules are being loaded because I have bindings in those modules that are working, however, I can't verify it.