Как написать модульный тест для ContentDocumentLink в качестве вложения EmailMessage? - PullRequest
0 голосов
/ 30 января 2019

У меня есть триггер EmailMessage (после вставки), я сделаю некоторые проверки вложений (обратите внимание, что мои вложения имеют ContentDocumentLink!)

Код выглядит следующим образом:

private static void doNotAllowProfilesSendEmailsWithAttachments(List<EmailMessage> newMessages) {

        if (!validateCurrentUserRule()) {
            System.debug('====User without the permission===');
            String digitalSignature = [SELECT CA_Digital_Signature__c FROM User WHERE Id = :UserInfo.getUserId()][0].CA_Digital_Signature__c;
            System.debug('===digitalSignature===='+digitalSignature);
            System.debug('===newMessages===='+newMessages);
            Set<String> msgIdSet = new Set<String>();
            Map<String, Set<String>> attMap = new Map<String, Set<String>>();
            for(EmailMessage msg:newMessages){
                msgIdSet.add(msg.Id);
            }
            System.debug('===msgIdSet===='+msgIdSet);
            for(ContentDocumentLink cdl :[SELECT Id, LinkedEntityId, ContentDocumentId, ContentDocument.title FROM ContentDocumentLink where LinkedEntityId IN :msgIdSet]){
                if(!attMap.containsKey(cdl.LinkedEntityId)){
                    attMap.put(cdl.LinkedEntityId, new Set<string>());
                }
                attMap.get(cdl.LinkedEntityId).add(cdl.ContentDocument.title);
            }
            System.debug('===attMap===='+attMap);
            for(EmailMessage msg:newMessages){
                if(msg.Incoming == FALSE){
                    for(String title : attMap.get(msg.Id)){
                        if(!digitalSignature.contains(title)){
                            msg.addError('You may not include an attachment in outbound emails.');
                            break;
                        }
                    }
                }
            }
        }
    }

А вот мой модульный тест моего триггера:

@IsTest
    public static void doNotAllowProfilesSendEmailsWithAttachments_TestWrong() {

        String[]emails = new String[]{
                'wei.dong@pwc.test'
        };
        Boolean isSentSuccessful = true;

        // Test when we attach an attachment with 'Stand User'
        Profile p = [SELECT Id FROM Profile WHERE Name = 'Consumer Care Agent'];
        User u = new User(Alias = 'standt', Email = 'standarduser@testorg.com',
                EmailEncodingKey = 'UTF-8', LastName = 'Testing', LanguageLocaleKey = 'en_US',
                LocaleSidKey = 'en_US', ProfileId = p.Id,
                TimeZoneSidKey = 'America/Los_Angeles',
                UserName = 'standarduser_dongwei_test@testorg.com');

        Test.startTest();

        System.runAs(u) {

            // Insert a new contact for inner search contact ID
            Contact newContact = new Contact();
            newContact.LastName = 'Last Name';
            insert newContact;

            // 1. Create a Document as an attachment
            Document doc = new Document();
            doc.Name = 'Test document';
            doc.Body = Blob.valueOf('Test me');
            doc.ContentType = 'text/plain';
            doc.Type = 'txt';
            doc.FolderId = UserInfo.getUserId();
            insert doc;

            // 2. Preparing to attach the attachment
            Messaging.EmailFileAttachment file = new Messaging.EmailFileAttachment();
            file.setContentType('application/txt');
            file.setFileName('testAttachment.txt');
            // Make this as an attachment
            file.setInline(false);
            file.Body = doc.Body;


            // 3. Successfully sent
            Map<String, String> replacers = new Map<String, String>();
            replacers.put('dongwei', '');
            isSentSuccessful = CA_Utility.sendSingleEmail(emails,
                    'Test', 'Test body',replacers, 'DongWei',
                    true, new Messaging.EmailFileAttachment[]{
                            file
                    });
            System.assert(isSentSuccessful);

            EmailMessage email = new EmailMessage();
            email.FromAddress = 'test@abc.org';
            email.Incoming = True;
            email.ToAddress = 'test@xyz.org';
            email.Subject = 'Test email';
            email.HtmlBody = 'Test email body';

            Blob beforeblob = Blob.valueOf('Unit Test Attachment Body');

            ContentVersion cv = new ContentVersion();
            cv.title = 'Bad Signature Here';
            cv.PathOnClient = 'test';
            cv.VersionData = beforeblob;
            insert cv;

            ContentVersion testContent = [SELECT id, ContentDocumentId FROM ContentVersion where Id = :cv.Id];

            ContentDocumentLink contentlink = new ContentDocumentLink();
            contentlink.LinkedEntityId = email.Id;
            contentlink.ShareType = 'V';
            contentlink.ContentDocumentId = testcontent.ContentDocumentId;
            contentlink.LinkedEntityId = email.Id;

            email.ContentDocumentLinks.add(contentlink);
            insert email;
        }

        Test.stopTest();
    }

Что меня удивляет, так это то, что покрытие не хорошее, потому что я всегда не могу ввести 'for' для ContentDocumentLink.Итак, как написать единое целое с ContentDocumentLinks вместе, чтобы улучшить покрытие?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...