I got Initialization error in Cucumber with maven and selenium - maven

Test Runner
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(features="features",glue={"stepDefinition"})
public class TestRunner {
}
MyApplication.feature
Feature: Test test smoke scenario
Scenario Outline: Test login with valid credentials
Given open fireFox and start application
When I enter valid "username" and valid "password"
Then User should be able to login successfully
Examples:
| username | password |
| 9739817000 | mnbvcxz |
| 9739817001 | mnbvcxz1 |
| 9739817002 | mnbvcxz2 |
Maven POM
<groupId>demo</groupId>
<artifactId>prac</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>prac</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.53.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.2.4</version>
</dependency>
</dependencies>
</project>
Smoke.java
public class Smoke {
WebDriver driver;
#Given("^open fireFox and start application$")
public void open_fireFox_and_start_application() throws Throwable {
driver=new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://testweb.com");
}
#When("^I click on Login$")
public void I_click_on_Login() throws Throwable {
driver.findElement(By.xpath("//a[contains(.,'Login')]")).click();
}
#When("^enter valid \"([^\"]*)\" and valid \"([^\"]*)\"$")
public void enter_valid_and_valid(String un, String pwd) throws Throwable {
driver.findElement(By.id("Username")).sendKeys(un);
driver.findElement(By.id("Password")).sendKeys(pwd);
}
#Then("^Click on Login$")
public void Click_on_Login() throws Throwable {
driver.findElement(By.id("loginUser")).click();
}
#Then("^User should be able to login successfully$")
public void User_should_be_able_to_login_successfully() throws Throwable {
}
These above are the test runner,feature file,Smoke test class.
Its throwing an Initilization error.I am new to Cucumber and recheck all the maven dependency ,its correct only.But even also its giving error
enter image description here

As, you have not specified any sets of data for your feature file, you do not need to use Scenario Outline. You can use it when you need to execute same scenario with different sets of data. Hence, remove Scenario Outline from your feature file (shown below the updated feature file) and retry:
Feature: Test Milacron smoke scenario
Scenario: Test login with valid credentials
Given open fireFox and start application
When I enter valid "username" and valid "password"
Then User should be able to login successfully
Please refer to link for more details about writing feature files. Let me know, if you have any further queries.

Scenario Outline is used to pass different sets of input data to your scenario. For instance 'ABC' and 'PWD' are your username, password respectively then update your feature file as below,
Feature: Test Milacron smoke scenario
Scenario Outline: Test login with valid credentials
Given open fireFox and start application
When I enter valid "username" and valid "password"
Then User should be able to login successfully
Examples:
| username | password |
| ABC | PWD |

What worked for me was to remove the empty feature files (those without any scenarios present) from the features directory.

Your pom file is absolutely fine.
Here you are using Scenario Outline if you are using Scenario outline there should be Examples annotation in the feature file. Anyways your test scenario can be achieved without using scenario outline
Update feature file and java file with below code:
Myapplication.feature:
Feature: Test test smoke scenario
Scenario: Test login with valid credentials
Given open fireFox and start application
When I click on Login
When I enter valid "username" and valid "password"
Then I click on Loginbutton
Then User should be able to login successfully
Smoke.java:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class Smoke {
WebDriver driver;
#Given("^open fireFox and start application$")
public void open_fireFox_and_start_application() throws Throwable {
driver=new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://testweb.com");
}
#When("^I click on Login$")
public void I_click_on_Login() throws Throwable {
driver.findElement(By.xpath("//a[contains(.,'Login')]")).click();
}
#When("^I enter valid \"([^\"]*)\" and valid \"([^\"]*)\"$")
public void i_enter_valid_and_valid(String arg1, String arg2) throws Throwable {
driver.findElement(By.id("Username")).sendKeys(arg1);
driver.findElement(By.id("Password")).sendKeys(arg2);
}
#Then("^I click on Loginbutton$")
public void Click_on_Login() throws Throwable {
driver.findElement(By.id("loginUser")).click();
}
#Then("^User should be able to login successfully$")
public void User_should_be_able_to_login_successfully() throws Throwable {
}
}
Maintain Folder structure as mentioned in the attached image
If you want to use scenario outline update feature file like below
Same smoke.java file will works in this case.
Feature: Test test smoke scenario
Scenario Outline: Test login with valid credentials
Given open fireFox and start application
When I click on Login
When I enter valid "<username>" and valid "<password>"
Then I click on Loginbutton
Then User should be able to login successfully
Examples:
|username|password|
|test|test|
Let me know if it works for you

Related

Spring boot and Swagger url and startup questions

I come from programming in c# and now I have to create a couple of Rest Apis in Spring Boot.
Everything is working ok and I can show the API in Swagger with springfox-swagger-ui
But I have two questions that I could not find in Internet
Is there any way to show the url ui in the console app with server, port, etc?
Is there any way to open the swagger url everytime I run the app in the localhost?
Thanks
Spring boot version
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
I know it's not the question you're asking, but springfox is currently having issues with newer versions of spring. The spring version you're using is still working but as of 2.6 there are bugs, and it looks like the project is not well maintained. Since you're at the beginning of the project, switching is not too hard. You could move to springdocs for example (for migration: https://springdoc.org/#migrating-from-springfox).
With respect to opening a url, there are some good solutions mentioned here: How to open the default webbrowser using java . You could make your swagger url a property and have swagger configure it accordingly, then you can reuse the property to call the url on run-time. If you want to differentiate between environments I'd suggest use profiles. Only open the url in the browser if you start the app on dev environment, and not on prod is then specified by using #Profile("dev"). Create a commandline/application runner with the profile annotation (https://www.tutorialspoint.com/spring_boot/spring_boot_runners.htm), and call the url from there.
That said, combining it gives:
package com.example.demo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import java.awt.*;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
#Profile("dev")
#Component
public class SwaggerRunner implements ApplicationRunner {
#Value("${springdoc.swagger-ui.path}")
private String swaggerPath;
#Override
public void run(ApplicationArguments args) throws Exception {
log("\nWelcome to Multi Brow Pop.\nThis aims to popup a browsers in multiple operating systems.\nGood luck!\n");
final String swaggerUrl = "http://localhost:8000/" + swaggerPath;
log("We're going to this page: " + swaggerUrl);
String myOS = System.getProperty("os.name").toLowerCase();
log("(Your operating system is: " + myOS + ")\n");
try {
if (Desktop.isDesktopSupported()) { // Probably Windows
log(" -- Going with Desktop.browse ...");
Desktop desktop = Desktop.getDesktop();
desktop.browse(new URI(swaggerUrl));
} else { // Definitely Non-windows
Runtime runtime = Runtime.getRuntime();
if (myOS.contains("mac")) { // Apples
log(" -- Going on Apple with 'open'...");
runtime.exec("open " + swaggerUrl);
} else if (myOS.contains("nix") || myOS.contains("nux")) { // Linux flavours
log(" -- Going on Linux with 'xdg-open'...");
runtime.exec("xdg-open " + swaggerUrl);
} else
log("I was unable/unwilling to launch a browser in your OS :( #SadFace");
}
log("\nThings have finished.\nI hope you're OK.");
} catch (IOException | URISyntaxException eek) {
log("**Stuff wrongly: " + eek.getMessage());
}
}
private static void log(String log) {
System.out.println(log);
}
}
put springdoc.swagger-ui.path=/custom/path in your application.properties to change the path to your swagger-ui

Declarative services in OSGI

I have created a (very) simple test to determine how to send and receive events using Apache Felix.
This is my sender:
package be.pxl;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
import java.util.HashMap;
#Component(name = "be.pxl.Publisher", immediate = true)
public class Publisher {
EventAdmin admin;
#Activate
public void run(Object object) {
System.out.println("IN PUBLISHER");
Event event = new Event("event", new HashMap<String, Object>());
System.out.println("\tEVENT: " + event);
admin.postEvent(event);
System.out.println("\tADMIN: " + admin);
}
#Reference(name="be.pxl.admin", service = EventAdmin.class)
protected void setEventAdmin(EventAdmin admin) {
this.admin = admin;
}
}
This is my receiver:
package be.pxl;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import java.util.Dictionary;
import java.util.Hashtable;
#Component(name = "be.pxl.Subscriber", immediate = true)
public class Subscriber implements EventHandler {
private BundleContext context;
#Activate
public void run(Object object) {
System.out.println("IN SUBSCRIBER");
System.out.println("\tIN RUN METHOD");
String[] topics = new String[]{"event"};
Dictionary props = new Hashtable();
props.put(EventConstants.EVENT_TOPIC, topics);
System.out.println("\t\tCONTEXT: " + context);
context.registerService(EventHandler.class.getName(), this, props);
System.out.println("\t\tCONTEXT AFTER REGISTERSERVICE: " + context);
}
public void handleEvent(Event event) {
System.out.println("IN SUBSCRIBER");
String text = event.getProperty("text").toString();
System.out.println("\tEVENT CALLED: " + text);
}
#Reference(name="be.pxl.context", service=BundleContext.class)
protected void setBundleContex(BundleContext context) {
this.context = context;
}
}
This is the pom of my sender:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>be.pxl</groupId>
<artifactId>EventSender</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.service.event</artifactId>
<version>1.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.core</artifactId>
<version>6.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.service.component.annotations</artifactId>
<version>1.3.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
<version>3.2.100.v20100503</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>2.4.0</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-Vendor>SmartCampus</Bundle-Vendor>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Export-Package>
be.pxl.*;version="1.0.0"
</Export-Package>
<Import-Package>
org.osgi.service.component.annotations
org.eclipse.osgi.service
org.osgi.core
org.osgi.service.event
</Import-Package>
<_dsannotations>*</_dsannotations>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
</project>
Everything compiles fine. I create it using mvn clean package, then I install this jar file in my apache felix container and start it. However, nothing happens. Nothing get pritns out.
Thanks in advance!
You appear to be most of the way there! As you've identified, Event Admin uses a whiteboard model to receive events. The important thing is that you need to tell the whiteboard which topics you want to listen to, which you do.
%%% Update %%%
Event admin topic names use a hierarchy of tokens separated by / characters. When publishing an event you do so to a specific topic, for example foo/bar/baz. When receiving events the EventHandler will be called for topics that match its registered interest(s). These interests can either be for a specific topic, or they can end with a * to indicate a wildcard match. For example foo/bar/* would receive events sent to foo/bar/baz and events sent to foo/bar/fizzbuzz.
%%% Back to the original %%%
There are, however a couple of issues with your code:
Firstly:
#Reference(name="be.pxl.context", service=BundleContext.class)
protected void setBundleContex(BundleContext context) {
this.context = context;
}
This is not how you access the BundleContext for your bundle. If you do need a BundleContext then it should be injected as a parameter into your #Activate annotated method. A BundleContext should never be registered as a service (it represents your bundle's private access to the OSGi framework), and it would not surprise me to find that this reference is unsatisfied in your example. You don't actually need the BundleContext however because...
Secondly:
#Activate
public void run(Object object) {
System.out.println("IN SUBSCRIBER");
System.out.println("\tIN RUN METHOD");
String[] topics = new String[]{"event"};
Dictionary props = new Hashtable();
props.put(EventConstants.EVENT_TOPIC, topics);
System.out.println("\t\tCONTEXT: " + context);
context.registerService(EventHandler.class.getName(), this, props);
System.out.println("\t\tCONTEXT AFTER REGISTERSERVICE: " + context);
}
This is not the right way to write an activate method (and as a result it may not be being called), nor should you be registering your component as a service here. When you make your class an #Component it will automatically be registered as a service using each directly implemented interface. This means that:
#Component(name = "be.pxl.Subscriber", immediate = true)
public class Subscriber implements EventHandler {
...
}
is already an OSGi EventHandler service!
You can add service properties to your component using the #Component annotation, or from the OSGi R7 release (due in a couple of months) using Component Property annotations. In this case you want to set your event.topics property like this:
#Component(property="event.topics=event")
You can then get rid of the activate method completely if you like.
Finally:
Event Admin is not a message queue, and your publisher is a one-shot send. Therefore if your publisher sends the event before the handler is fully registered then it will never receive the event. Consider making the publisher send periodic events, or be certain that the receiver starts before the publisher so that you see the message.
P.S.
It's not technically a problem, but I see that you're using version 2.4 of the maven-bundle-plugin. This is very old and the current released version of bnd is 3.5.0. The Bnd team have also started providing their own Maven plugins (such as the bnd-maven-plugin) that you might want to look at.

WebDriverManager for PhantomJSDriver not working

I cannot get WebDriverManager to work. I would like to use PhantomJSDriver without having to set a system property like this:
System.setProperty("phantomjs.binary.path", "E:/phantomjs-2.1.1-windows/bin/phantomjs.exe");
I have these dependencies in my pom.xml:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>1.5.1</version>
</dependency>
This is my code/test:
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class TestA {
WebDriver driver;
#BeforeClass
public static void setupClass() {
PhantomJsDriverManager.getInstance().setup();
}
#Before
public void setUp() {
driver = new PhantomJSDriver();
}
#Test
public void test() {
driver.get("https://www.google.de/");
System.out.println(driver.getTitle());
assertEquals("Google", driver.getTitle());
}
}
The test fails:
org.junit.ComparisonFailure: expected:<[Google]> but was:<[]>
Does anybody know what I am doing wrong? Thanks in advance!
UPDATE: Now I have another problem. Before using the webdrivermanager I had this:
DesiredCapabilities dc = DesiredCapabilities.phantomjs();
dc.setJavascriptEnabled(true);
dc.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS,
new String[] { "--web-security=no", "--ignore-ssl-errors=yes" });
System.setProperty("phantomjs.binary.path", "E:/phantomjs-2.1.1-windows/bin/phantomjs.exe");
WebDriver driver = new PhantomJSDriver(dc);
Now, when I delete the line with System.setProperty(...), it is not working anymore. Thanks for helping.
Looks like your making the assertion to early, so the page is not loaded when you call getTitle() on it. What does your println print out?
Try adding a wait to to your test, if you know the page title should be "Google" then why not wait for that to be true before doing any further assertions? When the page title is equal to what your expecting you can be reasonably confident the page is loaded. Try this:
public Boolean waitForPageIsLoaded(String title) {
return new WebDriverWait(driver, 10).until(ExpectedConditions.titleIs(title));
}

second scenario in my cucumber feature file is not executing

I'm trying to learn Cucumber with selenium java . have written two scenario's , when i run my feature file which contains two scenarios , only scenario #1 is executing , for scenario #2 its throwing Java null pointer exception
Feature: POC of my framework works
Scenario: Login test
Given I navigate to the Bugzilla website
When I click on login
And I enter the values
Then I check to see if i was successfully loged in or not
Scenario: File a bug test
Given I navigate to the File a bug page
When I click on widgets
And I enter the bug details
Then Bug should be submited succefully
My step definition file :
package cucumber.features;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class StepDefinitions1 {
protected WebDriver driver;
protected String baseUrl;
// Scenario 1
#Given("^I navigate to the Bugzilla website$")
public void I_navigate_to_the_Bugzilla_website() throws Throwable {
driver = new FirefoxDriver();
baseUrl ="https://landfill.bugzilla.org/bugzilla-4.4-branch/index.cgi";
driver.get(baseUrl);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#When("^I click on login$")
public void I_click_on_login() throws Throwable {
driver.findElement(By.id("login_link_top")).click();
}
#And("^I enter the values$")
public void I_enter_the_values() throws Throwable {
driver.findElement(By.id("Bugzilla_login_top")).clear();
driver.findElement(By.id("Bugzilla_login_top")).sendKeys("jeevan.anekal#gmail.com");
driver.findElement(By.id("Bugzilla_password_top")).clear();
driver.findElement(By.id("Bugzilla_password_top")).sendKeys("testuser#123");
driver.findElement(By.id("log_in_top")).click();
}
#Then("^I check to see if i was successfully loged in or not$")
public void I_check_to_see_if_i_was_successfully_loged_in_or_not() throws Throwable {
System.out.println("Login Successfull");
}
// Scenario 2
#Given("^I navigate to the File a bug page$")
public void I_navigate_to_the_File_a_bug_page() throws Throwable {
driver.findElement(By.id("enter_bug")).click();
}
#When("^I click on widgets$")
public void I_click_on_widgets() throws Throwable {
driver.findElement(By.linkText("Widgets")).click();
}
#And("^I enter the bug details$")
public void I_enter_the_bug_details() throws Throwable {
new Select(driver.findElement(By.id("bug_severity"))).selectByVisibleText("trivial");
new Select(driver.findElement(By.id("cf_drop_down"))).selectByVisibleText("---");
new Select(driver.findElement(By.id("rep_platform"))).selectByVisibleText("Macintosh");
new Select(driver.findElement(By.id("op_sys"))).selectByVisibleText("Mac OS X 10.0");
driver.findElement(By.id("short_desc")).clear();
driver.findElement(By.id("short_desc")).sendKeys("OS crashed");
driver.findElement(By.id("comment")).clear();
driver.findElement(By.id("comment")).sendKeys("Os debugging issue");
}
#Then("^Bug should be submited succefully$")
public void Bug_should_be_submited_succefully() throws Throwable {
System.out.println("Bug submitted successfully");
}
}
Looks like you are not calling the browser and navigating to the page in scenario 2
You need do do something similar to this
#Given("^I navigate to the File a bug page$")
public void I_navigate_to_the_File_a_bug_page() throws Throwable {
driver = new FirefoxDriver();
baseUrl ="https://landfill.bugzilla.org/bugzilla-4.4-nch/index.cgi";
driver.get(baseUrl);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.id("enter_bug")).click();
enter code here
}
or use #Before hooks to initialize the browser
I think I kind get your problem here. I had encountered similar problem before.
So when running the feature file, either by clicking on the run button from the bar or right click in the feature file then run..., take a look at what it says when actually clicking it. Because if you hover over a certain scenario and click run, it will only run that scenario, not the whole feature file where there is more than 1 scenarios.

Invoke Struts Action Test from within a web app (JSF managed bean): TestCase.fname cannot be null

I have a Junit 3.8 test of a Struts 2 action that runs with no problems from my workspace (from eclipse: right click > run as > junit test).
For this, I use two plugins:
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-junit-plugin</artifactId>
<version>2.1.8</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>2.1.8</version>
</dependency>
Here is the test class:
package com.myapp.user.my;
import org.apache.struts2.StrutsSpringTestCase;
import com.myapp.user.action.UserAction;
import com.opensymphony.xwork2.ActionProxy;
public class TestAccountActionUsingStrutsTestCase extends StrutsSpringTestCase {
public void testUserNameErrorMessage() throws Exception {
request.setParameter("userBean.userName", "Bruc");
request.setParameter("userBean.password", "test");
ActionProxy proxy = getActionProxy("/userAction");
UserAction userAction = (UserAction) proxy.getAction();
proxy.execute();
assertTrue("Problem There were no errors present in fieldErrors but there should have been one error present", userAction.getFieldErrors().size() == 1);
assertTrue("Problem field user.userName not present in fieldErrors but it should have been",
userAction.getFieldErrors().containsKey("userBean.userName") );
System.out.println("Finish 1 test.");
}
}
Next, I try to invoke this test, this time from within a web application (a JSF managed bean).
Here is my code for trying to do that (I'm calling the following runTest() method from a managed bean):
import java.util.List;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import com.myapp.user.my.TestAccountActionUsingStrutsTestCase;
public class CallStrutsActionExecuteThruTest {
public void runTest(){
System.out.println("CallStrutsActionExecuteThruTest.runTest() is executed.");
TestAccountActionUsingStrutsTestCase test = new TestAccountActionUsingStrutsTestCase();
JUnitCore jUnitCore = new JUnitCore();
Result result = jUnitCore.run(test);
List<Failure> list = result.getFailures();
for (Failure failure : list) {
System.out.println(failure.getMessage());
}
System.out.println("Test done!");
}
}
When I access the managed bean, I can see that runTest() is called. The first output CallStrutsActionExecuteThruTest.runTest() is executed. is printed to console. Strangely, the next outputs are not printed to console, although the debugger shows me they are executed.
Also, result.getFailures() returns a list with one element. As I said, its failure.getMessage() for some reason is not printed to console, but when I watch it in the debugger its value is TestCase.fname cannot be null.
* Even when I have only one method in my test class:
public void testTrue() throws Exception {
System.out.println("inside testTrue().");
assertTrue(true);
}
I still get the same results.
My questions are,
If I want to run the Struts action test from a JSF managed bean, am I using the Junit API correctly?
Why weren't the outputs that followed the first one printed to console?
How do I set TestCase.fname with a value? First I don't see a method in my test class to set this value. Second, from my understanding, fanme is the name of the test method in the test class that I want to call; and jUnitCore.run(test) should call all the test methods in the test class test, so how can I specify all these methods with only one fname parameter?
Download - you can download my project here. I use Maven, Eclipse, and deploy on Jboss 7.
I access the JSF managed bean by: http://localhost:8080/Struts2WithSpringDIIntegrationExampleJunitFromUI-1.0-SNAPSHOT/xhtml/hello.jsf
Struts2 tests don't work with raw parameters for some reason. Use parameterMap instead.
Map<String, String[]> parameterMap = new HashMap<String, String[]>();
parameterMap.put("userBean.userName", new String[]{"Bruc"});
parameterMap.put("userBean.password", new String[]{"test"});
StrutsMockHttpServletRequest request = new StrutsMockHttpServletRequest();
request.setupGetServletPath("/userAction");
request.setParameterMap(parameterMap);

Resources