简体   繁体   English

Salesforce Apex 单元测试错误

[英]Salesforce Apex unit testing error

I am trying to create a Salesforce unit test for a new trigger I created.我正在尝试为我创建的新触发器创建 Salesforce 单元测试。

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.我是 Apex 的新手,我不知道如何解决这个问题。 Any Salesforce and Apex experts out there who can help?任何可以提供帮助的 Salesforce 和 Apex 专家? Thanks!谢谢!

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因为 casSubject 可能会查询不止一个 Case .... 你应该使用 List

The following line is causing issue :以下行导致问题:

Case ca = [SELECT Subject, ContactId from Case where Subject =: caseSubject]; 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';所以它有两个主题“SOS Video Chat”的记录;

If you change the Subject from 'SOS Video Chat' to any other String it will run successfully.如果您将主题从“SOS 视频聊天”更改为任何其他字符串,它将成功运行。

尝试为您的案例添加限制:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM