WebDriver windows not closed when running testNG.xml with more than one class in eclipse - eclipse

I have a testNG suite with more than 10 classes. When I start testNG.xml as a suite, the browsers(ff) not closing before going to 2nd class where I have used to open the browser and close it in every class. I have tested it with giving only one class the browser is closed. Please check the below code for #AfterTest
#BeforeClass(alwaysRun = true)
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://www.example.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test(priority=0)
public void testActivityMasterDBCheck() throws Exception {
--------------------
--------------------
#AfterTest
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString))
{
fail(verificationErrorString);
}
}
and XML is
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test name="Test">
<classes>
<class name="Admin.ManagePackagesDBCheck"/>
<class name="Reports.ActiveStatusReportDBCheck"/>
----------
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

Use #AfterClass annotation like this:
#AfterClass
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString))
{
fail(verificationErrorString);
}
}

Do that #AfterClass and (alwaysRun = true). Reason your browser may not be closing is simple, you are using one driver instance to initiate the browser. So once your execution is over, the next class will start execution, but your is not over yet. So try using #AfterClass or #AfterMethod. I would suggest #AfterClass as, you are initiating your driver #BeforeClass
Hope that helps.

Related

OSGi custom shell command

I am trying to create a custom command for the OSGI console (Equinox) but I cannot seem to either register or use the command correctly. The bundle starts and tried to call mock:command or command to no avail. The used eclipse is rather old: 3.6.2.R36x_v20110210 and the containing bundle is started manually. Any ideas?
public class Activator extends Plugin
{
private static Activator plugin;
private MockCommand service;
#Override
public void start(BundleContext context) throws Exception{
plugin = this;
Dictionary<String, Object> properties = new Hashtable<String, Object>();
properties.put("osgi.command.scope", "mock");
properties.put("osgi.command.function", new String[] {MockCommand.COMMAND});
service = new MockCommand();
context.registerService(MockCommand.class.getName(),service, null);
super.start(context);
}
#Override
public void stop(BundleContext context) throws Exception{
plugin = null;
service = null;
super.stop(context);
}
public static Activator getDefault(){
return plugin;
}
}
And the CommandProvider:
public class MockCommand implements CommandProvider{
public static String COMMAND ="command";
public void _command(CommandInterpreter ci) throws Exception {
String commandID = "com.sample.project.fetchMySampleDataCommandId";
((IHandlerService)PlatformUI.getWorkbench().getService(IHandlerService.class)).executeCommand(commandID, null);
}
#Override
public String getHelp() {
StringBuffer buffer = new StringBuffer();
buffer.append("--- Available commands to call by ID ---\n\t");
buffer.append("command --> com.sample.project.fetchMySampleDataCommandId\n\t");
return buffer.toString();
}
}
There was apparently an OSGI Service-Component definition missing. In order to do that I created an /OSGI-INF/ServiceFacade.xml
<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="serviceFacade">
<implementation class="com.sample.project.MockCommand"/>
<service>
<provide interface="org.eclipse.osgi.framework.console.CommandProvider"/>
</service>
</scr:component>
and added to my /META-INF/MANIFEST.MF
Service-Component: OSGI-INF/ServiceFacade.xml

Eclipselink: No suitable driver found in glassfish while it works in JavaSE

