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

How does one trigger and test events on an IObservable?

我正在编写一个基本的 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 事件 正确吗?我可以使用可变变量来存储值,但这似乎不像 F# 方式:

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

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