You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

单元测试运行时如何打印AWS Lambda函数内的Console.WriteLine输出

解决方案

以下两种方案均可实现单元测试时打印Lambda内部的输出内容:


方法1:重定向Console输出到测试工具(无需修改Lambda代码)

不需要调整Lambda的业务代码,仅在单元测试中临时捕获控制台输出即可:

[Fact]
public async Task TestHelloWorldFunctionHandler()
{
    var request = new APIGatewayProxyRequest();
    var context = new TestLambdaContext();
    Dictionary<string, string> body = new Dictionary<string, string>
    {
        { "message", "hello world" }
    };

    var expectedResponse = new APIGatewayProxyResponse
    {
        Body = JsonConvert.SerializeObject(body),
        StatusCode = (int) HttpStatusCode.OK,
        Headers = new Dictionary<string, string> { { "Content-Type", MediaTypeNames.Application.Json } }
    };

    // 新增:捕获Console输出
    var originalConsoleOut = Console.Out;
    using var consoleOutput = new StringWriter();
    Console.SetOut(consoleOutput);

    var response = await new Function().FunctionHandler(request, context);

    // 新增:打印Lambda内部的Console输出
    _testOutputHelper.WriteLine("Lambda内部输出:\n" + consoleOutput.ToString());
    // 还原默认控制台输出
    Console.SetOut(originalConsoleOut);

    _testOutputHelper.WriteLine("Lambda Response: \n" + response.Body);
    _testOutputHelper.WriteLine("Expected Response: \n" + expectedResponse.Body);
    _testOutputHelper.WriteLine("Header: \n" + response.Headers.Values.ToArray()[0]);

    Assert.Equal(expectedResponse.Body, response.Body);
    Assert.Equal(expectedResponse.Headers, response.Headers);
    Assert.Equal(expectedResponse.StatusCode, response.StatusCode);
}

该方案适合临时调试场景,不需要改动线上运行的Lambda代码。


方法2:使用Lambda自带日志接口(更符合开发规范)

AWS Lambda原生提供了ILambdaContext.Logger日志接口,线上运行时会自动将日志上报到CloudWatch,单元测试时也可以直接读取缓存的日志内容:

  1. 调整Lambda代码,替换Console.WriteLine为官方日志接口:
public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context)
{
    // 替换Console.WriteLine
    context.Logger.LogLine($"Hello there");

    var body = new Dictionary<string, string>
    {
        { "message", "hello world" }
    };

    return new APIGatewayProxyResponse
    {
        Body = JsonConvert.SerializeObject(body),
        StatusCode = (int) HttpStatusCode.OK,
        Headers = new Dictionary<string, string> { { "Content-Type", MediaTypeNames.Application.Json } }
    };
}
  1. 单元测试中直接读取Lambda日志输出:
var response = await new Function().FunctionHandler(request, context);
// 直接从测试上下文获取Lambda日志并打印
_testOutputHelper.WriteLine("Lambda内部输出:\n" + context.Logger.ToString());

Rider输出检查

如果调整后仍看不到输出,打开测试结果面板的输出选项卡,下拉选择全部或标准输出,不要仅筛选「测试输出」即可。

内容的提问来源于stack exchange,提问作者Simon Rex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 02:21:01