0

我对编码相对缺乏经验,以前从未被迫编写测试类。我从概念上不理解它。我写了以下触发器:

trigger CreateNewInvoiceAndUpdateCM on CampaignMember(after insert, after update){
for (CampaignMember cm: trigger.new){

    if(cm.Status == 'Needs Renewal and Invoice'){
        Asset memb = [SELECT Id, Product2Id FROM Asset WHERE Id = :cm.Membership__c];
        Product2 prod = [SELECT Id, ProductCode FROM Product2 WHERE Id = :memb.Product2Id];
        Pricebook2 pb =[SELECT Id, Name FROM Pricebook2 WHERE Name = 'Standard Price Book'];
        PricebookEntry pbe = [SELECT Id, UnitPrice, Pricebook2Id, Product2Id FROM PricebookEntry WHERE Pricebook2Id = :pb.Id AND Product2Id = :prod.Id];

        Invoice__c inv = new Invoice__c();
        inv.Membership__c = cm.Membership__c;
        inv.Contact__c = cm.ContactId;
        inv.Price__c = pbe.UnitPrice;
        insert inv;



        CampaignMember newCm = [select Id, Invoice__c FROM CampaignMember WHERE Id = :cm.Id];
        newCm.Invoice__c = inv.Id;
        newCM.Status = 'Needs Renewal';
        update newCm;

        }}
        }

但是后来我不知道如何正确编写测试类。我浏览了 Salesforce 网站上的所有文档和无数帖子,但我的代码覆盖率未能从 13% (2/15) 提高 [顺便说一句,这是什么意思?]。

我写的测试类基本上只是试图把所有的东西都放进去,希望代码覆盖率会上升。我不知道我实际上应该对测试类做什么:

@isTest 

private class testCreateNewInvoiceAndUpdateCM{

static testMethod void testCreateNewInvoiceAndUpdateCM(){

PricebookEntry pbe = new PriceBookEntry();
pbe.UnitPrice = 2;

Campaign camp = new Campaign();
camp.Name = 'Test Campaign';
insert camp;

Account acc = new Account();
acc.Name ='Test Account';
insert acc;

Contact cont= new Contact();
cont.LastName = 'LastName';
cont.AccountId = acc.Id;
insert cont;


Asset ass = new Asset();
ass.Name = 'Test Asset';
ass.Membership_Start_Date__c = System.today();
ass.ContactId = cont.Id;
ass.AccountId = ass.Id;
insert ass;

Invoice__c inv = new Invoice__c();
inv.Membership__c = ass.Id;
inv.Contact__c = cont.Id;
inv.Price__c = pbe.UnitPrice;
insert inv;

CampaignMember cm = new CampaignMember(); 
cm.CampaignId = camp.Id;
cm.ContactId = cont.Id;
cm.Membership__c = ass.Id;
cm.Status = 'Needs Renewal and Invoice';
cm.Invoice__c = Inv.Id;

insert cm;


CampaignMember cm2 = [select Id, Status, Invoice__c  from CampaignMember where Id = :cm.Id];
System.assertEquals('Needs Renewal and Invoice',cm.Status);







   }
}

谁能帮帮我,这让我发疯了吗?

4

2 回答 2

1

在编写测试类之前,您需要重写触发器。你永远不要在 for 循环中查询。您还应该使用连接来最小化查询的数量。您应该查看 Apex 最佳实践指南。从这里开始:

http://wiki.developerforce.com/page/Apex_Code_Best_Practices

于 2013-12-17T18:04:20.377 回答
0

(2/15) 表示(触发器的)15 行中有 2 行通过了测试,您还有 13 行要测试,这意味着您的测试类代码没有涵盖这 13 行。你能指定你的触发器的哪两行通过了测试吗?这肯定有助于了解您的问题在哪里更好。

于 2013-11-15T17:13:47.420 回答