21

This is possible with Sitecore 8.2, since the GetChildren and Add methods became virtual with this version. (You could create an NSubstitute Sitecore 8.1 item, but NSubstiute would not be able to interact with its methods, so there would not be any point in doing so.) To create a Subsitute item, you need to: Create an item ID: var itemId = ID.NewID; ...


13

Answers 1) Yes, that will get out of control. You are actually implementing your own implementation for faking the Sitecore database. There already exists a solution for this: https://github.com/sergeyshushlyapin/Sitecore.FakeDb. I really recommend using this. From the github page: This is the unit testing framework for Sitecore that enables creation and ...


10

Mocking Pipeline Code in Sitecore before 8.2 If you are working in Sitecore before 8.2 your best bet would be to look into using Sitecore FakeDB; it offers an in-memory representation of Sitecore. It allows tests for all parts of Sitecore including pipeline code. An example from the documentation is: [Fact] public void ...


6

I abstract out the configuration in to one (usually one but could more if it's a large project) Class with a corresponding Interface. Then rather than changing the config - I inject a mocked Interface with the config defined so that the unit test tests the functionality I'm after. E.g. public class ModuleConfiguration : IModuleConfiguration { ...


6

If you're on Sitecore 8.2+, you can use abstract BaseLinkManager class (that's actually valid for all the old static managers). In combination with Sitecore Dependency Injection that is easy to inject the abstraction into a controller or a pipeline processor: public class MyController : ApiController { private readonly BaseLinkManager _linkManager; ...


5

Sitecore FakeDb does not set the context item because depending on the scenario, you might or might not need it to be set. If you need the context item not to be null, you can set it in your test using the ContextItemSwitcher: using (var db = new Db { new DbItem("home") }) { var home = db.Database.GetItem("/sitecore/content/home"); using (new ...


5

When writing unit tests for Sitecore my general rule of thumb is to try not to test whether it's doing its job, that's not your responsibility. I think you might be better off abstracting this away behind some interface. From your question, I can only assume that you have some consumer that is using a list of countries in some way. If you define an ...


5

You are using SXA ModelRepository which is using dependency injection and service locator pattern to inject for example: wrapper for Rendering wrapper PageContext ContentRepository few more things... Now if you want to test you first need to register those in the container and configure that container to be used (of course if you are not using certain ...


4

Assuming that you are using FakeDB for your Unit Tests you can simply change settings on the fly. See example: using (Db fakeDb = new Db()) { fakeDb.Configuration.Settings["SettingName"] = "SettingValue"; } More info here.


4

LinkManager is essentially just a static wrapper around LinkProvider, which uses virtual methods for everything. If you simply inject LinkManager.Provider into your controller's constructor, you can mock the LinkProvider in your tests.


4

Had a bit of a think about how to do this: Test the processor steps So the first thing to do is make sure all your code logic is off loaded to a service or manager class. The processor class really should just be responsible for creating the service/manager class (by constructor injection of course :) ) and then calling the appropriate method. So the main ...


3

The simplest solution is to change your code to make it more easily unit testable, and remove the dependence on the Sitecore.Context object, and instead pass in the required variables as a parameter to your method. For example, you could do the following and then unit test the dostuff() method: public bool process (string url) { dostuff(Sitecore.Context....


3

As I stated in comments, it's a good practice to provide a Minimal, Complete, and Verifiable example. For this particular case, it seems everything works fine so I need more details to reproduce your issue. If I create a test like this, it passes (NUnit 3.10.1): [Test] public void QueryTest() { using (var db = new Db { new DbItem("Countries")...


3

Ok I finally found my mistake. Since I am using DbTemplates, the DbLinkField needs to be added to the template first. db.Add(new DbTemplate("t1", t1_TemplateId)){ new DbLinkfield("theField") }); db.Add(new DbTemplate("T", T_TemplateId) { BaseIDs = new[] { t1_TemplateId} }); db.Add(new DbItem("root") { new DbItem("child1") { new ...


3

My problem was actually due to ReSharper Unit Test for NUnit runner. It was running tests from temporary location, not from the project output directory. Fix was to tell NUnit runner to set Environment.CurrentDirectory to Test assembly's folder:


3

I was able to run your code by not mocking Uri, but by Mock<XConnectClient> client = new Mock<XConnectClient>( new Mock<XConnectClientConfiguration>( new Mock<XdbModel>( "XdbName", new XdbModelVersion(1, 0), ...


3

By mocking a proper return type(GetPreviousProductsResponse) value for the injected service(_productService) instead of a model property(PreviousProducts) solved this issue. _productService.GetPreviousProducts(Arg.Any<GetPreviousProductsParameters>()).Returns(new GetPreviousProductsResponse); The test still doesn't return 'ViewResult' type as intended ...


3

If you go into ImageField.MediaItem getter, you'll notice that the MediaDatabase.GetItem() method uses 3 parameters including language and version: this.mediaItem = this.MediaDatabase.GetItem(mediaId, this.MediaLanguage, this.MediaVersion); In your test you mock another overload of the GetItem() method that uses ID only: database.GetItem(new ID("...


2

Recently, I have started using the SettingsSwitcher for mocking Sitecore <setting> values. I configure all of the mocked values in the constructor of a TestRunner class that I initialize before running any unit tests. The class is an IDisposable that I dispose of after the tests complete. Using the example in the OP, the setting[@name='mySftp'] has ...


2

I'd suggest not to use FakeDb for (unit) testing such scenario. If I unrerstand your intention correctly, you do not test any logic of your application. You're trying to test a piece of Sitecore functionality which is a perfect place for an integration test (e.g. using Postman). In this particular scenario it could be more robust and unlike unit test it's ...


2

You need to add template to the FakeDB database first. Just add those 2 lines to your code: var childTemplate = new DbTemplate("child", templateID); db.Add(childTemplate); e.g: var myHomeID = new ID(); var templateID = new ID(); var template = new TemplateID(templateID); using (var db = new Db {new DbItem("Home", myHomeID)}) { var childTemplate = ...


2

For testing authentication using FakeDb you can try next : [Theory] [AutoDbData] public void Login_UserIsNotLoggedIn_ShouldReturnFalse(FakeMembershipUser user, AuthenticationProvider authenticationProvider, AccountRepository repo) { authenticationProvider.Login(@"somedomain\John", Arg.Any<string>(), Arg.Any<bool>())....


2

There is a package from Sitecore.FakeDb that integrates with AutoFixture to generate items on the fly. The Nuget package is Sitecore.FakeDb.AutoFixture https://github.com/sergeyshushlyapin/Sitecore.FakeDb/wiki/AutoFixture-Samples After you generate the item, then you can assign the item as a MediaItem https://github.com/sergeyshushlyapin/Sitecore.FakeDb/...


2

I will start my answer with a question, why do you need to use FakeDB? Even though the idea of FakeDB is great in theory, it inevitably causes more issues than it solves, in my opinion, when testing units in your code, it's another story when you are carrying out integration tests, but then the argument would be why not manipulate a real Sitecore database. ...


2

It's a bug and needs to be fixed in FakeDb. But the good news is that you may hotfix it following the article instructions carefully: add shell site registration to your config: <sites> <site name="shell" domain="sitecore"></site> </sites> define class parameters in the following way (remove name, add masterDatabase): ...


2

Of course, it is possible. Moq has a different API, so I'd suggest to start from this guide first. This code sample configures item descendants to return an empty array: var itemMock = new Mock<Item>(id, itemData, database); var axesMock = new Mock<ItemAxes>(itemMock.Object); var expectedDescendants = new Item[] { }; itemMock.Setup(i => i....


2

From what I can see, the reason why it fails for you is because you're using different instances of GetItemByIdOptions class. First you "record" that when service.GetItem will be called with new GetItemByIdOptions(idGuid), it should return your product. And then you call service.GetItem with some other new GetItemByIdOptions(idGuid). Yes, both ...


2

I would do some code changes, starting with your public Item GetItem(string dataSourceId) method. You can easily replace this without using the GetItem(dataSourceId): public Item GetDataSourceItem() { return RenderingContext.CurrentOrNull.Rendering.Item; } To write a unittest for the datasourceItem you could have something like this: private readonly Db ...


1

This code should be enough: var bucketItem = db.GetItem(bucketId); bucketItem.Editing.BeginEdit(); bucketItem[Sitecore.Buckets.Util.Constants.IsBucket] = "1"; bucketItem.Editing.EndEdit(); You don't need to set BucketableField to "1"; The reason why your test doesn't work is that when you call BucketManager.IsBucket it calls BucketManager.Provider....


1

It does not have to be TDS. You can use items that you have serialized in Sitecore. Go to the Developer Toolbar, and then click on Serialize Item / Serialize Tree.


Only top voted, non community-wiki answers of a minimum length are eligible