I'm trying to create EntityManager in my webapp, but it's failing with:
No suitable driver found for jdbc:postgresql:://localhost/database
However the same persistance unit and the same code for creating EntityManager works when I run it as JavaSE console application (from main() ).
Googling gave me several common problems causing that error:
JDBC url is wrong
Shouldn't be since it works from main
JDBC Driver is not in the class path
I can create a Class object using Class.forName("org.postgresql.Driver"); for the driver so I think it is in the classpath.
Other things I tried:
I thought maybe the driver jar from glassfish/lib and the webapp/WEB-INF/lib are conflicting somehow so I tried with both of them together and separately, no luck.
Recreated a small new webapp hoping the problem will go away, it didn't :-)
Inject #PersistanceUnit - also didn't work, don't know is it the same issue or I didn't use it properly as I'm still learning about injection and EJBs
Thanks
Full error:
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: java.sql.SQLException: No suitable driver found for jdbc:postgresql://localhost/database Error Code: 0
Here is the code:
ManagedBean in webapp:
#ManagedBean
public class TestBean {
private String entry;
private String driver;
public String getFromDatabase(){
EntityManagerFactory emf = Persistence.createEntityManagerFactory("Unit1");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
EntityOne one = new EntityOne();
one.id = 1;
one.entry = "Bla bla";
em.persist(one);
tx.commit();
em.close();
return "done";
}
public String createDriver(){
try {
Class d = Class.forName("org.postgresql.Driver");
driver = d.getName();
} catch (ClassNotFoundException e) {
driver = "Class not found";
return "";
}
return "";
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getEntry() {
return entry;
}
public void setEntry(String entry) {
this.entry = entry;
}
}
Same code working in main:
public class Standalone {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("Unit1");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
EntityOne one = new EntityOne();
one.id = 1;
one.entry = "Bla bla";
em.persist(one);
tx.commit();
em.close();
}
}
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="Unit1" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.test.EntityOne</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost/database"/>
<property name="javax.persistence.jdbc.user" value="darko"/>
<property name="javax.persistence.jdbc.password" value="sifra"/>
<property name="eclipselink.target-database" value="PostgreSQL"/>
</properties>
</persistence-unit>
Place the posgres jdbc driver into the lib of glassfish. Its something like this.
[glassfish_home]/glassfish/domains/YOUR_DOMAIN/lib/
Also, restart the server after this.

Inject Spring bean within RESTEasy Resource at Test time

Within a Unit/Integration Test, I'm trying to use the RESTEasy embedded server TJWSEmbeddedJaxrsServer or POJOResourceFactory inorder to simulate through a MockHttpRequest.get("/data") a resource call for test purpose.
My problem is that based on the use of the server or the Resource factory I'm not able to have a non null instance of spring beans which are injected normally within my resources.
Here's some code for clarification, thanks in advance.
Spring application context :
<context:annotation-config />
<context:component-scan base-package="com.cdcfast.service" />
<bean id="simpleResource" class="com.cdcfast.rest.SimpleResource" />
SimpleResource.java :
#Component
#Path("/data")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public class SimpleResource {
#Autowired
private SimpleService service;
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<Data> getData() {
return MockDataBase.getInstance().getRows();
}
Unit Test :
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath*:/test/spring/testApplicationContext.xml" })
public class FakeTest {
private Dispatcher dispatcher;
#Before
public void before() {
dispatcher = MockDispatcherFactory.createDispatcher();
POJOResourceFactory noDefaults = new POJOResourceFactory(SimpleResource.class);
dispatcher.getRegistry().addResourceFactory(noDefaults);
}
#Test
public void aTestThatAlwaysPass() throws URISyntaxException {
MockHttpRequest request = MockHttpRequest.get("/data");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
Assertions.assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
Assertions.assertThat(response.getContentAsString()).isNotNull().isNotEmpty();
}
}
I've had this before because the RESTEasy factories create the POJO rather than Spring so they don't get wired up which can be worked around in the full container but is less easy in a test. The best way around this is to get a handle to your POJO once the factory creates it and then do something similar to this:
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(myPojo);
I personally ended up having Spring create the RESTEasy beans using the RESTEasy-Spring plugin and then launching my tests using Jetty, not sure if that is an option for you though.
I exeprienced same problem and i'have solved in similar way as James did:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:spring-context-test.xml" })
public class TestMyService {
Dispatcher dispatcher;
private String username = "user";
#Autowired
ApplicationContext context;
#Before
public void setUp() {
MyService g = new MyService(); //rest service with #autowired spring beans
context.getAutowireCapableBeanFactory().autowireBean(g);
dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getRegistry().addSingletonResource(g);
}
#Test
public void TestRest() {
MockHttpRequest request;
try {
request = MockHttpRequest.get("/rest/service").header("LOGON_USER", username);
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
assertTrue("Error, unexpected status code: " + response.getStatus(), response.getStatus() == 200);
LoggerFactory.getLogger(this.getClass()).info("********** " + response.getContentAsString());
} catch (URISyntaxException e) {
Log.error(e.getMessage(), e);
fail(e.getMessage());
}
}
}

GWT 2.5 Application Deployment in Tomcat?

