Search code examples
c#mstest

MSTest: Blocking a test until another test caches data


I am writing unit tests for an Api client. One test, ListAll(), loads all entries from the Api for the given account, and the other, Get(), loads a specific order.

Get() requires a unique Id of an entry, so I would like to cache the entries received from ListAll() and use one of them for the Get() test instead of calling ListAll() inside of the Get() test.

I have read up on the notion of ordered tests, but I would prefer a solution that disregards the order in which tests are run. Ideally, it would block the Get() test until the entries are cached, or, if the test is running individually, would then resort to listing all of the entries before continuing. I have considered the use of a private Lazy<Entries> field in the test class to achieve this, but so far this approach does not seem viable.


Solution

  • It is usually recommended that your tests be independent of each other.

    However, if you need to share data between tests for speed reasons, you could have a LoadDataIfNeeded() function which both tests call. The first time LoadDataIfNeeded() is run, it loads the data, puts the data into a static member, and returns it; the second time it simply returns the already loaded data from the static member. If you want your tests to run correctly in any order, make sure that none of your tests interfere with each other by modifying the shared data after it is loaded.