Hi Nat,
The code looks ok. You don't need to set the ContentGuid on your ContentAreaItem (as you're setting the ContentLink), but that shouldn't be related to the exception.
It's a NullReferenceException you're seeing, which probably means that your myContentArea is null. Is your code example the same as the sample you provided? If you set a breakpoint you should be easily able to identify the problem.
From the top of my head, you should not create new content area like that, but
var page = repo.GetDefault<MyPageType>(ContentReference.EmptyReference);
var cai = new ContentAreaItem{ ContentGuid = Guid.NewGuid(), ContentLink = new ContentReference(123)};
page.TheContentArea.Items.Add(cai);
Also ContentReference.EmptyReference does not make senses here.
of course I could be wrong thought
It is a NullReferenceException, but not because the ContentArea is null.
at EPiServer.Core.ContentArea.AddContentAreaItemsToFragments(IList items, Int32 startIndex)at EPiServer.Core.ContentArea.ModifyCollectionInternally(Action modification)at System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs e)at System.Collections.ObjectModel.ObservableCollection`1.InsertItem(Int32 index, T item)
The ContentReference.EmtyReference is just a parent ref, so really doesnt matter what is used there as far as I can tell - and if I substitue that for a 'real' ContentReference, it falls over just the same.
This is for a unit test, so the repo will only have the items in that I add.
Maybe the GetDefault<T> is not mocking/creating the necessary properties, but I have found very little information on how to write unit tests for Episerver, let alone what needs mocking as far as the repo is concerned.
Think this may help: https://www.meadow.se/wordpress/unit-testing-an-episerver-contentarea/
I am trying to write some unit tests, which require a block/page to have some items added to a ContentArea, which I need to do in the code.
However, when I run the following code - it throws an error.
var page = repo.GetDefault<MyPageType>(ContentReference.EmptyReference);var myContentArea = new ContentArea();var cai = new ContentAreaItem{ContentGuid = Guid.NewGuid(),ContentLink = new ContentReference(123)};myContentArea.Items.Add(cai); // <-- throws error here complaining about object ref not set.page.TheContentArea = myContentArea;// ..etchow can I add items to a ContentArea in the code.
thanks