Unable to switch to WEBVIEW using Selendroid, getting WebDriverException - selendroid

Im trying to automate hybrid application using Selendroid.
Im getting exception at "driver.switchTo().window("WEBVIEW").
Below is the code.
WebElement uname;
WebElement password;
#BeforeClass
public static void setUp() throws Exception{
System.out.println("Set up in progress");
SelendroidConfiguration config = new SelendroidConfiguration();
config.addSupportedApp("D:DJ/HDFC/iAgent.apk");
if(selendroidServer!=null){
selendroidServer.stopSelendroid();
}
selendroidServer = new SelendroidLauncher(config);
selendroidServer.launchSelendroid();
SelendroidCapabilities capa = new SelendroidCapabilities();
capa.setAut("com.hdfclife.msd:4.85");
capa.setEmulator(false);
//capa.setPlatformVersion(DeviceTargetPlatform.ANDROID19);
driver = new SelendroidDriver(capa);
}
#Test
public void selendroidTest() throws InterruptedException{
System.out.println("Hello.. mSD under Test -- " + driver.getCurrentUrl());
//driver.switchTo().activeElement();
driver.switchTo().window("WEBVIEW");
Thread.sleep(10000);
uname = driver.findElement(By.name("username"));
uname.sendKeys("110105");
Thread.sleep(3000);
password = driver.findElement(By.name("password"));
password.sendKeys("Hdfc#123");
Thread.sleep(3000);
WebElement loginBtn = driver.findElement(By.id("loginButton"));
loginBtn.click();
Thread.sleep(3000);
}
#AfterClass
public static void tearDown(){
selendroidServer.stopSelendroid();
driver.quit();
}
Below is the error displaying.
org.openqa.selenium.WebDriverException: CATCH_ALL: java.lang.NullPointerException
at io.selendroid.server.model.internal.WebViewHandleMapper.getWebViewByHandle(WebViewHandleMapper.java:49)
at io.selendroid.server.model.SelendroidWebDriver.init(SelendroidWebDriver.java:310)
at io.selendroid.server.model.SelendroidWebDriver.(SelendroidWebDriver.java:87)
Can any one help on this.
Thanks,
Dheeraj

Check with the WEBVIEW_01 and WEBVIEW_02 along with WEBVIEW in driver.switchto statement.
The identifier of web view can also be like above.

Related

Mockito do not throw exception

I have this method my repository method throws RepositoryException and service method throws Service exception i am mocking the repository and throwing repository exception but it is not throw any exception can anybody please explain what is going on here.
public class IndActivityTest {
static BigDecimal offset;
static SecurityContext userContext;
SearchFilter filter = new SearchFilter();
SearchFilterToDB filterToDB = new SearchFilterToDB();
static BigDecimal limit;
static User user = null;
#Mock
static UserRepository repository;
#Mock
static SearchRepository searchRepository;
#InjectMocks
static SearchApiServiceImpl searchApiImple;
#Before
public void init() {
MockitoAnnotations.initMocks(this);
}
#BeforeClass
public static void setUp(){
user = new User();
String scheme="https";
userContext = new ServiceSecurityContext(user, scheme);
}
#Test
public void getIndActivitiesPositiveResponse() throws RepositoryException,ServiceException{
List<IndActivityDetailEntity> activityDetailEntities = new ArrayList<>();
when(searchRepository.getIndActivitiesFromDB(filterToDB,user)).thenReturn(activityDetailEntities);
Response response = searchApiImple.getIndActivities(filter, userContext);
assertEquals(response.getStatus(), 200);
}
#Test(expected=ServiceException.class)
public void getIndActivitiesNegetiveResponse() throws RepositoryException,ServiceException{
when(searchRepository.getIndActivitiesFromDB(filterToDB,user)).thenThrow(new RepositoryException());
searchApiImple.getIndActivities(filter, userContext);
}
}
public Response getIndActivities(SearchFilter searchFilter, SecurityContext securityContext)
throws ServiceException {
List<Activity> activities = new ArrayList<>();
try {
logger.info("Entering getActivities");
List<IndActivityDetailEntity> activityDetailEntities = new ArrayList<>();
User user = (User) securityContext.getUserPrincipal();
SearchFilterToDB searchFilterToDB = newFilterToDB(searchFilter, user);
activityDetailEntities = searchRepository.getIndActivitiesFromDB(searchFilterToDB, user);
if (!activityDetailEntities.isEmpty())
activities = SearchUtil.convertIndActivityToIndActivityDTO(activityDetailEntities, searchRepository);
logger.info(" Exiting getActivities");
} catch(Exception e){
handleException(e);
}
return Response.status(200).entity(new InlineResponse200().data(activities)).build();
}
private void handleException(Exception e) throws ServiceException{
logger.error("Service Exception "+e);
if( e instanceof ServiceException)
throw (ServiceException)e;
if( e instanceof RepositoryException ){
RepositoryException re = (RepositoryException)e;
throw new ServiceException(re.getErrorCode(),re,re.getMessage());
}else{
throw new ServiceException(e.getMessage(), e,ServiceConstant.UNKNOWN);
}
}
The issue is at the line new FilterToDB(searchFilter, user) in your getIndActivities() method of the service, because searchFilterToDB objects are different, the method call is NOT actually mocked.
So, to solve the problem, you need to extract new FilterToDB object creation to a separate class & mock the method call to that class.

