I am trying to write a test class for the following trigger:
trigger WebToCaseCountry on Case (after insert)
{
Set<String> countries = new Set<String>();
for (Case c : Trigger.new)
{
if (!String.isEmpty(c.CountryWebFormText__c) && c.Newsletter__c == TRUE)
{
countries.add(c.CountryWebFormText__c);
}
}
if (countries.size() > 0)
{
Set<String> filteredCountries = new Set<String>();
for (Area__c a : [select Name from Area__c where Name in :countries])
{
filteredCountries.add(a.Name);
}
if (filteredCountries.size() > 0)
{
Case[] caseUpdates = new Case[] {};
Contact[] contactUpdates = new Contact[] {};
for (Case c : Trigger.new)
{
if (filteredCountries.contains(c.CountryWebFormText__c))
{
caseUpdates.add(new Case(Id = c.Id, Country_of_Origin__c = c.CountryWebFormText__c));
if (c.ContactId != null)
{
contactUpdates.add(new Contact(Id = c.ContactId, Country__c = c.CountryWebFormText__c));
}
}
}
update caseUpdates;
update contactUpdates;
}
}
}
But I am getting an error with the insert statement when I try to execute it in Execute Anonymous. This is the error that I receive: "Line: 2, Column: 1 System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, WebToCaseCountry: execution of AfterInsert caused by: System.StringException: Invalid id: CA Trigger.WebToCaseCountry: line 28, column 1: []"
This is my Test Class at the moment:
@isTest public class WebToCaseCountryTest {
public static testMethod void testTrigger()
{
//Case c = new Case (Id = '500g000000CoMzp');
Case caseObj = new Case(//Id = c.Id,
CountryWebFormText__c ='CA', Newsletter__c = TRUE);
insert caseObj;
System.debug(caseObj);
System.assert(caseObj.Country_of_Origin__c == caseObj.CountryWebFormText__c);
}
}
Case.Country_of_Origin__c
and ID field instead of a text field?System.assertEquals(caseObj.Country_of_Origin__c, [select Id from Area__c where Name = :caseObj.CountryWebFormText__c].Id);
should work. But what you really need to do is read up a bit more about Id values and names in Salesforce and get how they work clear in your mind. But you will also need to insert theArea__c
object in the test unless you use the bad practice of@isTest(SeeAllData=true)
.