Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Chris Mahoney 240 posts 452 karma points
    Jul 09, 2024 @ 02:08
    Chris Mahoney
    0

    Unit testing a SurfaceController

    Hi everyone,

    I think I need a bit of a sanity check here.

    In a SurfaceController I'm saving an image into an existing media item:

    IMedia media = _services.MediaService.GetById(guidGoesHere);
    media.SetValue(_mediaFileManager, _mediaUrlGenerators, _shortStringHelper, _contentTypeBaseServiceProvider, Constants.Conventions.Media.File, fileName, memoryStream);
    _services.MediaService.Save(media);
    

    This works correctly, but to get it going I had to add MediaFileManager etc. to the controller constructor. So my first question is whether this is the "best" way to do this.

    If it is, then I can move onto my actual question. I'm trying to set up some unit tests around this controller, using the example code at https://docs.umbraco.com/umbraco-cms/implementation/unit-testing#testing-a-surfacecontroller.

    The line in the SetUp method - as supplied in the example - fails to compile because it's not passing in a MediaFileManager. If I try to use Mock.Of<MediaFileManager>() then it compiles, but crashes with "Type to mock (MediaFileManager) must be an interface, a delegate, or a non-sealed, non-static class." There doesn't seem to be such as thing as an IMediaFileManager.

    What's the trick to get this working?

  • Chris Mahoney 240 posts 452 karma points
    Jul 11, 2024 @ 00:01
    Chris Mahoney
    0

    I've managed to get further:

    var mediaFileManager = new MediaFileManager(Mock.Of<IFileSystem>(), Mock.Of<IMediaPathScheme>(), NullLoggerFactory.Instance.CreateLogger<MediaFileManager>(), Mock.Of<IShortStringHelper>(), Mock.Of<IServiceProvider>());
    

    I then pass in mediaFileManager instead of Mock.Of<MediaFileManager>(). All is well. Almost.

    As I'd expect from a mocked implementation, attempting to create a content item doesn't do anything. The page I linked above says "you might want to start looking into replacing them with actual implementations" but I'm struggling to find any information around how to actually do this.

    So, in short, how do I create a content item from a unit test?

Please Sign in or register to post replies

Write your reply to:

Draft