- Published on, Time to read
- 🕒 1 min read
How to write unit test for a class with dependency to ServiceLocator — update
It's been a year since I wrote the article about unit testing with ServiceLocator. But, there are two things worth updating: replacing obsolete FormatterServices
and use scoped service provider.
First of, in the line:
var converterContext = (ConverterContext)FormatterServices
.GetUninitializedObject(typeof(ConverterContext));
...we can observe that FormatterServices
is obsolete as per SYSLIB0050: Formatter-based serialization is obsolete. We can read that for .NET 5 and greater, we should use the method from RuntimeHelpers
:
object obj = System.Runtime.CompilerServices.RuntimeHelpers
.GetUninitializedObject(typeToInstantiate);
That's the first thing. The second one is that we can use the scoped service provider to create the instance of the class that we want to test. This is useful if we want to have a scope for the test context and we don't want to pollute the global service provider (in context of other tests).
Example:
ServiceLocator.SetScopedServiceProvider(substituteForServiceLocator);
I updated:
- The original post: How to write unit test for a class with dependency to ServiceLocator (with example of Optimizely)?
- The code in my Foundation fork: XhtmlStringPropertyServiceTests