Dependency Resolution Exception - c#

I am doing Unit Testing In my Project.When I try to unit test my method a browser pops up and suddenly gets stopped after that I get a long exception I pasted following.
How to fix this mess as I have no idea whats the cause?
Exception:
https://paste.ubuntu.com/24389202/
BrowseHost Class
public static class BrowserHost
{
public static readonly SelenoHost Instance = new SelenoHost();
public static readonly String RootUrl;
static BrowserHost()
{
Instance.Run("BankingSite", 1468);
RootUrl= Instance.Application.Browser.Url;
}
}
UnitTest Class
namespace BankingSite.FunctionalUITests
{
[TestFixture]
public class LoanApplicationTest
{
[Test]
public void ShouldAcceptLoanApplication()
{
BrowserHost.Instance
.Application.Browser
.Navigate()
.GoToUrl($#"{BrowserHost.RootUrl}\LoanApplication\Apply");
var firstNameBox = BrowserHost.Instance.Application
.Browser
.FindElement(By.Id("FirstName"));
firstNameBox.SendKeys("Gentry");
var lastNameBox = BrowserHost.Instance.
Application.
Browser.
FindElement(By.Id("LastName"));
lastNameBox.SendKeys("Smith");
var ageBox = BrowserHost.Instance
.Application
.Browser
.FindElement(By.Id("Age"));
ageBox.SendKeys("40");
var incomeBox = BrowserHost.Instance
.Application
.Browser
.FindElement(By.Id("AnnualIncome"));
incomeBox.SendKeys("9999999");
Thread.Sleep(10000);
var applyButton = BrowserHost.Instance
.Application
.Browser
.FindElement(By.Id("Applt"));
applyButton.Click();
Thread.Sleep(10000);
var acceptMessageText = BrowserHost.Instance
.Application
.Browser
.FindElement(By.Id("acceptMessage"));
Assert.That(acceptMessageText, Is.EqualTo("Congratulations Gentry - Your Application was accepted!"));
Thread.Sleep(10000);
}
}
Following is the Screen Shot of URL I am browsing directly.

Hard to tell from what you've provided, but there is a clue in the stack trace:
System.TypeInitializationException : The type initializer for 'BankingSite.FunctionalUITests.BrowserHost' threw an exception.
----> Autofac.Core.DependencyResolutionException : An exception was thrown while executing a resolve operation. See the InnerException for details. ---> Not a Number (See inner exception for details.)
----> System.InvalidOperationException : Not a Number
Check the constructor for BankingSite.FunctionalUITests.BrowserHost and see if you can find the line that is causing the error. Apparently it is expecting a numeric value but received something else instead.

Related

How do I assert against a Boolean value to confirm that causes an exception to be thrown in C#?

I'm writing my unit tests for my application and I'm trying to make sure that an exception is throw in one of my services. That exception is throw based on a true/false condition but I'm not sure how to get it to work. I am using NSubstitute for mocking in my unit tests and MSTest for the testing framework.
Here is my unit test.
private readonly FileRepository _sut;
private readonly BlobServiceClient _blobServiceClient = Substitute.For<BlobServiceClient>();
private readonly BlobContainerClient _blobContainerClient = Substitute.For<BlobContainerClient>();
private readonly BlobClient _blobClient = Substitute.For<BlobClient>();
public BlobStorageFileRepositoryTests()
{
_blobServiceClient.GetBlobContainerClient(default).ReturnsForAnyArgs(_blobContainerClient);
_blobContainerClient.GetBlobClient(default).ReturnsForAnyArgs(_blobClient);
_sut = new FileRepository(_blobServiceClient);
}
[TestMethod]
[ExpectedException(typeof(Exception), "file already")]
public async Task PlaceFileInStorage_ShouldReturnErrorIfFileExists()
{
// Arrange
var fileName = "myfile.pdf";
// Act
_sut.CheckFileExists(fileName).Returns(true);
}
As you can see the test method is decorated with the expected exception type and the message we expect to see. The error I get when I attempt to run this test is:
Test method threw exception NSubstitute.Exceptions.CouldNotSetReturnDueToTypeMismatchException, but exception System.Exception was expected. Exception message: NSubstitute.Exceptions.CouldNotSetReturnDueToTypeMismatchException: Can not return value of type Task`1 for Response`1.get_Value (expected type Boolean).
This makes sense as I am returning a boolean when I declare CheckFileExists but I want to know how I can access the thrown error that occurs when the boolean is false. Here is the service itself so you can see the construction of this method.
public async Task PlaceFileInStorage(string fileName, byte[] data)
{
//Check if the file exists first
var fileCheck = await CheckFileExists(fileName);
var file = fileName.Insert(0, DateTime.UtcNow.ToString("yyyy-MM-dd-HH:mm:ss"));
if (fileCheck.Equals(false))
{
try
{
var blob = _container.GetBlobClient(fileName);
await using var ms = new MemoryStream(data, false);
await blob.UploadAsync(ms, CancellationToken.None);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
throw new Exception("This file already exists");
}
You can see above that it checks if the files exists in storage first and then we either save or return an exception based on that. So, in my unit test how can I check that the exception is thrown when the fileCheck condition is true?
Many thanks
I am not sure how NSubstitue works, but you're clearly receiving an exception because the mock you're trying to do is incorrect, hence your test fails because is NSubstitute who throws the exception, not your FileRepository class.
Now, if you want to check whether a tested method returns an exception of the expected type, you can use the Assert class:
Assert.ThrowsExceptionAsync<Exception>(async () => await _sut.PlaceFileInStorage(filename, data));
This assert will succeed only if the exception throw is of the type you specify.
Here you have the reference for this method: https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.testtools.unittesting.assert.throwsexceptionasync?view=visualstudiosdk-2022#microsoft-visualstudio-testtools-unittesting-assert-throwsexceptionasync-1

System.Data.Entity.Infrastructure.DbUpdateException Issue

I have a test method that tests a task that is suppose to get a task definition (task description) for edit:
[TestMethod]
public void GetTaskDefinitionsForEdit_HavingTaskDefinitions_ReturnsChecklistTaskDefinitions()
{
// this.CreateChecklistTaskDefinition(referenceKey: "Xxx123", description: "SomeDescription");
// this.checklistTaskTestHelper.CreateChecklistTaskDefinition(referenceKey: "Yyy234", description: "SomeOtherDescription");
this.helper.CreateChecklistTaskDefinition(referenceKey: "Xxx123", description: "SomeDescription");
this.helper.CreateChecklistTaskDefinition(referenceKey: "Yyy234", description: "SomeOtherDescription");
this.CompanyDbContext.SaveChanges();
//var result = this.checklistTaskTestHelper.checklistTaskDefinitionRepository.GetTaskDefinitionsForEdit(ChecklistReferenceType.ReconAccountGroup, "Xxx123");
var result = this.checklistTaskDefinitionRepository.GetTaskDefinitionsForEdit(ChecklistReferenceType.ReconAccountGroup, "Xxx123");
Assert.AreEqual(1, result.Count);
//Assert.AreEqual("Xxx123", result[0].ReferenceKey);
//Assert.AreEqual("SomeDescription", result[0].Description);
}
I also have an initilize method:
protected override void Initialize()
{
this.company = this.CreateCompany("Test company");
this.checklistTaskDefinitionRepository = this.CreateRepository<ChecklistTaskDefinitionRepository>(this.company);
this.helper = new ChecklistTaskTestHelper(this.checklistTaskDefinitionRepository, this.checklistTaskStatusRepository);
}
And these at the start of the class:
private Company company;
private ChecklistTaskDefinitionRepository checklistTaskDefinitionRepository;
private ChecklistTaskStatusRepository checklistTaskStatusRepository;
private ChecklistTaskTestHelper helper;
And as soon as I run the test method, It prints out this:
Test method Core.Data.Test.Modules.Checklists.ChecklistTaskDefinitionRepositoryTest.GetTaskDefinitionsForEdit_HavingTaskDefinitions_ReturnsChecklistTaskDefinitions threw exception:
System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries.
If you debug the test, you can retrieve the inner exception that in this case will give you the reason of the error (fk error, duplicated pk error, column does not exists, table does not exists, database does not exists).
To debug the test inside visual studio, right click on the test and click debug.

Invalid Operation Exception in C# Unit Test using Protractor

I have a simple test class like this:
public class MyTest
{
const string URL = "https://example.com/content/mypage.aspx";
IWebDriver driver;
NgWebDriver ngDriver;
[SetUp]
public void Setup()
{
driver = new ChromeDriver();
driver.Manage().Timeouts().SetScriptTimeout(TimeSpan.FromSeconds(10));
ngDriver = new NgWebDriver(driver);
}
[TearDown]
public void Teardown()
{
ngDriver.Quit();
}
[Test]
public void Basic()
{
ngDriver.Url = URL;
Assert.IsTrue(ngDriver.FindElement(By.CssSelector("#my")).Displayed);
}
}
and here's the HTML snippet:
<kendo-button id="my" ng-click="myCtrl.doSomething()">Do Something</kendo-button>
I'm getting the following error on the Assert.IsTrue line:
javascript error: [ng:test] http://errors.angularjs.org/1.3.15/ng/test
JavaScript stack:
Error: [ng:test] http://errors.angularjs.org/1.3.15/ng/test
at Error (native)
at https://example.com/AngularJS/1.3.15/angular.min.js:6:417
at Object.Ld [as getTestability] (https://example.com/AngularJS/1.3.15/angular.min.js:18:468)
at eval (eval at executeAsyncScript (unknown source), <anonymous>:10:13)
at eval (eval at executeAsyncScript (unknown source), <anonymous>:18:5)
at executeAsyncScript (<anonymous>:329:26)
at <anonymous>:345:29
at callFunction (<anonymous>:237:33)
at <anonymous>:247:23
at <anonymous>:248:3
(Session info: chrome=49.0.2623.87)
(Driver info: chromedriver=2.21.371459 (36d3d07f660ff2bc1bf28a75d1cdabed0983e7c4),platform=Windows NT 6.1 SP1 x86_64) (UnexpectedJavaScriptError)
and the stack trace is:
at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScriptCommand(String script, String commandName, Object[] args)
at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteAsyncScript(String script, Object[] args)
at Protractor.NgWebDriver.WaitForAngular() in c:\Users\Bruno\Projets\GitHub\bbaia\protractor-net\src\Protractor\NgWebDriver.cs:line 315
at Protractor.NgWebDriver.FindElement(By by) in c:\Users\Bruno\Projets\GitHub\bbaia\protractor-net\src\Protractor\NgWebDriver.cs:line 262
I only got the Protractor and Selenium WebDriver Nuget package. Is there something else I need to install or this is actually a code problem?
You're not actually navigating to the URL before the Assert?
Try -
[Test]
public void Basic()
{
NgDriver.Navigate().GoToUrl(URL);
Assert.IsTrue(ngDriver.FindElement(By.CssSelector("#my")).Displayed);
}
Building on what I shared below, I found that my problem was not specifying the root to the document. In my tag, I had
data-ng-app='myApp'
The code to create my protractor driver was:
ngDriver = new NgWebDriver(driver, "[ng-data='myApp']"
Protractor-net doesn't modify this direct CSS search criteria, so what worked was:
ngDriver = new NgWebDriver(driver, "[data-ng-app='myApp']"
Not an answer, but I don't have the ability to comment.
I'm seeing the same issue. Further investigation reveals that there is an exception being thrown when the NgWebDriver is instantiated. Inspecting the object shows the Location, PageSource, Title and Url members of the object created all "threw an exception of type 'System.InvalidOperationException' string {System.InvalidOperationException}". The exception only gets thrown up to the test when attempting to find an element.
My code looks like:
public DefaultPOM(IWebDriver webDriver, string baseURL)
{
driver = webDriver;
this.baseURL = baseURL;
driver.Manage().Timeouts().SetScriptTimeout(TimeSpan.FromSeconds(10));
driver.Navigate().GoToUrl(baseURL);
ngDriver = new NgWebDriver(driver, "[ng-app='myApp']");
ngDriver.Manage().Window.Maximize();
ngDriver.Navigate().GoToUrl(baseURL);
}
The inspecting the ngDriver object right after it is created shows the exceptions.
If I turn off synchronization before navigating, the only member of the driver object recording the exception is the Location.
ngDriver = new NgWebDriver(driver, "[ng-app='NCTWebPortal']");
ngDriver.IgnoreSynchronization=true;
ngDriver.Manage().Window.Maximize();
ngDriver.Navigate().GoToUrl(baseURL);
ngDriver.IgnoreSynchronization = false;

Using wait.until throws System.InvalidOperationException: No session ID specified

I have many test cases, where I need to wait until the page is loaded. I'm using explicit wait as the load times vary.
WebDriverWait _wait = new WebDriverWait(Drivers._driverInstance, new TimeSpan(0, 2, 0));
_wait.Until(D => D.Title);
It throws No session ID exception. I have a table that takes time to load in the page, so I tried using
_wait.Until(ExpectedConditions.ElementIsVisible(By.TagName("table")));
Even this throws the same error. The tests pass when I run each one individually and running all of them as suite raises this exception.
private static void InitialUpload(string filename)
{
SDDirectPage.filePath = filename;
SDDirectPage.filename = Path.GetFileNameWithoutExtension(SDDirectPage.filePath);
SDDirectPage.UploadButton.Click();
Drivers._driverInstance.SwitchTo();
SDDirectPage.FileReference = SDDirectPage.filename;
SDDirectPage.UploadTheFile();
//Check whether 404 occurred or the uploading file is smooth
if (Drivers._driverInstance.Title == "404 - File or directory not found.") //A bug at the moment, it uploads corrupted files most of the times.
{
Assert.Fail("404 error occurred. File might be corrupted or file mightnot be in the specified location..!");
return;
}
else
{
Drivers._driverInstance.SwitchTo().ParentFrame();
// SDDirectPage._wait.Until(D => D.Title);
SDDirectPage._wait.Until(ExpectedConditions.ElementIsVisible(By.TagName("table")));
Assert.AreEqual(SDDirectPage.filename + " - SmartDebit Front End Portal", Drivers._driverInstance.Title);
}
}
This is the function where I'm getting the exception. In some test cases, I have Assert.AreEqual, where I compare the titles. In those test cases, driver.Title raises the same error.
Here is the exception:
Test FullName: SDTestAutomation.SDDirectPage_Tests.FixInvalidRows_Search
Test Source: c:\Git\AutomationTest\automationtest\AutomationTest\SDTestAutomation\SDDirectPage_Tests.cs : line 249
Test Outcome: Failed
Test Duration: 0:02:19.2199494
Result Message:
Test method SDTestAutomation.SDDirectPage_Tests.FixInvalidRows_Search threw exception:
System.InvalidOperationException: No session ID specified
Result StackTrace:
at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(String mechanism, String value)
at OpenQA.Selenium.Remote.RemoteWebDriver.FindElementByTagName(String tagName)
at OpenQA.Selenium.By.<>c__DisplayClass1a.<TagName>b__18(ISearchContext context)
at OpenQA.Selenium.By.FindElement(ISearchContext context)
at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(By by)
at OpenQA.Selenium.Support.UI.ExpectedConditions.<>c__DisplayClass13.<ElementIsVisible>b__12(IWebDriver driver)
at OpenQA.Selenium.Support.UI.DefaultWait`1.Until[TResult](Func`2 condition)
at SDTestAutomation.SDDirectPage_Tests.InitialUpload(String filename) in c:\Git\AutomationTest\automationtest\AutomationTest\SDTestAutomation\SDDirectPage_Tests.cs:line 483
at SDTestAutomation.SDDirectPage_Tests.FixInvalidRows_Search() in c:\Git\AutomationTest\automationtest\AutomationTest\SDTestAutomation\SDDirectPage_Tests.cs:line 250
Here is the drivers class:
public class Drivers
{
static string path = #"C:\SmartDebit\SmartDebitTestAutomation\SmartDebitFramework\DriverResources\";
public static IWebDriver _driverInstance { get; set; }
public static void Initialize(string browser)
{
if (browser == "FF")
{
_driverInstance = new FirefoxDriver();
_driverInstance.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5000));
}
if (browser == "IE")
{
_driverInstance = new InternetExplorerDriver(path);
_driverInstance.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5000));
}
if (browser == "Chrome")
{
_driverInstance = new ChromeDriver(path);
_driverInstance.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5000));
}
}
}
Code for initialising the browser instance:
[ClassInitialize]
public static void BrowserInstance(TestContext t)
{
loginPage = new LoginPage();
loginPage.Init("FF");
loginPage.Goto("url of the application");
Assert.AreEqual("Login Page", Drivers._driverInstance.Title, "Login page titles doesn't match");
}
[TestInitialize]
public void Init()
{
try
{
Login();
}
catch (Exception ex)
{
Console.WriteLine("Exception:" + ex);
Assert.Fail("ValidLogin() test failed in HomePage_Tests.cs");
loginPage.QuitBrowser();
}
}
private static void Login()
{
loginPage.LoginName = "username";
loginPage.Password = "password";
loginPage.LoginButton();
SDDirectPage._wait.Until(d=>Drivers._driverInstance.Title);
Assert.AreEqual("Home Page - Front End Portal", Drivers._driverInstance.Title, "Home page title doesn't match");
Assert.IsTrue(HomePage.loggedInUserText.Contains("username"));
}
I'm using Firefox 43.0.2
Could someone help be to overcome this situation.
Thanks.
System.InvalidOperationException: No session ID specified occurs when you don't have valid driver instance in the method.
Please check Drivers._driverInstance is properly instantiated in your code. If possible post the Drivers class' relevant portions in the question.
Refer another SO question where the same problem is discussed: Disabling browser javascript with Selenium webdriver + specflow + c# + Pageobject + pagefactory
I am basically from Java, but observing the code and exception, i am excepting WebDriverWait is defined in SDDirectPage and calling here.right?
SDDirectPage._wait.Until(ExpectedConditions.ElementIsVisible(By.TagName("table")));
When you are calling defined wait method, you are not passing webdriver instance here. So i am expecting on switching to this method driver loosing the session. For sake of confirm, can you try executing the same by commenting this wait line (and my use something equivalent to Thread.sleep(5000) in Java for once to check this issue)
Thanks

