Trying to implement some small test cases in my Android application, but at the moment i have some trouble getting the test class to find the fragment.  Here is my Activity that just create my fragment.  public class DetailActivity extends FragmentActivity {     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_detail);        Intent intent = getIntent();        Bundle bundle = new Bundle();        bundle.putParcelable("match", intent.getParcelableExtra("match"));        DetailFragment fragment = new DetailFragment();        fragment.setArguments(bundle);        if (savedInstanceState == null) {           getSupportFragmentManager().beginTransaction()                   .add(R.id.container, fragment, "test")                   .commit();        }    } }   And my fragment looks like this.  public class DetailFragment extends Fragment {    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                          Bundle savedInstanceState) {        context = getActivity().getApplicationContext();       mh = getArguments().getParcelable("match");        int id = context.getResources().getIdentifier(               "c" + String.valueOf(mh.getChampionImage()),               "drawable", context.getPackageName()       );     }      @Override     public void onStart() {       super.onStart();       if (Utility.hasNetworkConnection(context)) {          FetchIcons fetchIcons = new FetchIcons();          fetchIcons.execute(mh);       }     }  ...//Some Code   My test looks like this.  public class DetailFragmentTest extends ActivityUnitTestCase&lt;DetailActivity&gt; {     DetailActivity activity;    DetailFragment fragment;     public DetailFragmentTest() {        super(DetailActivity.class);    }     @Override    protected void setUp() throws Exception {       super.setUp();       Intent intent = new Intent(new MockContext(), DetailActivity.class);       int[] i = {1, 2, 3, 4, 5, 6, 7};       MatchHistory mh = new MatchHistory("Win", "23", "42", "31", "23414", "321", 22, true, i);       intent.putExtra("match", mh);       startActivity(intent, null, null);       activity = getActivity();       fragment = (DetailFragment) activity.getSupportFragmentManager().findFragmentByTag("test");     }     public void testText() {     ...//Some more code    } }   Everything up to the part where i'm trying to receive the framgent works fine, but gives me NullPointerException as soon as i try to fetch it.  And my stacktrace doesn't shed much light on the problem.  java.lang.NullPointerException at com.plushogskolan.chobi.matchhistory.DetailFragmentTest.setUp(DetailFragmentTest.java:34) at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:86) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)   Been trying to solve it using several different methods, including just the ActivityInstrumentationTestCase2, but then i can't even get the Activity.  I'm clearly doing something wrong. But since not a single tutorial for unit testing in android have yielded any luck i can at least give it a shot here and see if anyone knows what the problem is.  Regards!
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?
107559
I am adding cookie to my page in the controller using  ApexPages.currentPage().setCookies(new Cookie[]{CookieName});  When am trying to get the code coverage, my test class is not covering the above line.  How to get the code coverage for the above setcookie method in the test class.
79593
I have a lightning component that displays Knowledge Articles based on Topic IDs that it is configured for. This works great so I went to create my test coverage for it and discovered that the inserted test Knowledge Articles can only ever be 'Draft' making my tests fail since the apex class only looks for 'Online'. Instead of rewriting my component I decided to overload the apex method so that when called without the status parameter it passes in 'Online' allowing my tests to pass in 'Draft' instead. However, the first method signature does not get called from the component resulting in null for the status parameter.  Here is the component controller:  ({     "retrieveArticles" : function(component, event, helper) {         var action = component.get("c.returnArticlesWithTwoTopicIds");         action.setParams({             mainTopicId : component.get("v.mainTopicId"),             secondaryTopicId : component.get("v.secondaryTopicId"),             limitAmount : component.get("v.limitAmount")         });          action.setCallback(this, function(response) {             var state = response.getState();             if (component.isValid() &amp;&amp; state === "SUCCESS") {                 // handle SUCCESS             }             else if (component.isValid() &amp;&amp; state === "ERROR") {                 // handle ERROR             }         });         $A.enqueueAction(action);     } })   Here is the apex class:  public with sharing class KnowledgeArticleVersionCtrl {     @AuraEnabled     public static List&lt;KnowledgeArticleVersion&gt; returnArticlesWithTwoTopicIds(String mainTopicId, String secondaryTopicId, Integer limitAmount) {         return returnArticlesWithTwoTopicIds(mainTopicId, secondaryTopicId, limitAmount, 'Online');     }      @AuraEnabled     public static List&lt;KnowledgeArticleVersion&gt; returnArticlesWithTwoTopicIds(String mainTopicId, String secondaryTopicId, Integer limitAmount, String status) {         // build query string         List&lt;KnowledgeArticleVersion&gt; articles = Database.query(query);         return articles;     } }   Is there something about the component that would cause it to not use the first signature, the one it should match, in place of the second one, which it shouldn't match?
122316
I am trying to do this:   Below is the screenshot taken from eclipse  package com.stack.tests;  import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxProfile;  public class PerformanceTesting {        public static void main(String[] args) {             FirefoxProfile profile = new FirefoxProfile();             WebDriver driver = new FirefoxDriver(profile);             driver.quit();         } }   Below is the error code taken while running:  E:\stackoverflow\src\test\java\com\stack\tests&gt;javac -cp selenium-serv er-standalone-2.52.0.jar PerformanceTesting.java  E:\stackoverflow\src\test\java\com\stack\tests&gt;set classpath=%classpat h%;.;  E:\stackoverflow\src\test\java\com\stack\tests&gt;java -cp .;selenium-ser ver-standalone-2.52.0.jar PerformanceTesting Exception in thread "main" java.lang.NoClassDefFoundError: PerformanceTesting (w rong name: com/stack/tests/PerformanceTesting)         at java.lang.ClassLoader.defineClass1(Native Method)         at java.lang.ClassLoader.defineClass(Unknown Source)         at java.security.SecureClassLoader.defineClass(Unknown Source)         at java.net.URLClassLoader.defineClass(Unknown Source)         at java.net.URLClassLoader.access$100(Unknown Source)         at java.net.URLClassLoader$1.run(Unknown Source)         at java.net.URLClassLoader$1.run(Unknown Source)         at java.security.AccessController.doPrivileged(Native Method)         at java.net.URLClassLoader.findClass(Unknown Source)         at java.lang.ClassLoader.loadClass(Unknown Source)         at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)         at java.lang.ClassLoader.loadClass(Unknown Source)         at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)   Does somebody know how to fix it?
72722
getRealPath() is returning the actual path in the local system, but returns null when deployed with a .war file.  &lt;%@ page import="java.io.*" %&gt; &lt;%@ page contentType="text/html;charset=ISO-8859-1" %&gt;  &lt;% int iLf = 10; char cLf = (char)iLf; String a= application.getResource("/"); //String myfile = application.getRealPath("/")+ "generate.xml"; //String myfile = request.getContextPath()+"generate.xml"; //String myfile = request.getRealPath("/")+"generate.xml";  out.println(myfile);     File outputFile = new File(myfile); outputFile.createNewFile(); FileWriter outfile = new FileWriter(outputFile); outfile.write(" &lt;?xml version='1.0' encoding='UTF-8'?&gt; "+cLf); outfile.write(" &lt;playlist version='1' xmlns = 'http://xspf.org/ns/0/' &gt; " +cLf); outfile.write(" &lt;title&gt;My Band Rocks Your Socks&lt;/title&gt; "+cLf);  outfile.write("&lt;trackList&gt;"+cLf);  %&gt;  &lt;%! String[] sports; %&gt;  &lt;%     sports = request.getParameterValues("sports");      out.println("&lt;html&gt;&lt;body&gt;&lt;h1&gt;hello&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;");      if (sports != null)     {           for (int i = 0; i &lt; sports.length; i++)          {                // outfile.writeln (sports[i]);                String total=sports[i];               String[] sa=total.split("[,]");               // String[] sub=new String();               outfile.write("&lt;track&gt;"+cLf);               for (int j=0;j&lt;sa.length;j++)               {                 // outfile.writeln(sa[j]);                 // outfile.writeln("sa["+j+"]="+sa[j]);                 if( j == 0)                 {                      outfile.write("&lt;location&gt;" + sa[0] +"&lt;/location&gt;"+cLf);                  }                 else if (j == 1)                      {                         outfile.write("&lt;image&gt;" + sa[1] +"&lt;/image&gt;"+cLf);                       }                      else if( j==2)                           {                             outfile.write("&lt;title&gt;" + sa[2] +"&lt;/title&gt;"+cLf);                           }                 }// end of inner for loop()                       outfile.write("&lt;/track&gt;"+cLf);          //outfile.writeln();       }// end of outer for()     }      //else outfile.writeln ("&lt;b&gt;none&lt;b&gt;");    outfile.write(" &lt;/trackList&gt; "+cLf);   outfile.write(" &lt;/playlist&gt; "+cLf);   outfile.close();    %&gt; &lt;object type="application/x-shockwave-flash" width="400" height="170"           data="xspf_player.swf?playlist_url=generate.xml"&gt;           &lt;param name="movie" value="xspf_player.swf?playlist_url=generate.xml" /&gt;  &lt;/object&gt;   Can anyone provide me with an alternative for this? It would be very helpful if you showed some sample code too.
120241
I'm using data faker and I would like to know how to make my variables available in all steps of my test.  I wanted to leave all elements mapped in the initial step, or be given  WebDriver driver = new ChromeDriver();     //Mapping the elements  WebElement nomeusuario = driver.findElement(By.className("whsOnd zHQkBf"));   My main code is:  public class Criar_Conta_Gmail {  @Given("^que eu esteja na pagina principal do gmail\\.$") public void que_eu_esteja_na_pagina_principal_do_gmail() throws Throwable {     System.setProperty("webdriver.chrome.driver","C:\\Browsers\\chromedriver.exe");     WebDriver driver = new ChromeDriver();     driver.get("https://www.gmail.com");     driver.findElement(By.xpath("//span[contains(text(),'Criar conta')]")).click();     Thread.sleep(2000);     driver.findElement(By.xpath("//div[contains(text(),'Para mim')]")).click();     throw new PendingException();   }  @When("^criar uma nova conta com telefone invalido\\.$") public void criar_uma_nova_conta_com_telefone_invalido() throws Throwable {         WebDriver driver = new ChromeDriver();         //Mapping the elements      WebElement nomeusuario = driver.findElement(By.className("whsOnd zHQkBf"));      // sending data to the application     Faker faker = new Faker();     String Nome = faker.name().firstName();     nomeusuario.sendKeys(Nome);      throw new PendingException(); }  @Then("^o sistema não permite a finalização do cadastro\\.$") public void o_sistema_não_permite_a_finalização_do_cadastro() throws Throwable  {     // Write code here that turns the phrase above into concrete actions     throw new PendingException(); }
18034
when i try to save the following code, i got the error below. Following same instructions given in this link, but still errors. Am i doing anything wrong here? please suggest.    @isTest private class WebSvcCalloutTest {     @isTest static void testEchoString() {         Account a = new Account(name='Tester',SAP_KUNNR__c='1172');         insert a;                       // This causes a fake response to be generated         Test.setMock(WebServiceMock.class, new WebServiceMockImpl());      } }   Error:  Save error: Method does not exist or incorrect signature: Test.setMock(Type, WebServiceMockImpl)    WebSvcCalloutTest.cls         @isTest global class WebServiceMockImpl implements WebServiceMock {    global void doInvoke(            Object stub,            Object request,            Map&lt;String, Object&gt; response,            String endpoint,            String soapAction,            String requestName,            String responseNS,            String responseName,            String responseType) {          sapComDocumentSapSoapFunctionsMcS.Z_GSSMWFM_HNDL_EVNTRQST00 sap1 = new sapComDocumentSapSoapFunctionsMcS.Z_GSSMWFM_HNDL_EVNTRQST00();                Map&lt;String,String&gt; mapSAP = new Map&lt;String,String&gt; {};         sapComDocumentSapSoapFunctionsMcS.ZgssmbstDatarcrd01 req = new sapComDocumentSapSoapFunctionsMcS.ZgssmbstDatarcrd01();               sapComDocumentSapSoapFunctionsMcS.ZGssmwfmHndlEvntrqst00Response_element ret =  sap1.ZGssmwfmHndlEvntrqst00('',req);         response.put('response_x', ret);     } }
48842
I'm creating my first full framework using Selenium and TestNG and recently implemented the ability to have logging enabled which will track every action (before and after).  public class CustomLogs {     //Set Logging_Level to "Debug" to enable logging     public String Logging_Level = "OFF";      public void Log(String message) {         if (Logging_Level == "Debug")         {System.out.println(message);         } else {         }     } }   Then, in my page objects, EVERY action method has a log statement before and after EVERY action.  public class LoginPage extends BrowserConfig {      final WebDriver driver;     private static CustomLogs customlogs = new CustomLogs();      //Elements on Page     @FindBy(id = "userId")     private WebElement userNameField;      //Constructor     public LoginPage(WebDriver driver) {         this.driver = driver;     }      //Fill Username     public void FillUsername(String userNameEntry) {         userNameField.clear();         customlogs.Log("Entering Username: "+userNameEntry+"...");         userNameField.sendKeys(userNameEntry);         customlogs.Log("Username entered.");   It seems like this is very beneficial, not only for debugging, but also because you can now print out every single action step, so keeping records or showing others what steps were completed is very straightforward.  But I can also see how this is cluttering the page object code.  Is this a good idea?  And/or is there a better way to do this?
7576
I have a lookup to a custom object called Project on my Opportunity object. I am trying to write a trigger that updates an Active, Awarded, and Title on the Project object whenever the Active, Awarded, or Title field is updated on Opportunity based some on more logic that isn't in my code below. This is my first trigger and needing a little help due to a NullPointerException where I try to set Project__r.Active__c = true. Any thoughts?      trigger ProjectFieldsTrigger on Opportunity (before insert, before update) {       //List&lt;Opportunity&gt; opp = [SELECT Name, Active__c, Funded__c, Title__c, Project__r.Name, Project__r.Active__c, Project__r.Awarded__c      //  FROM Opportunity WHERE Id IN :Trigger.New];      for(Opportunity o: Trigger.New){          if(o.Project__c != null){              if(o.Active__c == 'Y'){                 o.Project__r.Active__c = true;             }      }  }
74927
I'm getting this error:  javax.servlet.ServletException: bean not found within scope   on a page with this at the top.  &lt;jsp:useBean id="bean" type="com.example.Bean" scope="request" /&gt;   The class exists in the classpath, it worked this morning, and I don't get what not found within scope means.  How is this caused and how can I solve it?
12761
I am using a similar format for a trigger and helper class.  Can anyone help me with a test class? Trigger Trigger TestOrders on Order (Before Insert)  {     IF(Trigger.IsBefore)     {         IF(Trigger.IsInsert)         {             OrderTriggerHelper.UpdateAccount(Trigger.New);         }     } }    Trigger Class Public Class OrderTriggerHelper {     Public Static Void UpdateAccount(List&lt;Order&gt; OrderIds)     {         List&lt;Account&gt; AccList = [Select Id,Ship_To_Code__c from Account where Ship_To_Code__c != NULL];          IF(AccList != NULL)         {             FOR(Account A : AccList)             {                 FOR(Order O : OrderIds)                 {                     //To check the Case-sensitivity.                     String S1 = A.Ship_To_Code__c;                     String S2 = O.Ship_to_code_del__c;                     IF(S1.Equals(S2))                     {                         O.SFDC_Account_Name__c = A.Id;                     }                 }             }         }     } }
41937
I need to read a properties files that's buried in my package structure in com.al.common.email.templates.  I've tried everything and I can't figure it out.  In the end, my code will be running in a servlet container, but I don't want to depend on the container for anything. I write JUnit test cases and it needs to work in both.
52661
I know there is a difference between assert and verify in Junit; the assert results in a runtime exception, causing test method execution to abort. To overcome this problem, we can have verify which will make test case fail, but allowing test execution to proceed rather than getting aborted.  I doubt there is any such built in approach in testNG. I do understand that best practices say, there should not be multiple asserts in same test case.  But, in practical world, we do come across scenarios where we need to have multiple checkpoints in one test case and we don't want our test method to abort because of one check point failure (test execution should proceed despite failure).  How can we use a soft assert mechanism, similar to verify, which will not abort test method when there is a checkpoint failure.  Example:  @Test(dataProvider = "getMailUrl") public void testMail(email,subject); Assert.assertFalse(subject.isEmpty);//1st checkpoint Assert.assertNotNull(email); //2nd checkpoint Assert.assertEquals(email, "feedback@yoursite.com"); //3rd checkpoint   Now, I want test execution to proceed, even if the 1st checkpoint (validation of subject being not empty) fails. Definitely we will be not be using assert (hard assert). We will need concept of soft assert similar to verify (facilitated by Junit).   I understand, we have to build a customListener implementing TestNG interfaces or extending existing listeners such as TestListenerAdapter. I am still struggling - how can we do this?
77237
I am unable to cover the following class get set method. Need help in creating test class  public class Aresult{      public class Parent {         public String type {get; set;}         public String id {get; set;}         public String sequence_id {get; set;}         public String etag {get; set;}         public String name {get; set;}     } }   Please suggest  @isTest  public class CirriusGetItemsResultTest {     public static void myUnitTest(){         Aresult.parent a = new Aresult.parent();         a.type='hello';         a.id='hello';         a.sequence_id ='hello';         a.etag ='hello';         a.name ='hello';     } }
106675
If you're writing a library, or an app, where do the unit test files go?    It's nice to separate the test files from the main app code, but it's awkward to put them into a "tests" subdirectory inside of the app root directory, because it makes it harder to import the modules that you'll be testing.    Is there a best practice here?
61126
I am getting java.lang.NullPointerException while executing my test case , I am using Page Object Modle with PageFactory ,following are the code snippets  LoginPageObjec.java  public class LoginPageObjects {      @FindBy(xpath=".//*[@id='userName']")     private WebElement email;      @FindBy(xpath=".//*[@id='password']")     private WebElement password;      @FindBy(xpath=".//*[@id='loginFormSubmit']")     private WebElement loginBtn;      public void EnterUserName(String userName)     {         email.sendKeys(userName);     }      public void EnterPassword(String pass)     {         password.sendKeys(pass);     }      public void clickLogin()     {         loginBtn.click();     }   }   LoginTC.java  public class LoginTC extends BasePage{     private WebDriver driver;      @Test     public void login()     {         LoginPageObjects loginPage = PageFactory.initElements(driver, LoginPageObjects.class);         loginPage.EnterUserName("test.hr@domin.com.pk");         loginPage.EnterPassword("test");         loginPage.clickLogin();     } public void login1()         {             LoginPageObjects loginPage = PageFactory.initElements(driver, LoginPageObjects.class);             loginPage.EnterUserName("test.hr@domin.com.pk");             loginPage.EnterPassword("test");             loginPage.clickLogin();         }  }   BasePage.java  public class BasePage {     private WebDriver driver;      @BeforeMethod       public void initializeBrowser() {      driver=new FirefoxDriver();      driver.navigate().to("https://nexthrm-dev.vteamslabs.com/");      driver.manage().window().maximize();      }     @AfterMethod     public void closeBrowser()     {         driver.close();     }  }   I've extended BasePage class to utilize the (initialBrowser &amp; closeBrowser) functions in my test case but its producing nullpointer exception if I copy both of the functions (initialBrowser &amp; closeBrowser) into my LoginTC (testcase class) it works like charm but I dont want this redundant code i.e((initialBrowser &amp; closeBrowser) for all my testcases class could anyone explain why I am getting nullpointer exception
42604
here is my code in which i am trying to get the product name from opportunity line item but its returning back NULL value. can anyone please help me to get that product name. I can get id from product2 but i want the name of product so that i can abbreviate it and can store it in Order_Name__c field of orderItem. After adding the product only i am firing this trigger.     public class Procuct_Adding_To_Order{  public static void productOrder(List&lt;OpportunityLineItem&gt; oli){     system.debug('-----------------------');      set&lt;id&gt; prodset = new set&lt;Id&gt;(); for(OpportunityLineItem item : oli) {   prodSet.add(item.product2id); } // collect products Map&lt;Id, product2&gt; prodMap = new Map&lt;Id, Product2&gt;([select name from product2 where id in :prodSet]);   // create a map for OLIid &amp; corresponding Product Name Map&lt;Id, string&gt; OLIprodMap = new Map&lt;Id, string&gt;();  for(OpportunityLineItem item : oli) {  OLIprodMap.put(item.id, OLIprodMap.get(oli.product2id).name); //getting Error in this line. }      set&lt;Id&gt; setOppId = new set&lt;Id&gt;();      for(OpportunityLineItem obj: oli){          setOppId.add(obj.OpportunityId);      }      list&lt;opportunity&gt; needed = [Select Master_Opportunity__c from opportunity Where Opportunity.id =: setOppId];         List&lt;OrderItem&gt; orderIt = new List&lt;OrderItem&gt;();     for(Order ord: [Select id from Order where opportunityId =: needed[0].Master_Opportunity__c])       {        for(OpportunityLineItem o : oli)        {           OrderItem op = new OrderItem();          op.Opportunity_del__c = needed[0].Master_Opportunity__c;          op.orderId = ord.id;         op.Order_Name__c = o.product2Id;         system.debug('-----------------------3333333333333333333333'+ o.Product2Id);         op.PriceBookEntryId = o.PriceBookEntryId;         op.Quantity = o.Quantity;         op.UnitPrice = 100;         orderIt.add(op);            }          }     upsert orderIt;  } }