I am working on a test framework which is using Serenity, Selenium and jUnit. I have some tests which depend on user authentication. Basically I have to repeat all login steps for each test. I wanted to move these steps to a #Before method, but it seems that Steps are not being initialized in a method which is not annotated as #Test... See the code snippet below, AuthSteps instance is not being initialized.
Which are my options?
#RunWith(SerenityRunner.class)
public class MyTests extends AbstractTest {
#Managed(driver = "firefox", uniqueSession = false)
#Steps
AuthSteps auth;
#Before
public void authSetup() {
if (!authenticated){
auth.login();
//a lot of other things
}
}
#Test
public void mytest(){
//do test related stuff
}
They do. Steps will run with either #BeforeClass, #Before, #Test and so on. It seems that your if (!authenticated) statement might be excluding execution of your auth.login() step.
There's certainly not enough code provided here (like what is boolean authenticated)to clearly examine your issue, but I hope this answer helps you.
Related
I have been on a search recently for an answer to my question and I cannot seem to find it. I am trying to execute a simple test to run a JUnit test in static. When I try to execute the test I receive the following Failure.
java.lang.Exception: Method SimpleINt()should not be static.
I have JUnit 4 and hamcrest installed and pathsbuilt.
(I am still new to Selenium/Java so I am sure there is an easy explanation for this.)
package iMAP;
import org.junit.Test;
public class Test1 {
#Test
public static void SimpleINt ()
{
int i = 34;
System.out.println(i);
}
}
The JUnit documentation for #Test states:
The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case. To run the method, JUnit first constructs a fresh instance of the class then invokes the annotated method. Any exceptions thrown by the test will be reported by JUnit as a failure.
So, what is implicitly said here: the expectation is that #Test is only used for non static methods.
Beyond that: don't use keywords because you can. Learn what they mean. And static is something that you rather avoid (instead of using it all over the place).
Junit Methods should not be static as much I read and study. Just delete Static and try this:
package iMAP;
import org.junit.Test;
public class Test1 {
#Test
public void SimpleINt ()
{
int i = 34;
System.out.println(i);
}
}
Is there a Assert class present in Selenium C# just like we have in Coded UI test.
Or I should use the Microsoft.VisualStudio.TestTools.UnitTesting.Assert class to perform asserts in Selenium?
Yes, you would use the Assert class in your unit test framework, in your case MSTest.
The Selenium library doesn't have responsibility over test framework type of functions, including asserts.
You can use FluentAssertions which supports many different frameworks including MSTest which might minimize changes needed if you need to switch frameworks for any reason.
The Assert class is available with either the MSTest or NUnit framework.
I used NUnit, and there is the Assert class as in below line of code.
Sample code:
Assert.AreEqual(AmericaEmail, "SupportUsa#Mail.com", "Strings are not matching");
According to https://msdn.microsoft.com/en-us/library/ms182532.aspx
[TestClass]
public class UnitTest1
{
private IWebDriver driver;
[TestInitialize]
public void Setup()
{
driver = new ChromeDriver();
driver.Url = "Your URL";
}
[TestMethod]
public void TestMethod1()
{
//Your first test method
var element = driver.FindElement(By.Id("ID"));
Assert.IsTrue(element.Displayed);
Assert.AreEqual(element.Text.ToLower(), "Expected text".ToLower());
}
[TestMethod]
public void TestMethod2()
{
//Your second test method
}
[TestCleanup]
public void TearDown()
{
driver.Quit();
}
}
You can use MSTest or I would rather prefer to write simple assertion method. In Selenium, most of the use cases would be a Boolean check, IsTrue | IsFalse (you can even extend to write more complex assertions), so when you define your own assertion you will get more control of your script, like,
Taking a screenshot if the assertion fails
You can live with the failure and continue the test
You can mark the script as partially passing
Extract more information from the UI, like JavaScript errors or server errors
To use Assert you have to first create the unit testing project in Visual Studio.
Or import the following reference to the project.
using Microsoft.VisualStudio.TestTools.UnitTesting;
// Using this you can use the Assert class.
Assert.IsTrue(bool);
Assert.IsFalse(bool);
Assert.AreEqual(string,string);
Assert.Equals(obj1, obj2); // Object comparison
Assert.AreEqual(HomeUrl, driver.Url); // Overloaded, comparison. Same object value
Assert.AreNotEqual(HomeUrl, driver.Url);
Assert.AreSame("https://www.google.com", URL); // For the same object reference
Assert.IsTrue(driver.WindowHandles.Count.Equals(2));
Assert.IsFalse(driver.WindowHandles.Count.Equals(2));
Assert.IsNull(URL); Assert.IsNotNull(URL);
Selenium C# is not offering an assert class. You have to borrow it from somewhere or write your own implementation.
Writing your own implementation will give you more freedom to manage assertions, as Peter said.
Here is the basic idea. Just create a static class having assert methods like this:
public static class MyAssertClass
{
public static void MyAreEqualMethod(string string1, string string2)
{
if (string1 != string2)
{
// Throw an exception
}
}
}
MSTest Framework : Assert Class
https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.testtools.unittesting.assert?view=mstest-net-1.3.2
This way assert can be used for switching into popup's displayed:
IAlert alert = driver.SwitchTo().Alert();
String alertcontent = alert.Text;
Assert.AreEqual(alertcontent, "Do you want to save this article as draft?");
obj.waitfn(5000);
alert.Accept();
I have 2 test classes one is for testing the register functionality of a website and another is for login.
public class TestResister{
#test
public void testSignup(){
}
}
public class TestLogin{
#test
public void testLoginUser(){
}
}
I want that when i run testLoginUser() function it automatically call testSignup().
Yes it is possible. Something like the following:
#Test(priority = 1)
public void testMethod1(){
//some code
}
#Test(priority = 2)
public void testMethod2(){
//some code
}
See this. Lower priority will execute first. However, any any condition, ***Test dependency* is not best practice. Each and every test should be designed to perform independently. Think about what will happen to test with priority 2 if test with priority 1 fails.
Not sure if I understand your problem correct, but you just need to call the method.
public class TestRegister{
public void testSignup(){
}
}
public class TestLogin{
public void testLoginUser(){
TestRegister.testSignup();
}
}
Or
public class TestLogin{
public void testLoginUser(){
TestRegister tstregister = new TestRegister();
tstregister.testSignup();
}
}
Your question is not very clear, what if the registration is already done? will it fail ?
I think you are looking for the following attribute.
You can use the attributes dependsOnMethods or dependsOnGroups, found on the #Test annotation.
There are two kinds of dependencies:
Hard dependencies. All the methods you depend on must have run and
succeeded for you to run. If at least one failure occurred in your
dependencies, you will not be invoked and marked as a SKIP in the
report.
Soft dependencies. You will always be run after the methods you
depend on, even if some of them have failed. This is useful when you
just want to make sure that your test methods are run in a certain
order but their success doesn't really depend on the success of
others. A soft dependency is obtained by adding "alwaysRun=true" in
your #Test annotation.
Here is an example of a hard dependency:
#Test
public void signup() {}
#Test(dependsOnMethods = { "singup" })
public void login() {}
In this case if singup fails login wont run. If you want to still run login then add "alwaysRun=true". Then login will run irrespective of signup is successful or not.
For more please look up http://testng.org/doc/documentation-main.html
I am trying to integrate TestLink with TestNG
Approach is below
1>Write ITestListner with onTestFailure and onTestSuccess
2> get Annotation of the method(like testName which will be equivalent to test name in testlink) which is being failed/success in a variable
3>Make connection with TestLink using API available and update the test case.
However I am struggling to find method Annotation value in ITestListner and requirement is to get annotation values in ITestListner only so that correct test cases can be updated in Test_link
Can someone please help me how to get Test Method annotation value in ITestListner or any other approach in which i can integrate testlink update with TestNG
Hi Thanks niharika for help
,First of all you are correct in explaining use of TestNG but we are using TestNG for Selenium and already there are around 1000 test cases writen in test Methods and we have to live with that
Some how i have figured the solution ,we can still get the testName of the test method using two listners
This is just work around I am not sure if this is the best approach but as of now solving my purpose
package com.automation.testng.listner;
import org.testng.*;
public class MyIInvokeMethodListner_TestName_TestLink implements IInvokedMethodListener {
public static String testName;
public void afterInvocation(IInvokedMethod arg0, ITestResult arg1) {
// TODO Auto-generated method stub
}
public void beforeInvocation(IInvokedMethod m, ITestResult tr) {
// TODO Auto-generated method stub
//This give the Annotation Test object
org.testng.annotations.Test t=m.getTestMethod().getMethod().getAnnotation(org.testng.annotations.Test.class);
MyIInvokeMethodListner_TestName_TestLink.testName = t.testName().toString();
}
}
MyITestListner goes like below
package com.automation.testng.listner;
import org.testng.*;
public class MyITestListner_TestLink extends TestListenerAdapter {
/*IAnnotationTransformer at;
public Listner_1()
{
this.at = new Annotation_listner();
}*/
#Override
public void onTestFailure(ITestResult tr)
{
System.out.println("Hurray !I am being inboked from Test listner");
MyIInvokeMethodListner_TestName_TestLink a = new MyIInvokeMethodListner_TestName_TestLink();
System.out.println(MyIInvokeMethodListner_TestName_TestLink.testName);
}
public void onTestSuccess(ITestResult tr)
{
MyIInvokeMethodListner_TestName_TestLink a = new MyIInvokeMethodListner_TestName_TestLink();
System.out.println(MyIInvokeMethodListner_TestName_TestLink.testName);
}
}
Basically we are getting the method and then using Test Annotation class setting the static variable which can be used in MyITestListner
The ITestListener is the one which is used after <test> tag. For getting the method name and annotation specifics, you need to implement IInvokedMethodListener and in the after/before methods of this interface, and use something like method.getTestMethod().getMethodName() to get the executing method name.
If you are adding testName at the method level, I think you are doing it wrong since the help of testng mentions this "The name of the test this test class should be placed in. This attribute is ignore if #Test is not at the class level."
If you are indeed specifying the #Test at your class level then you can get it as below :
method.getTestMethod().getTestClass().getTestName()
A bit ugly and you probably want to wrap those parts in null checks in your code but this is how you get the testName specified in the annotation from the ITestResult:
iTestResult.getMethod().getConstructorOrMethod().getMethod().getAnnotation(Test.class).testName()
I have a code like this:
public class MyTest extends TestCase {
private MyObject mObject1;
private MyObject mObject2;
...
#Override
public void setUp() throws Exception {
super.setUp();
}
public void testSomething() {
mObject1 = new MyObject();
mObject2 = new MyObject();
}
public void testSomething2() {
// Here I can't access the previously created objects mObject1 and
// mObject2, because they are again null.
// Why is that, if *my* setUp() method doesn't touch them?
}
My guess is that JUnit instantiates the class again every time. Can someone please explain me the workflow?
Thanks.
JUnit will instantiate the class (MyTest) once per test and then execute the methods
setUp()
testXXX()
tearDown()
until it runs all the methods that start with test and don't receive any parameters. So in your example, Junit will instantiate MyTest twice. You can read more about this in the JUnit documentation.
Bear in mind that this is the old way of writing tests. From Junit 4 (I think) the preferred way is to use annotations. You can check the annotations documentation here.
As a side note, NUnit, reuses the instance of the test, so in the same scenario, it would only instantiate MyTest once.
JUnit will instantiate this class once per test method, so only once in the code above, but try it again with two test methods and you will see it instantiated twice. If you want to save some state in fields without having to use statics, take a look at TestNG, which reuses the same instance for all test methods.