[erlang-questions] test driven development
Joe Armstrong
erlang@REDACTED
Sun Nov 25 13:58:01 CET 2007
I think a lot of Erlang programmers have accidentally being using test
driven development for a long time without knowing it. This is because
the test mechanism
is so lightweight that it goes unnoticed...
There are actually two interpretations of a pattern:
- a test
- an unpacking operation
If there is any possibility that an '=' can fail then the '=' can be
viewed as a test.
Suppose I want to start by writing unit tests before I write my code.
I'll illustrate this by writing a function nth
that returns the n'th element of a list.
I can start by writing a test case:
test()->
b = nth(2,[a,b,c]).
Because = can fail here this serves as a test.
This can be viewed as an extremely light-weight unit test
Now I write my nth function and test it
..
As I proceed I add more tests:
test() ->
b = nth(2,[a,b,c]),
{'EXIT',_} = (catch, nth(-1, [a,b])),
{'EXIT',_} = (catch nth(3,[a,b])),
hooray.
This is three unit test, but no big deal.
I often write a function test/0 like this (that returns hooray) and
build this into my
edit-compile-test cycle - when all my module say hooray then I'm happy.
Functions can be viewed as having in-build unit test code in many places:
foo(...) ->
...
{ok, Socket} = gen_tcp:connect(....)
...
is a test AND an unpacking operation boiled into one.
Suppose I write
...
gen_tcp:send(Socket, Data)
...
This involves no testing, but adding a test is easy
...
ok = gen_tcp:send(Socket, Data)
....
adds a test - this has the added benefit of causing the program
to fail as soon as the
error is detected. "fail early" is *always* a good idea since it
minimizes the chance
of causing additional errors.
Even without equality the way functions are written provides a
form of assertion checking.
foo(a) -> 1;
foo(b) -> 2.
asserts that the argument to foo/1 is a or b. So ideas of assertions
and "design by contract" are pretty much implicit in all Erlang code.
It's only after the Erlang book was published that I realized that this way of
interpreting code was not widespread - this is perhapses something further books
and articles might like to emphasis.
On Nov 25, 2007 3:41 AM, Andrew Arrow <oneone@REDACTED> wrote:
> I've just finished the Joe Armstrong book (coming from a Java and Ruby
> background) and I noticed there was nothing in the book about test
> driven development.
>
> Is the idea that Erlang forces you to write such bug free code there
> are no need for tests? Or was this simply beyond the scope of the
> book?
>
> Do professional Erlang programmers create lots of unit and functional
> tests like Java and Ruby programmers do? If so, is there a way to run
> all the tests like there is with junit/testng or Test::Unit in ruby?
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
>
More information about the erlang-questions
mailing list