Get Method, Class and LineNumber from StatckTrace in Application_UnhandledException event

I am developing Windows Phone 7 Silverlight Application. I want to do Application Level error handling instead of writing try...catch... in all methods. I need to extract Method Name, Class Name and Line Number where the actual error occurred. Below is the demo code. In Application_UnhandledException event, I am expecting Method = "GenerateError" and Class = "ExceptionTesting". Also, I want to get LineNumber where the actual error occurred (this is not shown in code).
Code to generate Error:
public partial class ExceptionTesting : PhoneApplicationPage
{
// Generate Error to Test Exception Handling
private void GenerateError()
{
Int16 i = Convert.ToInt16("test");
}
}
Code that Handles Application Level Exception:
// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
StackTrace st = new StackTrace();
var query = st.GetFrames() // get the frames
.Select(frame => new
{
Method = frame.GetMethod(),
Class = frame.GetMethod().DeclaringType
});
foreach (var q in query)
{
if (q.Method.Name.Contains("GenerateError"))
{
MessageBox.Show("Class: " + q.Class + ", Method: " + q.Method);
}
}
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
The Application_UnhandledException method is not called from your method where the exception happens, so new StrackTrace() will not be meaningful, as you have discovered.
To get the stack trace for the place where the exception occurred, use e.Exception.StackTrace.
Note that the real exception may be wrapped inside another exception, possibly several layers deep (e.Exception.InnerException).
You could also use BugSense to get this information.
Disclaimer: I am one of the cofounders

Categories

Resources