2

I have a simple Apex trigger I'm trying to write a test for, but I get the error in the title when trying to save (error is at line 15 'insert n;'). I don't get this error in the line that inserts the lead. I've tried new Note() instead of passing through Note attributes and inserting the Note the same way I do the Lead, but nothing has worked so far, I feel like I'm overlooking a small syntax issue somewhere:

@isTest
public class TestNoteOnInsert {
    private static Id leadId;
    static {
        Lead testLead = new Lead();
        testLead.FirstName = 'Test first';
        testLead.LastName = 'Test last';
        testLead.Status = 'Open';
        testLead.Company = '100 test lane Brooklyn, NY';
        insert testLead;
        leadId = testLead.Id;
    }
    Note n = new Note(title='Sales Rabbit Note', body='Test', ParentId=leadId);
    Test.startTest();
    insert n;
    Test.stopTest();

    system.assertEquals(testLead.Notes__c, 'Test');
}

1 Answer 1

6

You can't put "executable" code outside of a method. Also, to actually have a unit test, you need a method marked with @isTest or testMethod. You also have a few other minor issues.

@isTest
public class TestNoteOnInsert {
    @isTest static void test() {
        Lead testLead = new Lead();
        testLead.FirstName = 'Test first';
        testLead.LastName = 'Test last';
        testLead.Status = 'Open';
        testLead.Company = '100 test lane Brooklyn, NY';
        insert testLead;
        Note n = new Note(title='Sales Rabbit Note', body='Test', ParentId=testLead.Id);
        Test.startTest();
        insert n;
        Test.stopTest();
        // REMEMBER: You have to query the data back from 
        // the database in order to see any changes.
        testLead = [SELECT Notes__c FROM Lead];
        // NOTE: Expected value should be first.
        system.assertEquals('Test', testLead.Notes__c);
    }
}

You must log in to answer this question.

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