TigerMan
05/17/2024, 10:38 AMjake williamson
06/26/2024, 10:43 PMIPublishedContent
, mainly getting into a 'you can't mock extension methods' nightmare...
did you get any further with this? i'm coming to the conclusion that the only way to unit test anything with IPublishedContent
is to write a wrapper service for all the extension methods...TigerMan
06/28/2024, 9:12 AMD_Inventor
06/28/2024, 11:57 AMjake williamson
06/29/2024, 1:00 AMUrl
used to be a property, it's not been a problem in the past but now it's an extension method, it's begun being an issue...
it's a pain, as you need to write a wrapper for every extension methods class and maintain them - but i guess it's a 'do once and make a nuget package' kinda thing.
the bit i go in loops with though is that the umbraco docos state:
https://docs.umbraco.com/umbraco-cms/reference/common-pitfalls#usage-of-singletons-and-statics
Generally speaking, if you are writing software these days you should be using Dependency Injection principles. If you do this, you probably aren't using Singletons or Statics (and for the most part you shouldn't be!).
seems weird that the docos say 'avoid statics' but then the core has them?!D_Inventor
06/29/2024, 6:07 AMItchy1505
02/17/2025, 4:58 PMD_Inventor
02/18/2025, 11:01 AMcsharp
public class MyService
{
public Card ConvertToCard(IPublishedContent content)
{
return new Card(content.Url(), content.Name);
}
}
This class is not testable, because it uses the .Url()
extension. So what I do, is I create a wrapper type:
csharp
public interface IUrlReader
{
string GetUrl(IPublishedContent content);
}
public class UrlReader : IUrlReader
{
public string GetUrl(IPublishedContent content)
=> content.Url();
}
And then I modify my service like this:
csharp
public class MyService(IUrlReader urlReader)
{
public Card ConvertToCard(IPublishedContent content)
{
return new Card(urlReader.GetUrl(content), content.Name);
}
}
Now I can mock/fake the IUrlReader
interface and run unit tests on this code.A hub and casual space for you to interact with fellow community members and learn more about Umbraco!
Powered by