2

I'm writing unit tests and using Moq as a mocking tool. In a previous question I was advised to use IXdbContext to mock the XConnect client, which works just fine. However, I run into problems if I mock the GetAsync() method to be able to get a Contact.

I need to get facets off of the returned Contact so I either have to mock a Contact and override the GetFacet<>() method, or create a real Contact instance with the proper facets in its Facets collection.

The first option fails because Contact is sealed, and the second option fails because the Facets collection is a ReadOnlyDictionary which can't be written to.

So how can I properly mock a Contact that I can return in GetAsync() so that I can get facets out of it?

1

If you go with the second option (real Contact instance), you can use reflection (e.g. ReflectionUtil) to set FacetMap property on the contact instance.

FacetMap is then used by Facets and GetFacet calls.

    [Test]
    public void Test1()
    {
       var contact = new Contact();

        var facetMap = new Dictionary<string, Facet>();
        var firstName = "Marek";

        facetMap[PersonalInformation.DefaultFacetKey] = new PersonalInformation
        {
            FirstName = firstName
        };

        Sitecore.Reflection.ReflectionUtil.SetProperty(contact, "FacetMap", facetMap);

        Assert.AreEqual(firstName, contact.GetFacet<PersonalInformation>().FirstName);
    }
1
  • I'm not a big fan of using reflection for testing, but for lack of better options it seems that's my only choice. Thanks for the code example!
    – GTHvidsten
    Sep 6 '21 at 7:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.