Skip to main content

Hello, there! I've checked all similar posts but still wasn't able to solve the problem. This is a pretty simple trigger from Trailhead:

trigger RestrictContactByName on Contact (before insert, before update) {

//check contacts prior to insert or update for invalid data

For (Contact c : Trigger.New) {

if(c.LastName == 'INVALIDNAME') { //invalidname is invalid

c.AddError('The Last Name "'+c.LastName+'" is not allowed for DML.');

}

}

}

This is my test class. The test class can get me 100% code coverage and the UI operation all works beautifully. The issue is the test result returned "System.AssertException: Assertion Failed" error at Line 15. Can anyone please explain to me why this is happening? Is it about Database opertion or DML statements? Thank you so much!

@isTest

private class TestRestrictContactByName {

@isTest static void TestLastNameIsvalid() {

// Test data setup

// Create a contact with a valid Last Name, and then try to insert/update it.

Contact c = new Contact (FirstName='Kathy',LastName='Smith',Department='Technology');

insert c;

// Perform test

Test.startTest();

Database.SaveResult result = Database.insert(c, false);

Test.stopTest();

// Verify

// In this case the insert/update should have been processed.

System.assert(result.isSuccess());

}

@isTest static void TestLastNameIsNotInvalid() {

// Test data setup

// Create a contact with a Last Name of 'INVALIDNAME', and then try to insert/update it.

Contact c2 = new Contact (FirstName='Joe',LastName='INVALIDNAME',Department='Finance');

insert c2;

// Perform test

Test.startTest();

Database.SaveResult result = Database.insert(c2, false);

Test.stopTest();

// Verify

// In this case the deletion should have been stopped by the trigger,

// so verify that we got back an error.

System.assert(!result.isSuccess());

System.assert(result.getErrors().size() > 0);

System.assertEquals('The Last Name "INVALIDNAME" is not allowed for DML.',

result.getErrors()[0].getMessage());

}

}

 
5 answers
  1. May 10, 2018, 8:49 AM
    Hi,

    Just remove the two extra "insert"

    insert c;

    insert c2;

    There are inserts twice each time and the second ones have an Id and failed .

    When you want to know the reasons, just add the code below:

    if (!result.isSuccess()) {

    // Operation failed, so get all errors

    for(Database.Error err : result.getErrors()) {

    System.debug('The following error has occurred.');

    System.debug(err.getStatusCode() + ': ' + err.getMessage());

    System.debug('Fields that affected this error: ' + err.getFields());

    }

    }

0/9000