1/* 2 * Copyright (c) 2025 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15import { AssertResult } from '../modal/assertModel'; 16import hilog from '@ohos.hilog'; 17let domain: number = 0x0000; //日志标识,0x0000作为测试框架的业务标识 18let tag: string = 'testTag'; //日志标识字符串,作为tag标识当前runner类下的测试行为 19 20export function assertThrowError(actualValue: () => void, expected: string[]): AssertResult { 21 let result = false; 22 let message = ''; 23 if (typeof actualValue !== 'function') { 24 throw new Error('actualValue is not a function'); 25 } 26 try { 27 actualValue(); 28 return { 29 pass: result, 30 message: ' An error is not thrown while it is expected!', 31 }; 32 } catch (err: Error) { 33 const length = expected.length; 34 const errorType = Class.of(err).getName(); 35 const errorTypeArr = errorType.split('.'); 36 const errType = errorTypeArr[errorTypeArr.length - 1]; 37 hilog.info(domain, tag, '%{public}s', 'assertThrowError errorType'); 38 hilog.info(domain, tag, '%{public}s', errorType); 39 if (length === 1) { 40 if (expected[0] !== '' && errType === expected[0]) { 41 result = true; 42 } else { 43 result = false; 44 message = 'expected throw failed , ' + errorType + ' is not ' + expected[0]; 45 } 46 } else if (length === 2) { 47 if ((expected[0] === '' || errType === expected[0]) && err.message === expected[1]) { 48 result = true; 49 } else if (expected[0] !== '' && errType !== expected[0]) { 50 result = false; 51 message = 'expected throw failed , ' + errorType + ' is not ' + expected[0]; 52 } else { 53 result = false; 54 message = 'expected throw failed , ' + err.message + ' is not ' + expected[1]; 55 } 56 } else { 57 result = false; 58 message = 'expect one or two parameters!'; 59 } 60 } 61 62 return { 63 pass: result, 64 message: message, 65 }; 66} 67