运行Salesforce Apex测试类报错:testLeapYear方法不存在,求解决
问题:运行SingletonTest测试类时提示testLeapYear方法不存在
运行SingletonTest测试类中的测试时,收到错误提示:
Method testLeapYear does not exist in the apex class with Id :01p5g00000iZVmG
涉及的类代码
SingletonTest.cls
@IsTest public with sharing class SingletonTest { @IsTest public static void testLeapYear() { //not stubbed out, so this will take the normal path w/o the switch SingletonController.printDateTime(); } @IsTest public static void testNonLeapYear() { //IS stubbed out, so this WILL take the alternate path DateTime newNow = DateTime.newInstance(2019, 9, 8); DateTimeProvider.instance = new DateTimeStub(newNow); SingletonController.printDateTime(); //in the wild, return data and make assertions here } private with sharing class DateTimeStub extends DateTimeProvider { public DateTime now; public DateTimeStub(DateTime now) { this.now = now; } public override DateTime now() { return now; } } }
DateTimeProvider.cls
public virtual with sharing class DateTimeProvider { @TestVisible private static DateTimeProvider instance; public static DateTimeProvider getInstance() { if (instance == null) { instance = new DateTimeProvider(); } return instance; } protected DateTimeProvider() { // protected constructor for testability - use getInstance() instead } public virtual DateTime now() { return DateTime.now(); } }
SingletonController.cls
public with sharing class SingletonController { @AuraEnabled public static void printDateTime() { DateTimeProvider dateProvider = DateTimeProvider.getInstance(); System.debug('Hey, is it a leap year?'); Boolean isLeapYear = Date.isLeapYear(dateProvider.now().year()); if (isLeapYear) { System.debug('Yep! Get testing!'); } else { System.debug('All clear. Enjoy your free time :) '); } } }
已尝试的操作
- 添加
Test.startTest()和Test.stopTest() - 将代码部署到组织
- 在开发者控制台运行代码
解决方案
这个错误的核心原因是组织中实际存在的SingletonTest类(ID:01p5g00000iZVmG)与你本地编写的版本不一致,该类中并未包含testLeapYear方法。可以按以下步骤排查解决:
核对组织内的类代码
在Setup的「Apex Classes」中找到ID为01p5g00000iZVmG的类,查看其源代码,确认是否存在testLeapYear方法。如果不存在,说明之前的部署未成功或部署了旧版本。重新部署完整测试类
确保本地SingletonTest类的代码完整(包含两个测试方法及内部Stub类),然后通过VS Code或开发者控制台重新部署,覆盖组织中的现有版本。部署时注意勾选「覆盖现有类」选项。检查测试方法的合规性
确认testLeapYear方法满足测试方法的要求:- 带有
@IsTest注解 - 是
public static修饰符 - 无返回值(返回类型为
void)
缺少任何一项都会导致系统无法识别该方法为测试方法。
- 带有
更新类的API版本
如果SingletonTest类的API版本过低,可能会对@IsTest注解或语法支持有问题。将类的API版本更新到58.0及以上(Salesforce最新稳定版本),重新部署后再运行测试。清理缓存并重新运行
在开发者控制台中关闭所有标签页后重启,或者执行匿名代码块(无需实际逻辑),清理系统缓存后再重新运行测试。
内容的提问来源于stack exchange,提问作者Robin
相关产品推荐
相关产品推荐

