Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public with sharing class ValidationController
{
private ApexPages.StandardController standardController;
public ValidationController(ApexPages.StandardController standardController)
{
// Configure fields to query and valid (alternative to SOQL)
this.standardController = standardController;
if(!Test.isRunningTest())
this.standardController.addFields(
new List<String> { Schema.Test__c.A_Number__c.getDescribe().getName() });
}
public PageReference validate()
{
// Validate record
Test__c test = (Test__c) standardController.getRecord();
if(test.A_Number__c != 42)
test.A_Number__c.addError('Not the answer to life the universe and everything!');
// If no errors display confirmation message
if(!ApexPages.hasMessages())
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Info, 'All is well, go ahead and click Update.'));
return null;
}
public PageReference validateAndUpdate()
{
// Validate
validate();
if(ApexPages.hasMessages(ApexPages.Severity.Error))
return null;
// Update the record and call standard controller save
Test__c test = (Test__c) standardController.getRecord();
test.Date__c = System.today();
return standardController.save();
}
@IsTest
private static void testValid()
{
// Insert valid data
Test__c validRecord =
new Test__c(
A_Number__c = 42,
Date__c = System.today().addDays(-2));
insert validRecord;
// Invoke validateAndUpdate controller method
ValidationController controller =
new ValidationController(
new ApexPages.StandardController(validRecord));
PageReference pageRef = controller.validateAndUpdate();
// Assert messages and record
System.assert(ApexPages.hasMessages(ApexPages.Severity.Info));
System.assertEquals(ApexPages.getMessages().size(), 1);
System.assertEquals([select Date__c from Test__c where Id = :validRecord.Id].Date__c, System.today());
}
@IsTest
private static void testInvalid()
{
// Insert invalid data
Test__c invalidRecord =
new Test__c(
A_Number__c = 52,
Date__c = System.today().addDays(-2));
insert invalidRecord;
// Invoke validateAndUpdate controller method
ValidationController controller =
new ValidationController(
new ApexPages.StandardController(invalidRecord));
PageReference pageRef = controller.validateAndUpdate();
// Assert messages and record
System.assert(ApexPages.hasMessages(ApexPages.Severity.Error));
System.assertEquals(ApexPages.getMessages().size(), 1);
System.assertEquals([select Date__c from Test__c where Id = :invalidRecord.Id].Date__c, System.today().addDays(-2));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment