2

Trying to get code coverage up and I am not understanding why this boolean value will not pass from the test method to the class. It always returns true.

Test Method:

  @isTest static void test_searchmorePages() {
    Test.startTest();
    CustomerController controller = new CustomerController();
    controller.standardSearch = false;
    controller.searchAdditional();
    controller.standardSearch = false;  
    controller.next();
    controller.clear();
    Test.stopTest();
}

Custom Controller:

public class CustomerController {
    public boolean standardSearch{get;set;}

public void searchAdditional() {
standardSearch = false;
}

public void next(){
     if (standardSearch = true) {
        system.debug('its true');
     }

     else {
         system.debug('its false');
     }
}

1 Answer 1

11
if (standardSearch = true) {

You are performing an assignment with = inside this if statement. Use == to compare for equality.

As a guard against this kind of mistake, you can write the constant first:

if (true == standardSearch) {

Then you get an error if you write the wrong number of = signs.

sfdxfox rightly notes that simply referencing Booleans without a comparison in a truth context, as if (standardSearch) or if (!standardSearch) is in many ways a better idiom that avoids this issue entirely. You may in a few cases want to make the comparison explicit as above - if you might have a null value, certainly, or in highly complex logical expressions where the more verbose form is more readable or clear.

The constant == variable pattern is one that applies equally in other contexts where you're making such a comparison against an lvalue (an expression to which a value may be assigned). For example,

if ('foo' == myStringVariable) {

if (2 == myIntegerVariable) {

if (2.0 == mySobjectList[1].Some_Currency_Field__c) {
2
  • That moment you realize everything you've ever created with a boolean conditional is wrong.
    – S.B.
    Commented May 25, 2018 at 22:24
  • 5
    My rule of thumb is to never compare a boolean to true or false: if(standardSearch) and if(!standardSearch) are the only form I use. I know people always say "but what about the nulls?!" to which I respond "My boolean values are never null. I initialize."
    – sfdcfox
    Commented May 25, 2018 at 23:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .