Visualforce 电子邮件模板单元测试

Visualforce email template unit test

我有一个使用 VF 模板发送电子邮件的触发器。我正在尝试为该代码编写一个单元测试,但在尝试创建测试数据时 运行 陷入了一个问题。
这是我的测试方法:

static TestMethod void testQuestionAttachment(){
    Id profileId = SYSTEM_ADMIN_PROFILE_ID;
    List<User> users = TestUtils.createUsers(profileId, 1);
    insert users;
    string templateText = '<messaging:emailTemplate subject="{!relatedTo.Name}" recipientType="User" relatedToType="Cutom_Object__c"><messaging:htmlEmailBody ><ul><li>test content</li></ul></messaging:htmlEmailBody></messaging:emailTemplate>';
    EmailTemplate template = new EmailTemplate(
        developerName = 'TestEmailVFTemplate', 
        TemplateType= 'visualforce', 
        FolderId = users[0].Id, 
        Name = 'TestEmailVFTemplate',
        IsActive = true);
    template.HtmlValue = templateText;
    template.Body = templateText;
    System.runAs(users[0]){
        insert template;
    }
    ...

它失败了FIELD_INTEGRITY_EXCEPTION, <messaging:emailTemplate> is required and must be the outermost tag in the markup at line 1 column 1: [Markup]
我真的不明白为什么这不起作用。我一定是遗漏了什么...

问题出在您的 TemplateType = 'Visualforce' 上。而是将其更改为 template.Markup=templateText;Markup 字段可用于分配 visualforce 模板的主体。我在测试中试过了class。 参考下面的例子:

static @isTest void myTest () { 
    Profile pf = [SELECT Id,Name FROM Profile WHERE Name = 'System Administrator' LIMIT 1];

    User usr = new User(
        Alias                 = 'usralias',
        Email                 = 'theuser@email.com',
        Emailencodingkey      = 'UTF-8',
        Lastname              = 'user_lastname',
        Languagelocalekey     = 'en_US',
        Localesidkey          = 'en_US',
        Profileid             =  pf.Id,
        Timezonesidkey        = 'America/Los_Angeles',
        Username              =  Math.random() + 'test@testuser.com',
        CompanyName           = 'the company',
        UserRoleId='00E28000000zqCy'
    );
    insert usr;
    string templateText = '<messaging:emailTemplate subject="{!relatedTo.Name}" recipientType="User" relatedToType="Custom_Object__c"><messaging:htmlEmailBody ><ul><li>test content</li></ul></messaging:htmlEmailBody></messaging:emailTemplate>';
    EmailTemplate template = new EmailTemplate(DeveloperName = 'TestEmailVFTemplate', TemplateType= 'Visualforce', FolderId = UserInfo.getUserId(),
    Name = 'TestEmailVFTemplate',
    IsActive = true);

    template.Markup=templateText;

    System.runAs(usr){
        insert template;
    }
}