测试类失败

时间:2013-02-28 19:21:38

标签: class testing salesforce apex-code

我正在处理此处发布的解决方案:http://mysalesforcecode.blogspot.com/2012/09/how-to-copy-record-owner-from-cloning.html

按钮和触发器的工作方式与预期一致,但由于我的测试中第二个系统断言,我一直在测试失败(测试机会所有者是否按照原始所有者字段保留。我是一个顶级新手,所以我可能会做一些明显错误的事情......希望如此 - 谢谢!

按钮:

{!URLFOR( $Action.Opportunity.Clone,Opportunity.Id,     
[cloneli=1,opp11='Prospecting',opp12='10',opp9= 
TEXT(MONTH(Opportunity.CloseDate))+"/" 
+TEXT(DAY(Opportunity.CloseDate))+"/" 
+TEXT(YEAR(Opportunity.CloseDate)+1) 
])}&00NZ0000000kfYf={!Opportunity.OwnerId}&retURL={!Opportunity.Id}

触发器(根据以下答案更新):

trigger OwnerIdChange on Opportunity (before insert)
{
 for(Opportunity o : Trigger.new)
 {
  if(o.OriginalOwner__c != null)
     o.OwnerId = o.OriginalOwner__c;
 }
}

测试类:

@istest
private class Opportunities_Test {

    static testMethod void Opportunities_Test1() {
    test.starttest();

      Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
      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@testorg.com');
      insert u;

      Profile s = [SELECT Id FROM Profile WHERE Name='System Administrator'];
      User u2 = new User(Alias = 'admin', Email='admin@testorg.com',
      EmailEncodingKey='UTF-8', LastName='Testing2', LanguageLocaleKey='en_US',
      LocaleSidKey='en_US', ProfileId = s.Id,
      TimeZoneSidKey='America/Los_Angeles', UserName='admin@testorg.com');
      insert u2;

     Account a = new account(Name = 'Test1');
     insert a;

     List <Opportunity> Opportunity;
            Opportunity O1 = new Opportunity();
            O1.ownerid = u.id;
            O1.accountid = a.id;
            O1.Amount= 1;
            O1.CloseDate = Date.today();
            O1.Name = 'Testing';
            O1.StageName= 'Prospecting';
            insert O1;

 Account b = new account(Name = 'Test2');
 insert b;

      List <Opportunity> Opportunity2;
        Opportunity O2 = new Opportunity();
        O2.accountid = b.id;
        O2.ownerid = u.id;
        O2.Amount= 1;
        O2.CloseDate = Date.today();
        O2.Name = 'Testing2';
        O2.StageName= 'Prospecting';
        O2.OriginalOwner__c= u2.id;
        insert O2;  


List<Opportunity> z = [SELECT Id, Ownerid, Name FROM Opportunity WHERE id= :O2.id];

 system.assertEquals(O1.ownerid, u.id);
 system.assertEquals(O2.OwnerID, u2.id);

     test.stoptest();          
    }
}

1 个答案:

答案 0 :(得分:1)

您的触发逻辑有点疯狂,请尝试将其更改为以下内容,看看是否会得到不同的结果。

trigger OwnerIdChange on Opportunity (before insert)
{
   for(Opportunity o : Trigger.new)
   {
      if(o.OriginalOwner__c != null)
         o.OwnerId = o.OriginalOwner__c;
   }
}

编辑:根据下面的评论,还应该指出他在插入和更新记录后没有得到记录的更新值。重新查询机会记录并根据返回的值断言。