I wrote a trigger to count the number of values in a multi-select picklist (custom_coins__c), if more than 10, error (too many coins selected). I'm new at writing code and can't figure out the test class. Any help is appreciated!

    trigger CustomCoins on OpportunityLineItem (before insert, before update) 
        for(Opportunitylineitem oli : trigger.new) {
            if(oli.Custom_Coins__c!= Trigger.oldmap.get(oli.id).Custom_Coins__c){
      List<string> coins = oli.Custom_coins__c.split(';');
            oli.Custom_Coins_Count__c   = coins.size();
                    oli.Custom_Coins__c.addError('Max of 10 coins for Module 4 Coins, please update selection) ');
                    oli.Custom_Coins_Count__c   = 0;

Test Class - 0 % coverage

public class CustomCoinsTest {

static testMethod void Customcoins() {
        Account acc = new Account(Name = 'Test');
insert acc;

Opportunity oppObj = new Opportunity(Name = 'TestOpp',AccountID = acc.Id,Amount = 2000,CloseDate=Date.today(),StageName='Close Won',Type='New Customer');
insert oppObj;

Product2 newProd = new Product2(Name = 'test product', family = 'test family');
insert newProd;

PriceBookEntry pbEntry = new PriceBookEntry(
    UnitPrice = 300,
    PriceBook2Id = [select id from PriceBook2 where isStandard = true].Id,
    Product2Id = newProd.Id,
    IsActive = true);

insert pbEntry ;

OpportunityLineItem oli = new OpportunityLineItem(
    Coins__c = 'Module 4 (custom selection)', 
    Custom_Coins__c = 'BTC (Bitcoin)',
    Quantity = 2,
    OpportunityID = oppObj.Id);
    System.debug('Coins before parsing Custom coins:' + oli.Custom_Coins_count__c);

   // insert oli
insert oli;


 //retrieve the new opp line
    oli = [SELECT Custom_coins_count__c FROM opportunitylineitem WHERE id = :oli.id ];
   system.debug('Coins after parsing custom coins:' + oli.Id);

// test that trigger correctly update Custom Coins
    system.assertEquals(12, oli.custom_coins_count__c);

1 Answer 1


Your trigger is coded to only take action if you perform a DML update operation:


But your unit test only performs an insert operation:

insert oli;

So the bulk of your trigger's code cannot execute in test context.

You need to either perform an update, or modify your trigger to take action upon insert, inasmuch as you are currently declaring a before insert event.

You must log in to answer this question.

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