I want to use TestNg in my learning project. While using TestNg framework, i am getting NullPointer Excetion. I think problem is in WebDriver object declaration part. But i don't know how i can implement the same. Can any one help me on the same?  Please find the code below,  package in.prolearn.testcases;  import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.testng.annotations.BeforeMethod; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test;  import in.prolearn.pages.HomePage; import in.prolearn.pages.SearchResultPage; import in.prolearn.utility.BrowserSelection;  public class VerifySnapDealSelection {     WebDriver driver = null;      @BeforeTest     public void preCondition(){         driver = BrowserSelection.browserSelection("Chrome");         BrowserSelection.openBrowser("https://www.snapdeal.com/");     }      HomePage hp = new HomePage(driver);     SearchResultPage srp = new SearchResultPage(driver);      @Test     public void NavigateToSearchCategoryPage() throws InterruptedException{         hp.menuSelectionGeneric("Computers &amp; Gaming");         Thread.sleep(5000);         hp.subMenuSelectionGeneric("External Hard Drives");         Thread.sleep(5000);     }     @Test     public void SearchResultPageValidation() throws InterruptedException{         srp.FirstcapacitySelection("1 TB");         Thread.sleep(5000);         driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);         srp.FirstcapacitySelection("2 TB");         Thread.sleep(5000);         srp.verifySelectedItem("1 TB");         srp.verifySelectedItem("2 TB");         Thread.sleep(5000);         srp.DeleteSelectedItem("2 TB");         Thread.sleep(5000);         srp.VerifycapacitySelection("2 TB", "false");         srp.VerifyItem("1 TB", "1TB");         srp.DeleteSelectedItem("1 TB");         Thread.sleep(5000);         srp.VerifycapacitySelection("1 TB", "false");     } }
129
What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them?  What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
84621
I'm struggling to test a class with pagereference. Following is the class...  public with sharing class redirectOrderPartner{  public String currentRecordId {get;set;} public orders__c orderId {get;set;}  public redirectOrderPartner(ApexPages.StandardController controller) {      }     Public Pagereference go(){      currentRecordId  = ApexPages.CurrentPage().getparameters().get('orderid');      system.debug('---currentRecordId  ---'+currentRecordId  );     orderId = [select id from orders__c where name =: currentRecordId limit 1];      system.debug('---orderid---'+orderId);      PageReference pageRef = new PageReference('/apex/OrderTrackingClass?id='+orderId.id);     pageRef.setRedirect(true);     return pageRef;    }   }   Following is what I tried....    @isTest  public class redirectOrderPartner_TEST  {             static testMethod void Test(){            Account acc = new Account(Name='ABC Corp.');           insert acc;            orders__c tempOrder = new orders__c(name = '0001234567', account__c = acc.id );           insert tempOrder;            Test.startTest();            PageReference pageRef = Page.redirectOrderPartner;           Test.setCurrentPage(pageRef);            ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(tempOrder);           ApexPages.currentPage().getParameters().put('Id',tempOrder.name);           PW_redirectOrderPartner ec = new redirectOrderPartner(sc);           ec.go();                                   Test.stopTest();       }   } I get the following error message on testing..     System.QueryException: List has no rows for assignment to SObject   What am I missing? Thanks
53191
I want to do an if/else test in SELENIUM IDE. If the checkbox is checked the test should run the IF-condition, whereas otherwise it should go into the ELSE. I tried several commands for the TARGET of the IF, but each time it chose the same way regardless of whether the condition pertained or not. So I need to know how to deal with the notation of SELENIUM IDE in this case. Hope anybody can help me by showing me how I can make the condition dependent on a checkbox..
100093
I am using the following code in selenium, but I am not able to retrieve data from database. I am getting the errors "The result set has no current row"  My code is   public class Auto {      public static void main(String[] args) throws InterruptedException, SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException     {           Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");         System.out.println("Driver loaded");           Connection con=DriverManager.getConnection("jdbc:sqlserver://192.168.*****\\SQLEXPRESS/*****_DW/EPS:****;user=******;password=******; ");          System.out.println("Driver loadedd");       java.sql.Statement stmt= con.createStatement();     ResultSet rs=stmt.executeQuery("select * from [*****_DW].[dbo].dim_grantee ");      System.out.println("Query executed");      while (rs.next());     {         String Name=rs.getString("NAME");          System.out.println("Name is");     }   }
112656
I have a problem with FeedItems in my Test class, it's very weird behaviour Does someone explain to me why this happens?  Callout Class  public with sharing class Callout {  public static void runProccess(Case[] records) {     Database.executeBatch(new CalloutBatch(records), 10); }  public static void send(Case[] records) {     Case[] toUpdate = new Case[]{};       for (case record : records) {         HttpRequest req = new HttpRequest();         req.setEndpoint('callout:test/SOME_URL');         req.setMethod('POST');         req.setHeader('Content-Type', 'application/json');         req.setBody('');         Http http = new Http();         HTTPResponse res = http.send(req);          Map&lt;String, Object&gt; response = (Map&lt;String, Object&gt;) JSON.deserializeUntyped(res.getBody());          toUpdate.add(new Case(Id = (Id) response.get('Id'), Status = (String) response.get('Status')));     }      update toUpdate;  } }   CalloutBatch Class  global with sharing class CalloutBatch implements Database.Batchable&lt;Case&gt;, Database.AllowsCallouts{  private final Case[] records;  global CalloutBatch (Case[] records) {     this.records = records; }  global Iterable&lt;Case&gt; start(Database.BatchableContext BC) {     return records; }  global void execute(Database.BatchableContext BC, Case[] scope) {     Callout.send(scope); }  global void finish(Database.BatchableContext BC) { } }   Test Class  @IsTest  private class CalloutTest { @IsTest static void shouldReaciveData() {     String status = 'Closed';     Case caseRecord = new Case(Type = 'Web', Status = 'New');     insert caseRecord;      //insert new FeedItem(ParentId = caseRecord.Id, Visibility='AllUsers', Type = 'TextPost', Body = '');      System.assertEquals(0, [SELECT Count() FROM Case WHERE Id = :caseRecord.Id AND Status = :status]);      Test.startTest();     Test.setMock(HttpCalloutMock.class, new CalloutTestMock(caseRecord.Id, status));     Callout.runProccess(new Case[]{caseRecord});     Test.stopTest();      System.assertEquals(1, [SELECT Count() FROM Case WHERE Id = :caseRecord.Id AND Status = :status]); } }   Mock Class  public with sharing class CalloutTestMock implements HttpCalloutMock {  private Id recordId; private String status;  public CalloutTestMock(Id recordId, String status) {     this.recordId = recordId;     this.status = status; }  public HTTPResponse respond(HTTPRequest req) {     HttpResponse response = new HttpResponse();      response.setStatusCode(200);     response.setBody('{"Id": "' + recordId + '", "Status": "' + status + '"}');      return response; } }   This code works, but when I uncomment insert FeedItem in Test Class I receive an error message:     System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out   Class.Callout.send: line 23, column 1   Class.CalloutBatch.execute: line 20, column 1   FeedItem doesn't have an impact on this functionality, (I don't have any Process Builders, triggers etc. on FeedItem object)
119160
This Trigger is on lead (Before Insert, Before Update) and it errors (System.NullPointerException: Attempt to de-reference a null object). I'm getting this error when i'm posting "Web to Lead". However i do have the right ORG iD and Record type id included on the xml file:   &lt;input type=hidden name="oid" value="xxxxxxxxxxxxx"&gt; &lt;input type=hidden name="recordType" id="recordType" value="zzzzzzzzzzzzzzzzzz"&gt;    trigger IAAILeadTrigger on Lead (before insert, before update){ //BEGIN: S-444340 T-561808 - Process only IAA Remarketing Recordtype data     Map&lt;ID,Schema.RecordTypeInfo&gt; rt_Map = Lead.sObjectType.getDescribe().getRecordTypeInfosById();      //Looks up the branches based on the Lead PostalCode     if(trigger.isBefore){          for(Lead ld : trigger.new){                      if (rt_map.get(ld.recordTypeID).getName().containsIgnoreCase('IAA Remarketing') )                if( trigger.isInsert ||                    (trigger.isUpdate &amp;&amp; ld.Branch__c == null) ||                   (trigger.isUpdate &amp;&amp; ld.PostalCode != trigger.oldMap.get(ld.id).PostalCode)               ){                   leads.add(ld);               }           }           }                 //Only check the leads that are in the lead list and NOT the full trigger.new list         if(!leads.isEmpty()){             LeadController.GetLeadBranches(leads);           }     }  }
82873
I am trying to learn how to do APEX testing but all the tests in the documentation are too complex and I can't find an example of a simple APEX Controller that is a Hello World Test.  I have this APEX Code  public class MessageMaker{ public static string helloMessage() {     return('You say "Goodbye," I say "Hello"');     } }   Should I be testing that the String is the same? Here is my test that doesn't work      @isTest public class MessageMakerTest {     public static testMethod void testMyClass(){         MessageMaker controller = new MessageMaker();         String helloMessage = helloMessage();          System.assertEquals(helloMessage, 'You say "Goodbye," I say "Hello"');      } }   I am getting this error.       Method does not exist or incorrect signature: helloMessage()   I have some more advanced APEX code but I want to understand what I need to test for and how before I can do that.  Thank you in advance.
56441
I am currently programming a trigger on Opportunities.   I created a test class for this and in my Sandbox I created an account, contact and opportunity. When I try to reference them   Opportunity Opp = [SELECT id from Opportunity where name = 'Test1'];    and then start my   Test.startTest();         Opp.StageName = 'PO in (100%)';          update Opp;         Test.stopTest();   It just errors and shows that Opp returns 0 rows. However when I paste my first bit of code in 'Execute Anonymous' it returns a row and the correct info.   Does this mean I have to create an account, contact, quote and all necessary fields in my test class?
90464
We noticed that lots of bugs in our software developed in C# (or Java) cause a NullReferenceException.  Is there a reason why "null" has even been included in the language?  After all, if there were no "null", I would have no bug, right?  In other words, what feature in the language couldn't work without null?
12247
I have the following code:  List&lt;MobileElement&gt; messages = driver.findElements (By.id ("body_bubble")); //find all messages MobileElement lastMessage = messages.get (messages.size () - 1); //get last message  // xpath query to check if the message is delivered String xpathDeliveryStatus = ".//*[contains(@resource-id, 'delivered_indicator') or contains(@resource-id, 'read_indicator') or contains(@resource-id, 'sent_indicator')]";  MobileElement deliveryStatus = lastMessage.findElement (By.xpath (xpathDeliveryStatus));   I want to do the same except that I want to find the deliveryStatus variable using explicit wait.  So I want to find the deliveryStatus variable inside the lastMessage variable using  wait.until (ExpectedConditions.visibilityOfElementLocated (By.locator))   How can I do this?  I don't want to do it using one immense Xpath. Besides, I don't even know how to find the last element with the id body_bubble using Xpath, as the number of these elements is not fixed and always changing.  P.S. For example, in Python we can define WebDriverWait with an element in the constructor instead of driver:  WebDriverWait(webelement, self.timeout)  Unfortunately, it does not work in Java.
11325
I have written a test class for a trigger on the lead object.  When i run the test class i get the following error:  Methods defined as TestMethod do not support Web service callouts, test skipped  There is an other trigger on lead that has a call to a webservice so i get this error.  I have wrapped the call with:  if (!Test.isRunningTest()) {    // do callout }   But i’m still getting the same error.  Any other way to run correctly the test class?  Thank you in advantage.
82927
How do you make a test class for custom controller? My search results involves this but trying to apply it in my test class only create too many error that I don't understand.  public static testMethod void testMyController() {     PageReference pageRef = Page.success;//Observe how we set the Page here     Test.setCurrentPage(pageRef);   . Does my test class need those line of codes when my controller class is only very simple.  public class ClientInfo_VFcontroller{     public Org_Info__c orgInfo {get; set;}     public ClientInfo_VFcontroller(){         orgInfo = new Org_Info__c();     }     public PageReference save(){         insert orgInfo;         orgInfo = null;         ScheduleRetrieve.ScheduleRetrieve();         return null;     } }
8444
How can I use JUnit4 idiomatically to test that some code throws an exception?  While I can certainly do something like this:  @Test public void testFooThrowsIndexOutOfBoundsException() {   boolean thrown = false;    try {     foo.doStuff();   } catch (IndexOutOfBoundsException e) {     thrown = true;   }    assertTrue(thrown); }   I recall that there is an annotation or an Assert.xyz or something that is far less kludgy and far more in-the-spirit of JUnit for these sorts of situations.
36484
I'm trying to implement a KeyListener for my JFrame. On the constructor, I'm using this code:  System.out.println("test"); addKeyListener(new KeyListener() {     public void keyPressed(KeyEvent e) { System.out.println( "tester"); }      public void keyReleased(KeyEvent e) { System.out.println("2test2"); }      public void keyTyped(KeyEvent e) { System.out.println("3test3"); } });   When I run it, the test message comes up in my console. However, when I press a key, I don't get any of the other messages, as if the KeyListener was not even there.  I was thinking that it could be because the focus is not on the JFrame and so they KeyListener doesn't receive any events.  But, I'm pretty sure it is.  Is there something that I am missing?
3034
I am a beginner in learning selenium Webdriver. I am not able to understand how page object and factory models works and how it can be beneficial?    Kindly help me explain it with detailed explanation.
52188
I want to learn Selenium WebDriver automation using Java. I have done manual testing before and want to learn automation. I just know the basics of Core Java.   Could you please suggest me the Core topics which one would require to perform test automation using Selenium WebDriver?   What topics on which a tester must concentrate and what topics to ignore in java programming?
92671
public class ExampleClass {       public static void publishCaseUpdateNotifications(List&lt;Case&gt; cases) {     List&lt;Case_Updated__e&gt; notifications = new List&lt;Case_Updated__e&gt;();     for (Case c: cases) {         notifications.add(new Case_Updated__e(             Case__c = (String)c.Id,             CreatedByName__c = UserInfo.getName(),             CaseNumber__c = c.CaseNumber         ));     }       List&lt;Database.SaveResult&gt; results = EventBus.publish(notifications);      for (Database.SaveResult result : results) {         if (!result.isSuccess()) {             for (Database.Error error : result.getErrors()) {                 System.debug('Error returned: ' +                     error.getStatusCode() +' - '+                     error.getMessage());             }         }       }      }    }   My Test Class: getting error   @isTest   public class ExampleTestClass {    @isTest   static void testClassforExample(){         Case testcase = new Case(Subject ='Test',);      list&lt;Case_Updated__e&gt; caseUpdate =      ExampleClass.publishCaseUpdateNotifications(testcase );       }      }   My Error is Method does not exist or incorrect signature: void publishCaseUpdateNotifications(Case) from the type ExampleTestClass   Please suggest me how to resolve this error.     trigger Cases on Case (after insert) { if(Trigger.isAfter) {     System.debug('I will be replaced shortly!'); }  }   Do we need test class for above trigger. Please suggest me too