简体   繁体   English

如何在顶点测试更新 class

[英]How to test an Update class in apex

Hello I am new to apex and soql, I would like some help on my test class, below is the code i am having trouble with,您好,我是 apex 和 soql 的新手,我想对我的测试 class 有所帮助,下面是我遇到问题的代码,

    public class UpdateMyCard {
    @AuraEnabled(cacheable=false)
    public static Card__c updateCard(Double Amount){
        String userId = UserInfo.getUserId();
        Card__c myCard = [SELECT Id, Card_no__c, total_spend__c From Card__c Where OwnerId =:userId];
        myCard.total_spend__c = myCard.total_spend__c + Amount;
        try{
            update myCard;
        }catch (Exception e) {
           System.debug('unable to update the record due to'+e.getMessage());
        }
        return myCard;
    }
}

Test Class测试 Class

@isTest
public static void updatecard(){
    UpdateMyCard.updateCard(200);
}

Error:错误:

System.QueryException: List has no rows for assignment to SObject 

 

Your code assumes there's already a Card record for this user.您的代码假定该用户已有 Card 记录。 And it's exactly 1 record (if you have 2 your query will fail).它恰好是 1 条记录(如果您有 2 条记录,您的查询将失败)。 I'm not sure what's your business requirement.我不确定您的业务需求是什么。 Is it guaranteed there will always be such record?能保证永远有这样的记录吗? Should the code try to create one on the fly if none found?如果没有找到,代码是否应该尝试动态创建一个? You might have to make that "updateCard" bit more error-resistant.您可能必须使“updateCard”更防错。 Is the total spend field marked as required?总支出字段是否标记为必填项? Because "null + 5 = exception"因为“null + 5 = 异常”

But anyway - to fix your problem you need something like that in the test.但无论如何 - 要解决您的问题,您需要在测试中使用类似的东西。

@isTest
public static void updatecard(){
    Card__c = new Card__c(total_spend__c = 100);
    insert c;

    UpdateMyCard.updateCard(200);

    c = [SELECT total_spend__c FROM Card__c WHERE Id = :c.Id];
    System.assertEquals(300, c.total_spend__c);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM