I'm starting to use common test
as my test framework in erlang.
Suppose that I have function I expect to accept only positive numbers and it should blows in any other case.
positive_number(X) when > 0 -> {positive, X}.
and I want to test that
positive_number(-5).
will not complete successfully.
How do I test this behaviour? In other languages I would say that the test case expects some error or exception and fails if it function under test doesn't throws any error for invalid invalid parameter. How to do that with common test?
Update:
I can make it work with
test_credit_invalid_input(_) ->
InvalidArgument = -1,
try mypackage:positive_number(InvalidArgument) of
_ -> ct:fail(not_failing_as_expected)
catch
error:function_clause -> ok
end.
but I think this is too verbose, I would like something like:
assert_error(mypackage:positive_number, [-1], error:function_clause)
I assuming that common test has this in some place and my lack of proper knowledge of the framework that is making me take such a verbose solution.
Update: Inspired by Michael's response I created the following function:
assert_fail(Fun, Args, ExceptionType, ExceptionValue, Reason) ->
try apply(Fun, Args) of
_ -> ct:fail(Reason)
catch
ExceptionType:ExceptionValue -> ok
end.
and my test became:
test_credit_invalid_input(_) ->
InvalidArgument = -1,
assert_fail(fun mypackage:positive_number/1,
[InvalidArgument],
error,
function_clause,
failed_to_catch_invalid_argument).
but I think it just works because it is a little bit more readable to have the assert_fail
call than having the try....catch
in every test case.
I still think that some better implementation should exists in Common Test, IMO it is an ugly repetition to have this test pattern repeatedly implemented in every project.