1

这是我正在测试的代码:

defmodule BracketParser do
    @spec parse_line(binary) :: binary
    def parse_line(line), do: parse_line_as_list(String.graphemes(line), false, [])
    defp parse_line_as_list([], true, _acc) do
        IO.puts("hello")
        raise SyntaxError
    end
    defp parse_line_as_list([], _collect, acc) do
        Enum.reverse(acc) |> IO.iodata_to_binary
    end
    defp parse_line_as_list(["{" | t], _collect, acc) do
        parse_line_as_list(t, true, acc)
    end
    defp parse_line_as_list(["}" | t], _collect, acc) do
        parse_line_as_list(t, false, acc)
    end
    defp parse_line_as_list([h | t], true, acc) do
        parse_line_as_list(t, true, [h | acc])
    end
    defp parse_line_as_list([_h | t], collect, acc) do
        parse_line_as_list(t, collect, acc)
    end
end

这是我的测试:

ExUnit.start

defmodule TestBracketParser do
    use ExUnit.Case

    test "should get the text inside a pair of brackets" do
        assert_raise SyntaxError, fn() -> BracketParser.parse_line("{bill") end
    end
end

目标是有一个解析器来收集{}符号之间的文本。如果列表为空并且集合标志设置为 true,我希望代码会引发语法错误。但是,当我运行这段代码时,我得到了这个:

  1) test should get the text inside a pair of brackets (TestBracketParser)
     test_parse_brackets.exs:6
     Got exception SyntaxError but it failed to produce a message with:

     ** (FunctionClauseError) no function clause matching in IO.chardata_to_string/1
         (elixir) lib/io.ex:461: IO.chardata_to_string(nil)
         (elixir) lib/path.ex:312: Path.relative_to/2
         (elixir) lib/exception.ex:713: SyntaxError.message/1
         (ex_unit) lib/ex_unit/assertions.ex:658: ExUnit.Assertions.check_error_message/2
         (ex_unit) lib/ex_unit/assertions.ex:639: ExUnit.Assertions.assert_raise/2
         test_parse_brackets.exs:10: TestBracketParser."test should get the text inside a pair of brackets"/1
         (ex_unit) lib/ex_unit/runner.ex:306: ExUnit.Runner.exec_test/1
         (stdlib) timer.erl:166: :timer.tc/1
         (ex_unit) lib/ex_unit/runner.ex:245: anonymous fn/4 in ExUnit.Runner.spawn_test/3

我不知道为什么会有一个FunctionClauseError被抛出。我似乎已经解释了所有模式。我究竟做错了什么?

4

1 回答 1

3

作为raise各州的文件,

如果msg是一个原子,它只raise/2是以原子作为第一个参数和 [] 作为第二个参数调用。

raise/2exception/1在参数上调用函数。

在您的情况下,您应该使用raise "SyntaxError"或提供一个名为SyntaxError调用的模块defexception/1

于 2018-04-06T00:13:32.580 回答