使用随机错误测试应用
生成应用时,应测试应用如何处理 API 错误。 使用开发代理可以模拟在应用中 使用 GenericRandomErrorPlugin 的任何 API 上的错误。
模拟任何 API 上的错误
若要开始,请在 GenericRandomErrorPlugin
配置文件中启用。
{
"$schema": "https://raw.githubusercontent.com/dotnet/dev-proxy/main/schemas/v0.24.0/rc.schema.json",
"plugins": [
{
"name": "GenericRandomErrorPlugin",
"enabled": true,
"pluginPath": "~appFolder/plugins/dev-proxy-plugins.dll",
"configSection": "errorsContosoApi",
"urlsToWatch": [
"https://api.contoso.com/*"
]
}
]
}
提示
由于每个 API 不同,因此通常为每个要模拟错误的 API 配置实例 GenericRandomErrorPlugin
。 若要更轻松地管理配置,请命名 configSection
为要模拟其错误的 API 之后。 此外,使用插件指定要在属性中 urlsToWatch
模拟错误的 URL。 这样,可以更轻松地管理配置,并在将来重复使用它。
接下来,将插件配置为使用包含要模拟的错误的文件。
{
"errorsContosoApi": {
"errorsFile": "errors-contoso-api.json"
}
}
最后,在错误文件中,定义要模拟的错误响应列表。 例如,若要使用自定义 JSON 响应模拟 500 错误,请使用以下配置:
{
"$schema": "https://raw.githubusercontent.com/dotnet/dev-proxy/main/schemas/v0.24.0/genericrandomerrorplugin.schema.json",
"errors": [
{
"request": {
"url": "https://api.contoso.com/*"
},
"responses": [
{
"statusCode": 500,
"headers": [
{
"name": "content-type",
"value": "application/json; charset=utf-8"
}
],
"body": {
"code": "InternalServerError",
"message": "Something went wrong"
}
}
]
}
]
}
可以根据需要定义任意数量的错误响应。
使用配置文件启动开发代理,并使用应用查看它如何处理错误。 对于每个匹配请求,开发代理确定是模拟错误,还是使用 配置的失败率将请求传递到原始 API。 当开发代理模拟错误时,它会使用配置文件中定义的错误响应数组中的随机错误。
暂时禁用模拟
如果在配置文件中使用模拟,则可以使用 --no-mocks
此选项暂时禁用它们。
devproxy --no-mocks
下一步
详细了解 GenericRandomErrorPlugin
。