首页 > 解决方案 > 如何为 Plug 错误处理编写测试

问题描述

我正在尝试使用-- with等Plug.Test来测试错误处理。Plug.ErrorHandlerassert conn.status == 406

我有defp handle_errors(包含一条send_resp语句),它似乎被调用了,但是,我的测试仍然失败,但仍然有同样的异常(好像handle_errors没有效果)。

对示例高级插件(不是 Phoenix)应用程序的引用也将不胜感激。

标签: testingerror-handlingelixirplug

解决方案


尝试这样的事情(未经测试):

defmodule NotAcceptableError do
  defexception plug_status: 406, message: "not_acceptable"
end

defmodule Router do
  use Plug.Router
  use Plug.ErrorHandler

  plug :match
  plug :dispatch

  get "/hello" do
    raise NotAcceptableError
    send_resp(conn, 200, "world")
  end

  def handle_errors(conn, %{kind: _kind, reason: reason, stack: _stack}) do
    send_resp(conn, conn.status, reason.message)
  end
end

test "error" do
  conn = conn(:get, "/hello")

  assert_raise Plug.Conn.WrapperError, "** (NotAcceptableError not_acceptable)", fn ->
    Router.call(conn, [])
  end

  assert_received {:plug_conn, :sent}
  assert {406, _headers, "not_acceptable"} = sent_resp(conn)
end

推荐阅读