如何在IObservable上触发和测试事件?

时间:2015-01-30 05:30:38

标签: testing asynchronous f#

我正在编写一个基本的UDP服务器,用于侦听给定端口上的消息,对输入进行一点按摩,并使用已处理的消息触发事件。我想编写测试,向服务器发送消息并验证是否引发了正确的事件。

服务器看起来像这样:

type UdpServer() =
    let messageReady = new Event<string>()

    member x.Start () = async {
            let rec loop () =                 
                let message = receiveMessage ()
                messageReceived.Trigger(message)
                return loop ()
            return! loop ()
        }

    member x.MessageReady = messageReady.Publish

我想写一个像这样的测试:

[<Test>]
let ``Should process message correctly`` () =
    let server = new UdpServer()
    server.Start() |> Async.Start
    sendMessageToServer "test message"

    // This will wait indefinitely since the message was already sent in the previous line
    let processedMessage = server.MessageReady |> Async.AwaitEvent |> Async.RunSynchronously
    processedMessage |> should be "expected output"

如何向服务器发送消息,然后测试是否已触发MessageReady事件 是否正确?我可以使用mutable来存储值,但这看起来不像F#方式:

let mutable processedMessage = ""
server.MessageReady |> Observable.subscribe(fun m -> processedMessage <- m)
sendMessageToServer "test message"
processedMessage |> should be "expected output"

1 个答案:

答案 0 :(得分:1)

使用observable和事件本质上是必要的,因此可以使用mutables / ref单元来检查它们是否被引发。