Apex测试:实例化自定义Controller时的语法错误排查
Apex控制器实例化错误排查
原控制器代码
public class MyNewCaseController { public string filterId {get; set;} public MyNewCaseController(ApexPages.StandardController ctrl){ string filter = ApexPages.currentPage().getParameters().get('filterId'); if (filter != null) filterId = filter; } }
原测试类代码
@isTest public without sharing class MyNewCaseListControllerTest { @isTest public static void testMyNewCaseController (){ // Instantiate a new controller with all parameters in the page MyNewCaseListController controller = new MyNewCaseListController.MyNewCaseListController(ApexPages.StandardController ctrl); // Do something } }
遇到的错误
- 使用上述测试代码时,报错“Invalid type: CommunitiesCaseListController.CommunitiesCaseListController”;
- 尝试
MyNewCaseListController controller = new MyNewCaseListController();时,报错“Constructor not defined: [MyNewCaseListController].()”; - 尝试
MyNewCaseListController.MyNewCaseListController();时,报错“Invalid type: MyNewCaseListController.MyNewCaseListController”; - 尝试
MyNewCaseListController controller = new MyNewCaseListController.MyNewCaseListController(ApexPages.ctrl);时,报错“Invalid type: MyNewCaseListController.MyNewCaseListController”。
错误原因及修正方案
1. 类名不匹配
控制器类名为MyNewCaseController,但测试类全程误用MyNewCaseListController,这是直接导致类型识别失败的笔误。
2. 构造函数调用语法错误
实例化类时无需重复类名(类名.类名()是错误写法),正确格式为new 类名(参数)。
3. 未提供构造函数必需参数
控制器仅定义了带ApexPages.StandardController参数的构造函数,没有无参构造函数,因此必须传入StandardController实例,不能空括号调用。
正确测试代码示例
@isTest public without sharing class MyNewCaseControllerTest { // 修正测试类名,与控制器对应 @isTest public static void testMyNewCaseController (){ // 1. 创建测试用Case记录,用于实例化StandardController Case testCase = new Case(Subject = 'Test Case'); insert testCase; // 2. 实例化StandardController ApexPages.StandardController stdCtrl = new ApexPages.StandardController(testCase); // 3. 若需测试filterId参数,设置页面参数 ApexPages.currentPage().getParameters().put('filterId', 'test_123'); // 4. 正确实例化自定义控制器 MyNewCaseController controller = new MyNewCaseController(stdCtrl); // 后续断言逻辑,验证filterId是否正确赋值 System.assertEquals('test_123', controller.filterId); } }
内容的提问来源于stack exchange,提问作者Jonathan Crow
相关产品推荐
相关产品推荐

