1

I am trying to create a Salesforce unit test for a new trigger I created.

trigger SOSCreateCaseCustom on SOSSession (before insert) {
    List<Event> aplist = new List<Event>();
    List<SOSSession> sosSess = Trigger.new;
    for (SOSSession s : sosSess) {
        try {
            Case caseToAdd = new Case();
            caseToAdd.Subject = 'SOS Video Chat';
            if (s.ContactId != null) {
                caseToAdd.ContactId = s.ContactId;
            } else {
                List<Contact> contactInfo = [SELECT Id from Contact WHERE Email = :s.AppVersion];
                if (!contactInfo.isEmpty()) {
                    caseToAdd.ContactId = contactInfo[0].Id;
                    s.ContactId = contactInfo[0].Id;
                }
            }
            insert caseToAdd; s.CaseId = caseToAdd.Id;
        }catch(Exception e){}
    }
}

Here is my unit test:

@isTest
private class SOSCreateCaseCustomTest {
    static testMethod void validateSOSCreateCase() {
        String caseSubject = 'SOS Video Chat';

        // set up case to add 
        SOSSession s = new SOSSession();
        insert s;

        Case caseToAdd = new Case(Subject='SOS Video Chat');
        caseToAdd.ContactId = s.ContactId;
        insert caseToAdd;

        Case ca = [SELECT Subject, ContactId from Case where Subject =: caseSubject];
        // Test that escaltion trigger correctly escalate the question to a case
        System.assertEquals(s.ContactId, ca.ContactId);
    }
}

I keep getting this error.

System.QueryException: List has more than 1 row for assignment to SObject

I am new to Apex and I have no idea how to fix this. Any Salesforce and Apex experts out there who can help? Thanks!

2 Answers 2

1

I think this one:

Case ca = [SELECT Subject, ContactId from Case where Subject =: caseSubject];

Because the casSubject may query more then one Case.... You should use List

Sign up to request clarification or add additional context in comments.

1 Comment

that's actually not the issue, I solved this with the help from the salesforce forum. Thanks anyway
1

The following line is causing issue :

Case ca = [SELECT Subject, ContactId from Case where Subject =: caseSubject];

It is returning two cases, the one you inserted in test data and other that is inserted by trigger. So it is having two records for Subject 'SOS Video Chat';

If you change the Subject from 'SOS Video Chat' to any other String it will run successfully.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.