I am using GWT 2.5. I have an application using gwt-rpc. I have compiled the project and make war file using an ant-script. When I would deploy the project on tomcat it loads successfully but Doesn't show any control. Just a simple blank html page. here are my files.
Module
<?xml version="1.0" encoding="UTF-8"?>
<!--
When updating your version of GWT, you should also update this DTD reference,
so that your app can take advantage of the latest GWT module capabilities.
-->
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.5.0//EN"
"http://google-web-toolkit.googlecode.com/svn/tags/2.5.0/distro-source/core/src/gwt-module.dtd">
<module rename-to='interviewscheduler'>
<!-- Inherit the core Web Toolkit stuff. -->
<inherits name='com.google.gwt.user.User'/>
<!-- Inherit the default GWT style sheet. You can change -->
<!-- the theme of your GWT application by uncommenting -->
<!-- any one of the following lines. -->
<inherits name='com.google.gwt.user.theme.clean.Clean'/>
<!-- <inherits name='com.google.gwt.user.theme.standard.Standard'/> -->
<!-- <inherits name='com.google.gwt.user.theme.chrome.Chrome'/> -->
<!-- <inherits name='com.google.gwt.user.theme.dark.Dark'/> -->
<!-- Other module inherits -->
<inherits name="com.smartgwt.SmartGwt"/>
<!-- Specify the app entry point class. -->
<entry-point class='interviewscheduler.client.InterViewScheduler'/>
<!-- Specify the paths for translatable code -->
<source path='client'/>
<source path='shared'/>
</module>
Remote Service
package interviewscheduler.client;
import interviewscheduler.shared.Interview;
import interviewscheduler.shared.Teacher;
import java.util.LinkedHashMap;
import java.util.List;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
#RemoteServiceRelativePath("interviewScheduler")
public interface InterviewSchedulerService extends RemoteService{
Boolean loadStudentData() throws IllegalArgumentException;
Boolean loadParentData() throws IllegalArgumentException;
Boolean loadTeacherData() throws IllegalArgumentException;
Boolean loadClassData() throws IllegalArgumentException;
Boolean loadClassMemberShipData() throws IllegalArgumentException;
Boolean loadRoomData() throws IllegalArgumentException;
Boolean loadSessionData() throws IllegalArgumentException;
Boolean loadInterviewData() throws IllegalArgumentException;
LinkedHashMap<String, String> getStudentNames() throws IllegalArgumentException;
String getParentName(String studentKey) throws IllegalArgumentException;
List<Teacher> getAvailableTeachers(String studentKey) throws IllegalArgumentException;
List<Teacher> getRequestedTeachers(String studentKey) throws IllegalArgumentException;
List<Interview> getInterviewByStudent(String studentKey) throws IllegalArgumentException;
List<Interview> getInterviewByTeacher(String teacherCode) throws IllegalArgumentException;
List<Object> getInterviewsForGrid(List<Interview> list) throws IllegalArgumentException;
String addInterview(Interview obj) throws IllegalArgumentException;
String removeInterview(String studentId, String teacherId) throws IllegalArgumentException;
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee">
<!-- Servlets -->
<servlet>
<servlet-name>interviewSchedulerServlet</servlet-name>
<servlet-class>interviewscheduler.server.InterviewSchedulerServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>interviewSchedulerServlet</servlet-name>
<url-pattern>/interviewscheduler/interviewScheduler</url-pattern>
</servlet-mapping>
<!-- Default page to serve -->
<welcome-file-list>
<welcome-file>InterViewScheduler.html</welcome-file>
</welcome-file-list>
</web-app>
Any ideas what I am doing wrong.? Its urgent.
package interviewscheduler.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.smartgwt.client.widgets.layout.VLayout;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class InterViewScheduler implements EntryPoint {
/**
* This is the entry point method.
*/
private InterviewSchedulerServiceAsync remoteObject=GWT.create(InterviewSchedulerService.class);
private VLayout wrapper=new VLayout();
private VLayout headerArea=new Header();
private VLayout contentArea=new ContentArea();
public void onModuleLoad() {
Window.enableScrolling(true);
Window.setMargin("0px");
remoteObject.loadStudentData(new AsyncCallback<Boolean>() {
#Override
public void onSuccess(Boolean result) {
RootLayoutPanel.get().add(drawWrapper());
}
#Override
public void onFailure(Throwable caught) {
System.out.println("Failed*****************");
}
});
}
/**
* initialize the wrapper of the web site which holds all other content------Main Container
*/
public VLayout drawWrapper(){
wrapper.setWidth100();
wrapper.setHeight100();
wrapper.setMargin(0);
wrapper.addMember(drawHeaderArea());
wrapper.addMember(drawContentArea());
return wrapper;
}
/**
* initialize the Header Area of the web site which contains Logo with Title and a logout button
*/
public VLayout drawHeaderArea(){
headerArea.redraw();
return headerArea;
}
/**
* initialize the Content Area of the web site which holds a main TabSet
*/
public VLayout drawContentArea(){
contentArea.redraw();
return contentArea;
}
}
You have to show your data somehow in your application. All you're doing right now is calling a bunch of services. It's actually quite confusing. You should just do all of that in one call to the server. It will save you A LOT of round trips and most likely will save you from having some failed calls.
Stupid mistake... I am not including the necessary libraries in WEB-INF/lib directory. Which causes to fail my RPC call. Any ways. Special thanks to Enrybo. Debugging Technique is very useful.

Starting Selenium with custom Firefox profile from Eclipse

I'm running Selenium tests from within Eclipse, but I can't load a custom Firefox profile.
Most sources suggest I need to launch the Selenium Server like this:
java -jar selenium-server.jar -firefoxProfileTemplate </path/to/template/>
But when launching my test from within Eclipse it doesn't use that - the tests will run if the Selenium Server isn't running.
This thread suggests that I can set the profile in the DefaultSelenium constructor:
Selenium RC - disabling browser cookie
But the code generated for me by Selenium IDE (Firefox plugin) doesn't use that constructor:
package com.example.tests;
import com.thoughtworks.selenium.*;
import java.util.regex.Pattern;
public class Example extends SeleneseTestCase {
public void setUp() throws Exception {
setUp("http://www.example.com/", "*firefox");
}
public void testExample() throws Exception {
selenium.open("/");
selenium.click("//body");
}
}
Where should I set the DefaultSelenium configuration options? Or is there some other method I can use to load my custom Firefox template?
Thanks!
Stu
I made a SeleniumTestCase that starts/stops the server before/after each test class and starts/stops the Selenium instance before/after each test:
public class SeleniumTestCase {
protected static Selenium selenium;
protected static AppNavUtils appNavUtils;
#BeforeClass
public static void setUpBeforeClass() throws Exception {
SeleniumServerControl.getInstance().startSeleniumServer();
}
#AfterClass
public static void tearDownAfterClass() throws Exception {
SeleniumServerControl.getInstance().stopSeleniumServer();
}
#Before
public void setUp() throws Exception {
// Replace "*chrome" with "*firefox" for Selenium > 1.0
selenium = new DefaultSelenium("localhost", 5444, "*chrome", "http://localhost:8080/");
selenium.start();
appNavUtils = new AppNavUtils(selenium);
}
#After
public void tearDown() throws Exception {
selenium.stop();
}
}
The SeleniumServerControl starts and stops the server:
public class SeleniumServerControl {
private static final SeleniumServerControl instance = new SeleniumServerControl();
public static SeleniumServerControl getInstance()
{
return instance;
}
private SeleniumServer server = null;
protected SeleniumServerControl(){}
public void startSeleniumServer() {
if (server == null) {
RemoteControlConfiguration rcc = new RemoteControlConfiguration();
rcc.setPort(5444);
//rcc.setFirefoxProfileTemplate(newFirefoxProfileTemplate)
server = new SeleniumServer(rcc);
}
server.start();
}
public void stopSeleniumServer()
{
if (server != null) {
server.stop();
server = null;
}
}
}
the version of code you have above assumes that you are running your tests against localhost on port 4444 thats why it is has 2 parameters in the setup.
To set up eclipse to run it you will need to update the run configuration. That is under
Run > Run Configurations
Have a look for the item that has selenium in it and add the config above so that when it runs it will pick it up and run.
I personally just fire up the server when I start working by running a batch file and kill it at the end of the day.