Search code examples
erlanggen-server

How to test gen server in erlang?


I am a beginner with erlang, and i write a basic gen server program as follows, I want to know, how to test the server so i can know it works well.

-module(gen_server_test).
-behaviour(gen_server).
-export([start_link/0]).
-export([alloc/0, free/1]).
-export([init/1, handle_call/3, handle_cast/2]).
start_link() ->
    gen_server:start_link({local, gen_server_test}, ch3, [], []).
alloc() ->
    gen_server:call(gen_server_test, alloc).
free(Ch) ->
    gen_server:cast(gen_server_test, {free, Ch}).
init(_Args) ->
    {ok, channels()}.
handle_call(alloc, _From, Chs) ->
    {Ch, Chs2} = alloc(Chs),
    {reply, Ch, Chs2}.
handle_cast({free, Ch}, Chs) ->
    io:format(Ch),
        io:format(Chs),
        Chs2 = free(),
    {noreply, Chs2}.

free() -> 
        io:format("free").
channels() ->
        io:format("channels").
alloc(chs) -> 
        io:format("alloc chs").

BTW: The program can be compiled, and it is not a good program, I just want to print something to make sure it works :)


Solution

  • You could try one of the following:

    1. Use the erlang shell and invoke the commands manually. Make sure the source or .beam file is in the Erlang path (parameter -pz, like this: erl -pz <path here>)

    2. Write an EUnit test case

    PS: I think you have an error in your code, because you seem to start the module ch3 as the server, not the gen_server_test module.