2

Is there an easy way to mock UrlResolver class? I pass it as a parameter to the constructor.

public Service(UrlResolver urlResolver){
    _urlResolver = urlResolver;
}

EDIT: According to Henrik N. comment, this issue had been addressed in EpiServer 8.

But until I have an EpiServer 8 in my solution I will use custom interface + adapter.

gringo_dave
  • 1,372
  • 17
  • 24
  • Note that the problem with mocking UrlResolver was addressed in EPiServer.CMS.Core 8.0.0 by changing the class to be an abstract base class without any dependencies. – Henrik N May 22 '15 at 02:54
  • If so, then this question is obsolete. Please add an answer and I will mark it as a correct answer. – gringo_dave May 22 '15 at 07:49

3 Answers3

2

The dependency that is causing the issue was removed in version 8.0.0 of EPiServer.CMS.Core so if you can update to the latest version you should be fine.

Henrik N
  • 529
  • 4
  • 12
1

I've ended up creating my own IUrlResolver interface and adapter for UrlResolver.

public interface IUrlResolver
{
    string GetUrl(ContentReference contentReference, Language language);
}

public class UrlResolverAdapter : IUrlResolver
{
    public string GetUrl(ContentReference contentReference, Language language)
    {
        return UrlResolver.Current.GetUrl(contentReference, language);
    }
}
gringo_dave
  • 1,372
  • 17
  • 24
  • Yes, this is the way to go for most (if not all) of EPiServers tightly coupled mess... –  Apr 06 '16 at 14:22
0

Yes. Using the excellent FakeItEasy mocking library, it's as easy as:

UrlResolver fakeUrlResolver = A.Fake<UrlResolver>();

Then use it to instantiate your Service.

var myService = new Service(fakeUrlResolver);

If you need the fake to return on specific method calls, that's possible too. Say, the code fetches the public URL for a PageReference.

PageReference myLink = new PageReference(123);
UrlResolver fakeUrlResolver = A.Fake<UrlResolver>();
A.CallTo(() => fakeUrlResolver.GetUrl(myLink)).Returns("my/fake/url");

// probably initialize some other code with myLink at this point

var myService = new Service(fakeUrlResolver);