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.
Related
I am trying to run several unit tests (by pressing Run All in Visual Studio). When I run all using Test>Run>All Tests the test below fails, but when I run the individual test (by right clicking the test itself in test Explorer) it succeeds. I believe I have my Setup and TearDown configured wrong, but I'm not sure whats missing.
Error:
Message: System.ArgumentException : An item with the same key has already been added. Key: System.Object[]
My Code:
[TestFixture]
public class GCLandingUserModelTest
{
DbContextOptions<GreenCardContext> gcopt = new DbContextOptionsBuilder<GreenCardContext>()
.UseInMemoryDatabase(databaseName: "GreenCardSite").Options;
private GreenCardContext _mockGC;
[SetUp]
public void InitData()
{
_mockGC = new GreenCardContext(gcopt);
}
[TearDown]
public void ClearData()
{
_mockGC = null;
}
[Test]
public void TestAddObjMoq()
{
// Insert seed data into the database using one instance of the context
_mockGC.UserRolePrice.Add(new UserRolePrice { LGID = 1, UserRoleId = -1 });
_mockGC.SaveChanges();
Assert.AreEqual(1, _mockGC.UserRolePrice.ToList().Count, $"UserRolePrice not added to context");
//verify that obj created and changes were saved on the Mock Context
int objlgid = _mockGC.UserRolePrice.Where(x => x.UserRoleId == -1).Select(x => x.LGID).First();
Assert.AreEqual(1, objlgid,$"The returned lgid was: {objlgid}");
}
}
Maybe you need to clear the in-memory datastore.
_mockGC.Database.EnsureDeleted();
DatabaseFacade.EnsureDeleted Method
Ensures that the database for the context does not exist. If it does
not exist, no action is taken. If it does exist then the database is
deleted.
Warning: The entire database is deleted, and no effort is made to
remove just the database objects that are used by the model for this
context.
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.
I've created a new test project in a pre-existing Visual Studio solution and attempting to mock a controller so I can test routing. The main project makes use of Combres for minification of css etc. To better demonstrate the problem I've put the .AddCombresRoute into the test which generates the error I'm trying to solve.
private HttpContextBase rmContext;
private HttpRequestBase rmRequest;
[TestInitialize]
public void SetupTests()
{
// Setup Rhino Mocks
rmContext = MockRepository.GenerateMock<HttpContextBase>();
rmRequest = MockRepository.GenerateMock<HttpRequestBase>();
rmContext.Stub(x => x.Request).Return(rmRequest);
}
[TestMethod]
public void RhinoMocksRoutingTest()
{
// Arrange
RouteCollection routes = new RouteCollection();
RouteConfig.RegisterRoutes(routes);
rmRequest.Stub(e => e.AppRelativeCurrentExecutionFilePath).Return("~/Home/Index");
// Act
routes.AddCombresRoute("Combres Route"); *** ERRROR HERE ***
RouteData routeData = routes.GetRouteData(rmContext);
// Assert
Assert.IsNotNull(routeData);
Assert.AreEqual("Home",routeData.Values["controller"]);
Assert.AreEqual("Index",routeData.Values["action"]);
}
Despite making the correct references, ensuring combres.xml and combres.xsd are in App_Data (and copied to local) and dropping in the relevant entries into app.config I get the following error when I run the test:
ArgumentNullException was unhandled by user code. An exception of type
'System.ArgumentNullException' occurred in System.Xml.dll was not
handled in user code. Additional information: Value cannot be null.
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
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