基于某些条件在触发器中调用Apex类。测试类通过测试但代码覆盖率为0%

时间:2017-01-24 16:30:29

标签: apex

当工作订单更新为已完成时,需要使用工作订单中的两个字段值和另一个对象att中的两个字段值创建新的水表读数记录。工作订单和水表读数都有一个查询(工作订单)和主要细节关系(水表读数)与att.Sorry代码如此之多,但我真的很困难,需要帮助。

trigger CreateWaterMeterReading on sm1e__smWork_Order__c (after update) 

{   
 if (Trigger.new.size() == 1) 
 {
 sm1e__smWork_Order__c wo = Trigger.new[0];
 if(wo.sm1e__WO_Type__c == 'Meter Read Move In/Out ' && wo.sm1e__Status__c == 'Completed')
 reateNewWaterMeterRead.createWMRforMoveInOrOut(wo.Id);
   }
}
--Apex class


 public class CreateNewWaterMeterRead {

 public static void createWMRforMoveInOrOut(string workorderId)
 {
   Work_Order__c wo = [Select          Equipment__r.Name,Completion_Date__c,Meter_Reading__c from             Work_Order__c where Id = : workorderId ];
        Equipment__c att = [Select Id,Last_Water_Meter_Reading_Date__c,Last_Water_Meter_Reading__c from Equipment__c where Name = : wo.Equipment__r.Name ];

        List<Water_Meter_Readings__c> newwmr = new List<Water_Meter_Readings__c>();
         Water_Meter_Readings__c wmr = new Water_Meter_Readings__c();
        wmr.Meter__c = att.Id;
        wmr.Current_Meter_Reading__c = wo.Meter_Reading__c;
        wmr.Current_Read_Date__c = wo.sm1e__Completion_Date__c;
        wmr.Prior_Meter_Reading__c = att.Last_Water_Meter_Reading__c;
        wmr.Prior_Read_Date__c = att.Last_Water_Meter_Reading_Date__c;
        wmr.Source__c = 'Manual Read';
        newwmr.add(wmr);
        if(newwmr.size() >0)
             insert newwmr;
             }

- 测试类

isTest(SeeAllData = true)
public class CreateNewWaterMeterReadTest 
{
   static testmethod void createWMRforMoveInOrOut()
   {

        Work_Order__c wo = [Select Id,Equipment__r.Name,Completion_Date__c,Meter_Reading__c from Work_Order__c where sm1e__Status__c != 'Completed' AND sm1e__WO_Type__c = 'Meter Read Move In/Out' LIMIT 1];
        Equipment__c att = [Select Id,Last_Water_Meter_Reading_Date__c,Last_Water_Meter_Reading__c from Equipment__c where Name = : wo.Equipment__r.Name ]; 

        test.startTest();
        wo.Meter_Reading__c = 1317;
        wo.sm1e__Status__c = 'Completed';
        update wo;
        test.stopTest();
        System.debug('updated wo');

        Water_Meter_Readings__c wmr = new Water_Meter_Readings__c();
        System.debug('wmr for test');
        wmr.Meter__c= att.Id;
        wmr.Current_Meter_Reading__c = wo.Meter_Reading__c;
        wmr.Current_Read_Date__c = wo.Completion_Date__c;
        System.debug('in between wmr');
        wmr.Prior_Meter_Reading__c = att.Last_Water_Meter_Reading__c;
        wmr.Prior_Read_Date__c = att.Last_Water_Meter_Reading_Date__c;
        wmr.Source__c = 'Manual';
        insert wmr; 

1 个答案:

答案 0 :(得分:0)

您在更新后已写入触发器。但是在您的测试类中,您正在插入记录而不是更新它。这就是您的代码覆盖率为0%的原因。请参阅此link

要执行触发器,您必须执行已编写触发器的dml操作。您还可以通过创建其实例从测试类调用您的类方法。请参阅上面的链接。