如何测试@future方法

时间:2015-08-08 15:59:27

标签: salesforce apex

我有以下服务:

public with sharing class LibraryService {

    public static void remove(String jsonString) {
        Library__c library = [ SELECT Id, ilms__Library_Name__c FROM ilms__Library__c WHERE Id = libraryId ] ;

        AccessService.deleteReviewerGroup(library);

        delete library;
    }
}

AccessService类

public  with sharing class AccessService {
        public static void deleteLibraryReviewerGroup(Library__c library) {

        List<Library__Share> reviewersGroups = [ SELECT UserOrGroupId FROM ilms__Library__Share WHERE AccessLevel = 'Read' AND ParentId = :library.Id  ];
        System.debug('reviewersGroups: ' + reviewersGroups);

        if(reviewersGroups.size() == 1) {
            String reviewersGroupId = reviewersGroups[0].UserOrGroupId;

            delete reviewersGroups;

            AccessService.deleteReviewerGroup(reviewersGroupId);
        }

        return;
    }
    @future
    public static void deleteReviewerGroup(String groupId) {
        List<Group> reviewerGroup = [ SELECT Id FROM Group WHERE Id = :groupId ];

        delete reviewerGroup;

    }
}

现在,当我尝试测试LibraryService remove方法时,我一直收到以下错误:

  

第一个错误:MIXED_DML_OPERATION,更新非安装对象后,不允许对安装对象进行DML操作(反之亦然)。

@isTest(SeeAllData=true)
private class TestLibrary {
    static testMethod void testRemoveLibrary() {
        Library__c library = new Library__c(...);
        Boolean isRemoved = LibraryService.remove(TestUtilsClass.idJson(library.Id));

        System.assertEquals(isRemoved, true);
    }
}

我尝试将Test.startTest()和Test.stopTest()添加到testRemoveLibrary方法,但我仍然得到相同的错误。难道我做错了什么?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

@isTest(SeeAllData=true)
private class TestLibrary {

    static testMethod void testRemoveLibrary() {

        Library__c library = new Library__c(...);
        Test.start();
        Boolean isRemoved = LibraryService.remove(TestUtilsClass.idJson(library.Id));
        Test.stop();
        System.assertEquals(isRemoved, true);
    }
}

请添加Test.start并停止包含您的方法。