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
Related
I am currently using the ExtentReport framework to generate a comprehensive test report after TestNG completes its suite of test class using Selenium.
To make the process easier and to reduce code, I am using a listener class to automate the Test Success and Test Failure scenerios such that in case of every success/failure, there will some actions done to the report automatically. The listener implementation goes like this:
public class Listeners extends Base implements ITestListener{
ExtentTest test;
ExtentReports extent=ExtentReporterNG.getReportObject();
**ThreadLocal**<ExtentTest> extentTest =new **ThreadLocal**<ExtentTest>();
public void onTestStart(ITestResult result) {
// TODO Auto-generated method stub
test= extent.createTest(result.getMethod().getMethodName());
extentTest.set(test);
}
public void onTestSuccess(ITestResult result) {
takeScreenShotandAttachtoReport();
extentTest().get().log("Success");
}
public void onTestFailure(ITestResult result) {
takeScreenShotandAttachtoReport();
extentTest().get().log("Failure");
}
public void onFinish(ITestContext context) {
// TODO Auto-generated method stub
extent.flush();
}
As above, with every test case, an ExtentTest ThreadLocal would be instantiated along the interface methods, which would execute with respect to their individual listeners based on the test results. This reduces the extra code that are needed for the same implementation if ExtentReport was to be instantiated on every test class. However, this implementation has its own hurdle: It would not allow variations (logging, individual test result customization, etc). Say I'd want some ExtentReport logging to be done for each unique test case, I have no ways to invoke the listener and do any type of logging for that particular test.
Is there anyway that this can be solved?
I have a test class that has several tests. At the moment I have this to start up the server, wipe the database etc:
#ClassRule
public static final DropwizardAppRule<ServiceConfig> RULE =
new DropwizardAppRule<ServiceConfig>(ServiceApp.class, ResourceHelpers.resourceFilePath("config.yml"));
All my tests work with this individually. But when I run them all together some fail since other tests modify data. I tried doing the following but I'm getting null pointers when calling RULE.getPort():
#ClassRule
public static DropwizardAppRule<ServiceConfig> RULE;
#Before
public void beforeClass() {
RULE = new DropwizardAppRule<ServiceConfig>(ServiceApp.class, ResourceHelpers.resourceFilePath("config.yml"));
}
I would have expected this to work but it doesn't seem to set the values of RULE properly. Any ideas?
Hi,
I don't know how to handle db "from within" DropwizardAppRule, so I may not really answer your question... I'm actually having another issue myself trying with DropwizardAppRule not properly being setup and torn down between tests. (So if you made progress going this way I'd like you insights).
Anyway, I think you need to handle your DB outside DropwizardAppRule and give it in the Rule. We resolved DB clearing by relying on custom and external TestsRules:
public class CockpitApplicationRule implements TestRule {
public static class App extends CockpitApplication<CockpitConfiguration> {
// only needed because of generics
}
public final DropwizardAppRule<CockpitConfiguration> dw;
public final EmbeddedDatabaseRule db;
public CockpitApplicationRule(String config, ConfigOverride... configOverrides) {
this.db = EmbeddedDatabaseRule.builder()
.initializedByPlugin(LiquibaseInitializer.builder().withChangelogResource("migrations.xml").build())
.build();
this.dw = new DropwizardAppRule<>(App.class, ResourceHelpers.resourceFilePath(config),
ConfigOverride.config("database.url", () -> this.db.getConnectionJdbcUrl()));
}
#Override
#Nullable
public Statement apply(#Nullable Statement base, #Nullable Description description) {
assert base != null;
assert description != null;
return RulesHelper.chain(base, description, dw, RulesHelper.dropDbAfter(db), db);
}
public DSLContext db() {
return DSL.using(db.getConnectionJdbcUrl());
}
}
Basically we override TestRule apply(...) to chain custom Statements. There's our RulesHelper if you want to take a look. That way the DB is cleanly handled by the Rules, we can fill our test DB in test classes using #Before setup methods.
org.zapodot.junit.db.EmbeddedDatabaseRule Is an external dependency that allows us to rather easily instantiate a DB for our tests.
The RulesHelper.dropDbAfter does the actual cleaning:
public static TestRule dropDbAfter(EmbeddedDatabaseRule db) {
return after(() -> DSL.using(db.getConnectionJdbcUrl()).execute("DROP ALL OBJECTS"));
}
You should be able to setup and clean the DB from #Before and #After methods without fully using TestRules though, but I'm not sure it's really easier in the end.
Hope this helped !
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.
What I have to do:
I have to test my spring mvc with JMockit. I need to do two things:
Redefine MyService.doService method
Check how many times redefined MyService.doService method is called
What the problem:
To cope with the first item, I should use MockUp; to cope with the second item I should use #Mocked MyService. As I understand this two approaches are overriding each other.
My questions:
How to override MyService.doService method and simultaneously check how many times it was invoked?
Is it possible to avoid mixing a behaviour & state based testing approaches in my case?
My code:
#WebAppConfiguration
#ContextConfiguration(locations = "classpath:ctx/persistenceContextTest.xml")
#RunWith(SpringJUnit4ClassRunner.class)
public class MyControllerTest extends AbstractContextControllerTests {
private MockMvc mockMvc;
#Autowired
protected WebApplicationContext wac;
#Mocked()
private MyServiceImpl myServiceMock;
#BeforeClass
public static void beforeClass() {
new MockUp<MyServiceImpl>() {
#SuppressWarnings("unused")
#Mock
public List<Object> doService() {
return null;
}
};
}
#Before
public void setUp() throws Exception {
this.mockMvc = webAppContextSetup(this.wac).build();
}
#Test
public void sendRedirect() throws Exception {
mockMvc.perform(get("/doService.html"))
.andExpect(model().attribute("positions", null));
new Verifications() {
{
myServiceMock.doService();
times = 1;
}
};
}
}
I don't know what gave you the impression that you "should use" MockUp for something, while using #Mocked for something else in the same test.
In fact, you can use either one of these two APIs, since they are both very capable. Normally, though, only one or the other is used in a given test (or test class), not both.
To verify how many invocations occurred to a given mocked method, you can use the "invocations/minInvocations/maxInvocations" attributes of the #Mock annotation when using a MockUp; or the "times/minTimes/maxTimes" fields when using #Mocked. Choose whichever one best satisfies your needs and testing style. For example tests, check out the JMockit documentation.
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()