Skip to content

Static Mocking by Telerik JustMock

Akira Sugiura edited this page Oct 12, 2015 · 11 revisions

This is one of the series that implements the samples that are in the official documents of JustMock, part 3. Let's migrate Static Mocking samples to Prig.

In this sample, as same as the previous, I employ the configuration that is added multiple projects to one solution because these are series(see also Final Mocking, Sealed Mocking). Let me continue explanation with Package Manager Console and PowerShell in the same way as the previous example Sealed Mocking. Each used command was explained in the previous example, so for more details, please see also it.

OK, let's make Stub Settings File:

PS 10.JustMockMigration> $TargetReferencedAssembly.GetTypes()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    Foo                                      System.Object
False    False    FooInternal                              System.Object
True     False    FooStatic                                System.Object
True     False    Bar                                      System.Object
True     False    BarExtensions                            System.Object


PS 10.JustMockMigration> $TargetReferencedAssembly.GetTypes() | pfind

Method
------
Void Submit()
Int32 Execute(Int32)
Int32 get_FooProp()
Void set_FooProp(Int32)
Void .cctor()
Void .ctor()
Void DoIt()
Void .ctor()
Void Do()
Void Execute()
Void .ctor()
Int32 Echo(StaticMockingMigration.Bar, Int32)


PS 10.JustMockMigration> $TargetReferencedAssembly.GetTypes() | pfind | pget | clip    # Paste to StaticMockingMigration.v4.0.30319.v1.0.0.0.prig
PS 10.JustMockMigration> exit

PS 10.JustMockMigration> $TargetReferencedAssembly.GetTypes() | ? { $_.Name -eq 'httpcontext' }

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    HttpContext                              System.Object


PS 10.JustMockMigration> $TargetReferencedAssembly.GetTypes() | ? { $_.Name -eq 'httpcontext' } | pfind -m 'get_current\b'

Method
------
System.Web.HttpContext get_Current()


PS 10.JustMockMigration> $TargetReferencedAssembly.GetTypes() | ? { $_.Name -eq 'httpcontext' } | pfind -m 'get_current\b' | pget | clip    # Paste to System.Web.v4.0.30319.v4.0.0.0.prig
PS 10.JustMockMigration> exit

Go back Visual Studio, paste to each indirection setting StaticMockingMigration.v4.0.30319.v1.0.0.0.prig, System.Web.v4.0.30319.v4.0.0.0.prig. Is the build successful? OK. Let's migrate actually!

###Static Constructor Mocking The Indirection Stub for a static constructor is named StaticConstructor literally:

[Test]
public void Prig_should_arrange_static_function()
{
    using (new IndirectionsContext())
    {
        // Arrange
        PFoo.StaticConstructor().Body = () => { };
        PFoo.FooPropGet().Body = () => 0;

        
        // Act
        var actual = Foo.FooProp;

        
        // Assert
        Assert.AreEqual(0, actual);
    }
}

###General Static Method Mocking This is general static method mocking. Well, it seems that collaborating with Moq is more easily understandable:

[Test]
public void Prig_should_throw_when_not_arranged()
{
    using (new IndirectionsContext())
    {
        // Arrange
        PFoo.StaticConstructor().Body = () => { };

        var executeMock = new Mock<IndirectionFunc<int, int>>(MockBehavior.Strict);
        executeMock.Setup(_ => _(10)).Returns(10);
        PFoo.ExecuteInt32().Body = executeMock.Object;

        var submitMock = new Mock<IndirectionAction>(MockBehavior.Strict);
        PFoo.Submit().Body = submitMock.Object;


        // Act, Assert
        Assert.AreEqual(10, Foo.Execute(10));
        Assert.Throws<MockException>(() => Foo.Submit());
    }
}

By the way, I like Assert.Throws than ExpectedException personally. Because in the case of using ExpectedException, even if the exception is occurred at unintended place(e.g. in the above example, when Foo.Execute(10) throws the exception), the test will be performed successfully.

###Mocking Static Property Get Replace the getter of an static property. I think I have explained several times, but... I introduce just in case :)

[Test]
public void Prig_should_fake_static_property_get()
{
    using (new IndirectionsContext())
    {
        // Arrange
        PFoo.StaticConstructor().Body = () => { };

        var called = false;
        PFoo.FooPropGet().Body = () => { called = true; return 1; };

        
        // Act
        var actual = Foo.FooProp;

        
        // Assert
        Assert.AreEqual(1, actual);
        Assert.IsTrue(called);
    }
}

###Mocking Static Property Set Replace the setter of an static property:

[Test]
public void Prig_should_fake_static_property_set()
{
    using (new IndirectionsContext())
    {
        // Arrange
        PFoo.StaticConstructor().Body = () => { };

        var fooPropSetMock = new Mock<IndirectionAction<int>>(MockBehavior.Strict);
        fooPropSetMock.Setup(_ => _(10));
        PFoo.FooPropSetInt32().Body = fooPropSetMock.Object;

        
        // Act, Assert
        Foo.FooProp = 10;
    }
}

About the way of the verification, there is a little difference from JustMock's example. Personally, I think that it doesn't need to verify again whether the method is called by the condition if specifying MockBehavior.Strict. Because the exception is thrown automatically if the method is called by unsatisfied condition.

###Mocking Internal Static Call This example is replacing an internal static method. I think that it doesn't just leave comments, but it should verify that any exceptions aren't thrown:

[Test]
public void Prig_should_fake_internal_static_call()
{
    using (new IndirectionsContext())
    {
        // Arrange
        PFooInternal.DoIt().Body = () => { };

        
        // Act, Assert
        Assert.DoesNotThrow(() => FooInternal.DoIt());
    }
}

###Mocking Static Class This example is replacing the method of a static class. It doesn't seem that I have to explain something :)

[Test]
public void Prig_should_mock_static_class()
{
    using (new IndirectionsContext())
    {
        // Arrange
        PFooStatic.Do().Body = () => { };


        // Act, Assert
        Assert.DoesNotThrow(() => FooStatic.Do());
    }
}

###Mocking Current HttpContext This is the example that replaces current HTTP context. In fact, the original procedure is only valid during HTTP request, but there is no longer limit.

[Test]
public void Prig_should_assert_mocking_http_context()
{
    using (new IndirectionsContext())
    {
        // Arrange
        var called = false;
        PHttpContext.CurrentGet().Body = () => { called = true; return null; };


        // Act
        var ret = HttpContext.Current;


        // Assert
        Assert.IsTrue(called);
    }
}

###Mocking Extension Methods This is replacing an extension method. As it turned out, an extension method is an static method. So it can be replaced as same as the previous examples.

[Test]
public void Prig_should_fake_extension_method()
{
    using (new IndirectionsContext())
    {
        // Arrange
        var foo = new Bar();

        var echoMock = new Mock<IndirectionFunc<Bar, int, int>>();
        echoMock.Setup(_ => _(foo, 10)).Returns(11);
        PBarExtensions.EchoBarInt32().Body = echoMock.Object;


        // Act
        var actual = foo.Echo(10);


        // Assert
        Assert.AreEqual(11, actual);
    }
}

Complete source code is here.