I am unit testing and trying to mock a class calling C functions through ffi. A pair of functions is responsible for starting and stopping a thread in C. The start function passes a nativePort to C to communicate with the thread. The stop function is signaling the thread to wrap up. The thread will then use the nativePort handle to tell the listener running in the startFunction that it finished.
DartFunc1() --ReceivePort.SendPort.nativePort--> native library in C stores port handle globally and starts processing in a thread. DartFunc2() -> calls native C function that uses global port handle to tell dart processing ended.
In the unit test I am trying to imitate this behavior by mocking the start and stop call to C. However, I have no idea how to get the dart sendPort to tell the listener in the other function we are done.
I spend literally all day on Google searching for similar problems (maybe hidden solutions?), looking through the documentation of mockito, flutter, the ffi package.
Somewhere I saw IsolateNameServer.lookupPortByName => SendPort?
and that I can create ReceivePort with a name argument (at least for debugging), so I did that.
The code looks something like this:
test("run", () {
when(() => clib.start).thenReturn((invocation) => (_) {});
when(() => clib.stop).thenReturn(() => () {
SendPort? port = IsolateNameServer.lookupPortByName("PortA");
port?.send(1);
});
expect(sut.isRunning, false); sut.start(); // will call clib.start internally
expect(sut.isRunning, true); sut.stop(); // will call clib.stop internally
expect(sut.isRunning, false); // <= this always fails
});