Quasar multi fibers warning

I am new to quasar and I tried doing this.
Basically I get a warning the fiber is blocking a thread. Why ? can I not do something like below ?
Thanks
//in my my testclass I have this
String websites[] = {"http://www.google.com",""http://www.lol.com",""http://www.somenoneexistantwebsite.com"};
for(int i=0; i < websites.length ; i++){
TestApp.getWebsiteHTML(websites[i]);
}
//in TestApp
public static void getWebsiteHTML(String webURL) throws IOException, InterruptedException, Exception {
new Fiber<Void>(new SuspendableRunnable() {
#Override
public void run() throws SuspendExecution, InterruptedException {
WebInfo mywi = new WebInfo();
mywi.getHTML(webURL);
}
}).start().join();
}
//in WebInfo
public static String getHTML(String urlToRead) throws Exception {
StringBuilder result = new StringBuilder();
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
Have a look at the "Runaway fibers" sub-section in the docs.
HttpURLConnection is thread-blocking so in order to avoid stealing threads from the fiber scheduler for too much time (which risks killing your Quasar-based application's performance) you should rather use an HTTP client integrated with Quasar (or integrate one yourself).

How to hit the database from junit using JPA

I am writing junit test case, how to hit the database from junit using jpa.
I wrote the code for but got the following exception
javax.persistence.PersistenceException: No Persistence provider for EntityManager named smsPU
I added provide in src/test/resources/META-INF/persistent.xml file, But i got the that error.
I am posting the my code also please check where is the wrong in this code.
public class SmsBeanTest {
private SmsBean smsBean;
private SmsNotification notification;
private EntityManagerFactory entity;
private EntityManager em;
#Before
public void setUp() throws Exception {
String CONFIG_ATTR_NAME = "webappConfig";
smsBean = new SmsBean();
ServletContext ctx = mock(ServletContext.class);
Configuration config = new Configuration();
config.initProperties("syniverse-sms.properties");
when(ctx.getAttribute(CONFIG_ATTR_NAME)).thenReturn(config);
smsBean.setServletContext(ctx);
**//em = mock(EntityManager.class);
Properties prop = new Properties();
// Ensure RESOURCE_LOCAL transactions is used.
prop.put(TRANSACTION_TYPE,
PersistenceUnitTransactionType.RESOURCE_LOCAL.name());
// Configure the internal connection pool
prop.put(JDBC_DRIVER, "com.mysql.jdbc.Driver");
prop.put(JDBC_URL, "jdbc:mysql://localhost:3306/platform_service_db");
prop.put(JDBC_USER, "root");
prop.put(JDBC_PASSWORD, "root");
prop.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML,
"src/test/resources/META-INF/persistence.xml/lib/fdn-persistence-1.0.0-SNAPSHOT.jar");
entity = Persistence.createEntityManagerFactory("smsPU", prop);
System.out.println(entity);
em = entity.createEntityManager(prop);
smsBean.setEm(em);**
// doNothing().when(em).persist(notification);
smsBean.init();
notification = new SmsNotification();
}
#After
public void tearDown() throws Exception {
smsBean = null;
notification = null;
//entity.close();
//em.close();
}
#Test
public void testSendSms() {
SmsNotificationDTO sms = new SmsNotificationDTO();
sms.setToAddress("9985291980");
sms.setMessage("Sending Message...");
try {
SyniverseDispatcher disp = mock(SyniverseDispatcher.class);
SyniverseResponse resp = new SyniverseResponse();
resp.setResponseStr("1234");
String smsTo = notification.getDestination();
String smsMsg = notification.getMessage() + new Date().getTime();
String urlStr = smsBean.getHostname() + "?user=" + smsBean.getUser() + "&pass=" + smsBean.getPass() + "&smsfrom=" + smsBean.getShortCode() + "&smsto=" + sms.getToAddress() + "&smsmsg=" + sms.getMessage();
SyniverseRequest req = new SyniverseRequest();
req.setRequestURL(urlStr);
when(disp.dispatch(req)).thenReturn(resp);
smsBean.sendSms(sms);
assertNotNull(sms.getToAddress());
assertEquals(10, sms.getToAddress().length());
assertNotNull(sms.getMessage());
assertEquals("1234", resp.getResponseStr());
} catch (SmsException e) {
fail(e.getMessage());
}
}
}
please help me,
it can't find the persistance.xml because you have it incorrectly defined. "src/test/resources/META-INF/persistence.xml/lib/fdn-persistence-1.0.0-SNAPSHOT.jar" the jar file shouldn't be listed.

ClientResponse Failure in mockito test cases

Iam working on mockito testcases positive test methods are getting executed but comming to Exception Test methods its failing with the Exception
java.lang.Exception: Unexpected exception, expected<com.apple.ist.retail.xcard.common.exception.InvalidArgumentException> but was<org.jboss.resteasy.client.ClientResponseFailure>
at
Below is the test method which is failing and its parent class containing client object
package com.apple.ist.retail.xcard.ws.exception;
public class TestActivatePrepaidCard extends CertificateResourceTestCase {
public TestActivatePrepaidCard(String aMediaType) {
super(aMediaType);
}
#Before
public void setUp() {
super.setUp();
}
#Test(expected = InvalidArgumentException.class)
public void testActivatePrepaidCard_InvalidArgumentException()
throws DuplicateCertificateIDException, InvalidArgumentException,
DupTxnRefException, AmountException, SystemException,
XCardException {
when(
server.activatePrepaidCard(any(DiagnosticContext.class),
any(String.class), any(Number.class),
any(Amount.class), any(String.class), any(int.class),
any(HashMap.class), any(String.class),
any(SalesOrg.class), any(TxnRef.class))).thenThrow(
new InvalidArgumentException("Invalid Argument ",
INVALID_ARGUMENT));
client.activatePrepaidCard(certificateRequest);
}
Its failing near client.activatePrepaidCard(certificateRequest); with ClientResponseFailure Exception
Parent test case is
package com.apple.ist.retail.xcard.ws.exception;
#RunWith(value = Parameterized.class)
public abstract class CertificateResourceTestCase extends Assert {
protected CertificateResource client;
protected XCardServiceServer server;
protected CertificateResource resource;
protected CertificateRequest certificateRequest;
// protected Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
private String mediaType;
public CertificateResourceTestCase(String aMediaType) {
this.mediaType = aMediaType;
server = mock(XCardServiceServer.class);
CertificateResourceImpl xcardServiceRs = new CertificateResourceImpl();
xcardServiceRs.setService(server);
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getRegistry().addSingletonResource(xcardServiceRs);
dispatcher.getProviderFactory().addExceptionMapper(
XCardExceptionMapper.class);
dispatcher.getProviderFactory().addExceptionMapper(
BusinessExceptionMapper.class);
dispatcher.getProviderFactory().addExceptionMapper(
RuntimeExceptionMapper.class);
dispatcher.getProviderFactory().addExceptionMapper(
BusinessExceptionMapper.class);
dispatcher.getProviderFactory().addExceptionMapper(
RuntimeExceptionMapper.class);
dispatcher.getProviderFactory()
.getServerMessageBodyWriterInterceptorRegistry()
.register(new XCardTxnWriterInterceptor());
dispatcher.getProviderFactory().getContextDataMap()
.put(HttpServletRequest.class, new MockHttpServletRequest());
client = ProxyFactory.create(CertificateResource.class, "/", new InMemoryClientExecutor(dispatcher));
diagnosticContext.setReportingRecommended(false);
}
#After
public void tearDown() throws Exception {
Mockito.reset(server);
}
Please let me know whats wrong in my code,I am pasting complete code so that I will not miss any detail
Your code is throwing an ClientResponseFailure. Debug your test and find out why. Use an exception breakpoint.

How to redirec to to HTML if exception occured

I've been trying to search for a way to redirect to an HTML file if a SQLException occurs. I'm going to give you an example.
I have my connection class something like this:
public class DBConection{
Connection con = null;
public DBConnection() throws RuntimeException{
try {
Class.forName("org.gjt.mm.mysql.Driver");
String user = "root";
String pass = "12345";
String db = "java";
con = DriverManager.getConnection("jdbc:mysql://localhost/" + db, user, pass);
}catch (ClassNotFoundException ex) {
throw new RuntimeException();
}catch (SQLException ex) {
throw new RuntimeException();
}
}
}
and I'm calling it from a Servlet class,
public class ElectionsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String RETURN_PAGE = "index.jsp";
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
DBConnection con = new DBConnection();
response.sendRedirect(RETURN_PAGE);
}
}
If an error ocurres during the DBConnection I want to redirect it to my RETURN_PAGE. Can anybody help me?
Just use the builtin container managed exception handling facilities. You need to rethrow the caught exception as ServletException and define the error page as <error-page> in web.xml.
You only need to change your DB access logic accordingly. It's far from sane, safe and efficient. The exception handling is also strange. You seem to have ripped this from a completely outdated resource given the fact that you're using the deprecated MySQL JDBC driver class name.
Here's a basic kickoff example:
public final class Database {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost/java";
private static final String USER = "root";
private static final String PASS = "12345";
static {
try {
Class.forName(DRIVER);
}
catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError("The JDBC driver is missing in classpath!", e);
}
}
private Database() {
// Don't allow construction.
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USER, PASS);
}
}
Finally use and handle it in the servlet as follows:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Connection connection = null;
// ...
try{
connection = Database.getConnection();
// ...
}
catch (SQLException e) {
throw new ServletException("DB fail!", e);
}
finally {
// ...
if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
}
}
(better would be to wrap the DB job in a DAO class which in turn throws a SQLException, but that's a different problem)
And declare the error page in web.xml as follows:
<error-page>
<exception-type>java.sql.SQLException</exception-type>
<location>/WEB-INF/errorpages/database.jsp</location>
</error-page>
You can of course also use <location>/index.jsp</location> but that's not very friendly to the enduser as it's completely confusing why he returns back to there. Rather put that as a link in the database.jsp error page along with something user friendly like
Sorry, an unrecoverable problem has occurred while communicating with the DB. Please click the following link to return to the index page.
See also:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
The question is already answered, but I'll add a few comments:
I don't see the need of catching SQLException and ClassNotFoundException only to rethow RuntimeException instances. If you're planning to do nothing when this exception raises in your DBConnection class, just add throws to your constructor signature. With that, the compiler will check that a try-catch block be added when using your constructor.
There's no need of adding throws RuntimeException to your constructor signature. RuntimeException is a non-checked exception.
Add try-catch block to your doPost method and if any exception occurs in try block, catch that exception and redirect to RETURN_PAGE.
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
try{
DBConnection con = new DBConnection();
}catch(Exception e){
response.sendRedirect(RETURN_PAGE);
}
}