0

How can I run a unit test on my controller constructor if it contains the following:

originObjectIdString = ApexPages.currentPage().getParameters().get('Id');

When I run the tests, I get an error that the "Argument cannot be null"

3
  • 1
    That line is not the source of the error. – Adrian Larson Jul 15 '16 at 20:12
  • You would get the line number also? Line x column y – Ashwani Jul 15 '16 at 20:12
  • @AdrianLarson the error could be coming because the string variable is null in a subsequent line, where it is actually needed. – Sebastian Kessel Jul 15 '16 at 20:35
2

In this case, you would have to write your test following a pattern like this

Account testAcct = new Account(Name = 'My Account For Testing');
insert testAcct;

PageReference thePage = Page.YourVFPage
thePage.getParameters().put('id', testAcct.id);

Test.setCurrentPage(thePage);

Test.StartTest();

<do your thing here>

Test.StopTest();
5
  • Thanks - what if the ID needs to be the ID of an account, or contact. Do I first need to insert a record before I can do as you suggest? – user1813867 Jul 15 '16 at 20:37
  • Absolutely, while it is possible to write a test that depends on existing data, it is extremely bad practice to do so. I'll make sure the code shows a basic example. – Sebastian Kessel Jul 15 '16 at 20:38
  • Thanks! Can you also clarify what is the reason for "StartTest" "StopTest"? What type of code should be inside those blocks and what type of code should be outside? – user1813867 Jul 15 '16 at 20:39
  • All the actual testing you do should be inside the "Start" and "stop". Your assertions can be outside. The setup information should also be outside. This pattern gives you more limits to do what you need. For more info, read here: developer.salesforce.com/docs/atlas.en-us.apexcode.meta/… – Sebastian Kessel Jul 15 '16 at 20:41
  • By the way, if (and only if) this fixes your problem, please mark the solution as accepted so others can benefit. – Sebastian Kessel Jul 15 '16 at 20:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.