我刚开始学习Elixir。 我正试图用espec(https://github.com/antonmi/espec)测试异常,但我坚持了。
这是我的功能
defp call_xml(request_body) do
resp = HTTPotion.post("http://foo.bar", [body: request_body, headers: ["Content-Type": "text/xml"]])
if resp.status_code in [200, 201] do
{:ok, elem(XMLRPC.decode(resp.body), 1).param}
else
raise AbpError, message: "Message body"
end
end
def create_some_stuff(a, b, c) do
req = %XMLRPC.MethodCall{method_name: "Foo.Bar",
params:[a, b, c]} |> XMLPRC.encode!
call_xml(req)
end
# tests
use ESpec
use HyperMock
import :meck
context "when exception rised" do
it "returns err message" do
# stubbed with :meck
expect(MyModule, : create_some_stuff, fn("foo", "bar", "baz") -> raise CustomError end)
expect(MyModule. create_some_stuff("foo", "bar", "baz")).to eq("???")
end # it
end
在这种情况下,我的期望值出现了错误
** (AbpError) Error occured!
spec/lib/ex_abpclient_spec.exs:135: anonymous fn/7 in ExAbpclientSpec.example_returns_created_payback_eqcpjlrszudikwyovtmxbgfnha/1
(ex_abpclient) ExAbpclient.create_payment_payback("tr-TR", 10966, 10, "R", 495, 10, "DESC")
spec/lib/ex_abpclient_spec.exs:136: ExAbpclientSpec.example_returns_created_payback_eqcpjlrszudikwyovtmxbgfnha/1
(espec) lib/espec/example_runner.ex:33: ESpec.ExampleRunner.run_example/2
(elixir) lib/enum.ex:1088: Enum."-map/2-lists^map/1-0-"/2
(elixir) lib/enum.ex:1088: Enum."-map/2-lists^map/1-0-"/2
(espec) lib/espec/runner.ex:70: ESpec.Runner.run_examples/1
(espec) lib/espec/runner.ex:43: ESpec.Runner.do_run/2
如何获得存根异常? 提前致谢。
更新
我尝试使用HyperMock(https://github.com/stevegraham/hypermock)来存根请求,但也没有运气
context "when payback created" do
it "returns created payback" do
HyperMock.intercept do
request = %Request{body: "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodCall>.....",
headers: ["Content-Type": "text/xml"],
method: :post,
uri: "http://foo.bar/webApiXmlRpcServlet"}
response = %Response{body: "fooooo", status: 500}
stub_request request, response
expect MyModule.create_some_stuff("a", "b", "c") |> to(raise_exception AbpError, "fooooo")
end
end # it
end # exception
结果如下
/Users/retgoat/workspace/offside/ex_abpclient/spec/lib/ex_abpclient_spec.exs:135
** (AbpError) Error: "fooooo"
(ex_abpclient) lib/ex_abpclient.ex:55: ExAbpclient.call_xml/1
spec/lib/ex_abpclient_spec.exs:143: ExAbpclientSpec.example_returns_created_payback_nqfwohpurlvtzskdjxigeybamc/1
(espec) lib/espec/example_runner.ex:33: ESpec.ExampleRunner.run_example/2
(elixir) lib/enum.ex:1088: Enum."-map/2-lists^map/1-0-"/2
(elixir) lib/enum.ex:1088: Enum."-map/2-lists^map/1-0-"/2
(espec) lib/espec/runner.ex:70: ESpec.Runner.run_examples/1
(espec) lib/espec/runner.ex:43: ESpec.Runner.do_run/2
(espec) lib/espec/runner.ex:28: ESpec.Runner.handle_call/3
10 examples, 1 failures
Finished in 1.28 seconds (0.14s on load, 1.14s on specs)
异常上升,但我无法测试。
答案 0 :(得分:2)
罗马!
您必须将函数传递给expect
,而不是函数调用的结果。
因此,只需像{1}}那样将MyModule.create_some_stuff("a", "b", "c")
包裹起来,就像在ExUnit示例中一样:
fn -> end