Quantcast
Viewing all articles
Browse latest Browse all 21

Sitecore unit testing with test fixtures – media library support added

I recently wrote a post on Sitecore unit testing with test fixtures. I’ve now added support for the media library (updated in the project on GitHub).

So now, you can also unit test code that imports an image into the media library.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
        /// <summary>
        /// Imports an image into the root of the Sitecore media library
        /// </summary>
        /// <param name="sampleImage"></param>
        public static void ImportImage(string sampleImage)
        {
            FileInfo imageFile = new FileInfo(sampleImage);
            Item parentItem = Sitecore.Context.Database.GetItem("/sitecore/media library");

            var mediaCreatorOptions = new MediaCreatorOptions();
            mediaCreatorOptions.Database = Sitecore.Context.Database;
            mediaCreatorOptions.Language = Sitecore.Context.Language;
            mediaCreatorOptions.Versioned = false;
            mediaCreatorOptions.Destination = string.Format("{0}/{1}", parentItem.Paths.FullPath, ItemUtil.ProposeValidItemName(Path.GetFileNameWithoutExtension(sampleImage)));
            mediaCreatorOptions.FileBased = Sitecore.Configuration.Settings.Media.UploadAsFiles;

            var mc = new MediaCreator();
            mc.CreateFromFile(sampleImage, mediaCreatorOptions);
        }

And here’s some code to check if it works correctly.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
        [TestMethod]
        [Description("Tests the import of an image into the media library")]
        public void TestImageImport()
        {
            string sampleImage = ConfigurationManager.AppSettings["sampleimage"];
            SampleSitecoreLogic.ImportImage(sampleImage);

            // Get the imported media item
            MediaItem imported = new MediaItem(Sitecore.Context.Database.GetItem("/sitecore/media library/Cdm"));

            Assert.IsNotNull(imported, "Imported image could not be found");
            Assert.AreEqual("Image", imported.InnerItem.TemplateName);

            // Get the imported image data and put it in a memory stream
            MemoryStream memoryStream = new MemoryStream();
            imported.GetMediaStream().CopyTo(memoryStream);

            Assert.IsTrue(
                Sitecore.IO.FileUtil.ReadBinaryFile(sampleImage).SequenceEqual(memoryStream.ToArray()),
                "The imported image's content is different from the file");
        }

Viewing all articles
Browse latest Browse all 21

Trending Articles