如何在erlang中测试gen服务器?

时间:2011-05-06 06:31:33

标签: erlang gen-server

我是erlang的初学者,我写了一个基本的gen服务器程序如下,我想知道,如何测试服务器,以便我知道它运作良好。

-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:该程序可以编译,它不是一个好的程序,我只想打印一些东西以确保它有效:)

2 个答案:

答案 0 :(得分:8)

gen_server实现模块的优点在于它只是一个回调模块。甚至不需要生成底层的gen_server进程来测试它。

你需要做的就是让你的测试框架(通常是eunit)通过注入不同的输入(不同的gen_server状态,不同的输入消息)等来调用所有的handle_call / cast / info函数,并确保它返回正确的响应元组(例如。{reply,ok,NewState}或{noreply,NewState}等)。

当然,如果您的回调函数不是pure functions,这将无法正常工作。例如,在handle_call函数中,如果要向另一个进程发送消息,例如,或者您正在修改ets表。在这种情况下,您必须确保在运行测试之前预先创建了所有必需的进程和表。

答案 1 :(得分:1)

您可以尝试以下方法之一:

1)使用erlang shell并手动调用命令。确保source或.beam文件位于erlang路径(参数-pz)

2)写一个EUnit测试用例

PS:我认为您的代码中有错误,因为您似乎将模块ch3作为服务器启动,而不是gen_server_test模块。