In an Apex class, I've got a simple Boolean
that sets itself to either true
or false
depending on whether the field (Picklist) Candidate_Type__c
is equal to:
- Contract/Interim
- Permanent
See below:
public Boolean isContractInterim {
get {
if (isContractInterim == null) {
String candidateType = [SELECT Candidate_Type__c FROM Contact WHERE Id = :con.Id].Candidate_Type__c;
if (candidateType == 'Contract/Interim') {
isContractInterim = true;
}
else {
isContractInterim = false;
}
}
return isContractInterim;
}
set;
}
To quickly write a unit test for this, in the @testSetup
annotated method I used the following:
Contact con = new Contact(
FirstName = 'Joe',
LastName = 'Allen',
Candidate_Type__c = 'Contract/Interim'
);
INSERT con;
And ran this unit test:
@isTest static void test_is_contract_interim() {
Contact con = [SELECT Id, Candidate_Type__c FROM Contact WHERE Name = 'Joe Allen'];
System.debug('@@@@@@@@@@ ' + con);
LatestCandidatePrescreenCont controller = new LatestCandidatePrescreenCont(new ApexPages.StandardController(con));
System.assertEquals(true, controller.isContractInterim);
}
What's strange here is that con
only seemed to debug the Id
and not Candidate_Type__c
(as though it's somehow not being set?) and the assertion failed citing it was false
when I was expecting true
.
I've managed to get around this by removing the Candidate_Type__c = 'Contract/Interim'
line from @testSetup
and instead performing an UPDATE
DML inside the method which ultimately passes it:
@isTest static void test_is_contract_interim() {
Contact con = [SELECT Id, Candidate_Type__c FROM Contact WHERE Name = 'Joe Allen'];
con.Candidate_Type__c = 'Contract/Interim';
UPDATE con;
System.debug('@@@@@@@@@@ ' + con);
LatestCandidatePrescreenCont controller = new LatestCandidatePrescreenCont(new ApexPages.StandardController(con));
System.assertEquals(true, controller.isContractInterim);
}
I'm stumped here though as to why I have to update it to get it to return what I expect?