How should I unit test threaded code?

后端 未结 26 1923
悲&欢浪女
悲&欢浪女 2020-11-22 04:09

I have thus far avoided the nightmare that is testing multi-threaded code since it just seems like too much of a minefield. I\'d like to ask how people have gone about test

26条回答
  •  猫巷女王i
    2020-11-22 04:48

    There is an article on the topic, using Rust as the language in the example code:

    https://medium.com/@polyglot_factotum/rust-concurrency-five-easy-pieces-871f1c62906a

    In summary, the trick is to write your concurrent logic so that it is robust to the non-determinism involved with multiple threads of execution, using tools like channels and condvars.

    Then, if that is how you've structured your "components", the easiest way to test them is by using channels to send messages to them, and then block on other channels to assert that the component sends certain expected messages.

    The linked-to article is fully written using unit-tests.

提交回复
热议问题