Telerik Forums
JustMock Forum
6 answers
157 views
This may already be answered and I am just not searching for the right keywords but I will ask it again....

Within my Architecture I have 2 Interfaces (one public lets call it ISpecificBlockEntity which implements IBlockEntity, and one internal  IBlockEntitySetup).
I then have an object that implements both of these interfaces.  Within my code I have the following generic method:
public TResult CreateEmptyEntity<TResult>() where TResult : IBlockEntity
      {
          var result = DependencyInjector.InjectEntity<TResult>();
 
          var setupEntity = (result as IBlockEntitySetup);
          if (setupEntity == null)
          {
              throw new EntitySetupNotSupportedException(
                  "Entity type requested does not support construction through this method.");
          }
          return result = setupEntity.CreateEmptyEntity‎<TResult>();
      }

as you can see I don't want the functionality available in IBlockEntitySetup exposed outside of my library so I made that interface internal (the method shown in the entry point into the library).

What I need to do is mock an object for result (which is easy Mock.Create<ISpecificBlockEntity>()), and mock that same object as an IBlockEntitySetup so I can arrange the CreateEmptyEntity method to do nothing (and so setupEntity does not return null).
Here is the unit test for reference....
[Test]
       public void Test0010DependencyInjectionGetMethodCalledOnceWithCorrectType()
       {
           var mockedTower = Mock.Create<ITowerConfiguration>();
           var mockedTowerSetup = mockedTower as IBlockEntitySetup;
 
           Mock.Arrange(() => mockedTowerSetup.CreateEmptyEntity<ITowerConfiguration>()).DoNothing();
           Mock.Arrange(() => InjectorMock.InjectEntity<ITowerConfiguration>()).Returns(mockedTowerSetup as ITowerConfiguration).OccursOnce();
 
           Target.CreateEmptyEntity<ITowerConfiguration>();
 
           Mock.Assert(Target);
       }
This isn't working, it says the profiler must be enabled to mock/asset target IBlockEntitySetup.CreateEmptyEntity() method.
I have also tried replacing mockedTowerSetup with (mockedTower as IBlockEntitySetup) in the arrange statement, but then I get a Not Implemented exception (which is odd since it should be mocked.....).

Debugging for whatever reason isn't working right even with the profiler disabled....

Is there anyway to do this? Am I coming at this from the wrong direction? Any help is greatly appreciated.

Ricky
Telerik team
 answered on 22 Oct 2012
1 answer
140 views
I have determined that the following works:

public class TestCase1
{
    static TestCase1()
    {
        Mock.Replace<FileInfo, bool>(x => x.Exists).In<TestCase1>();
    }
 
    [Theory]
    [InlineData(false)]
    [InlineData(true)]
    public void MockedFileExists(bool expected)
    {
        FileInfo file = Helper.GetMockedFile(expected);
 
        bool actual = file.Exists;
 
        Assert.Equal(expected, actual);
    }
}
 
public class TestCase2
{
    static TestCase2()
    {
        Mock.Replace<FileInfo, bool>(x => x.Exists).In<TestCase2>();
    }
 
    [Theory]
    [InlineData(false)]
    [InlineData(true)]
    public void MockedFileExists(bool expected)
    {
        FileInfo file = Helper.GetMockedFile(expected);
 
        bool actual = file.Exists;
 
        Assert.Equal(expected, actual);
    }
}
 
public class Helper
{
    public static FileInfo GetMockedFile(bool exists)
    {
        FileInfo file = Mock.Create<FileInfo>("c:\\test.jpg");
        Mock.Arrange(() => file.Exists).Returns(exists);
        return file;
    }
}

I have two questions regarding the previous code:

  1. Is there a way I can specify the Mock.Replace once and not have to specify it in every code file I use the helper method?
  2. WIth this approach I have to add a Mock.Replace method for each method that I want to mock.  in cases where I am mocking multiple method calls is there a way to avoid having to specify a Mock.Replace for each method?
Kaloyan
Telerik team
 answered on 19 Oct 2012
1 answer
111 views
I have been reworking some classes to make them more testable.  I need to be able to test the constructor to make sure that it throws an exception when I have images that are different sizes.  The problem is that I am no longer creating this class using a List<Bitmap> because I need to know the file name for the image. 

My question is how can I mock the property that is used to get the image list before creating an instance of the class to determine if it throws an exception?

Update:

At this point I have been able to get a valid test working using the following code and xUnit:

public class MockTest
{
    [Fact]
    public void ShouldThrowExceptionWhenImagesAreDifferentSizes()
    {                     
        Foo foo = null;
        Mock.Arrange(() => foo.GetImageList()).Returns(new List<Bitmap> { new Bitmap(100, 100), new Bitmap(200, 200) });
 
        Assert.Throws<ApplicationException>(() => foo = new Foo(null));
    }
 
    public class Foo
    {         
        public Foo(List<FileInfo> files)
        {
            this.CheckImageDimensions();          
        }
 
        public void CheckImageDimensions()
        {
            Bitmap firstImage = this.Images.FirstOrDefault();
            Bitmap invalidImage = this.Images.Where(x => x.Width != firstImage.Width || x.Height != firstImage.Height).FirstOrDefault();
 
            if (invalidImage != null)
                throw new ApplicationException("Images with different dimensions are not supported.");
        }
  
        private List<Bitmap> _imageList;
             
        public List<Bitmap> Images
        {
            get
            {
                if (this._imageList != null)
                    return this._imageList;
                                                        
                this._imageList = this.GetImageList();
                return this._imageList;
            }
        }
                     
        public List<Bitmap> GetImageList()
        {
            throw new NotImplementedException();
        }
    }
}

The problem I have at the moment is that when I change:

Mock.Arrange(() => foo.GetImageList()).Returns(new List<Bitmap> { new Bitmap(100, 100), new Bitmap(200, 200) });

To

Mock.Arrange(() => foo.Images).Returns(new List<Bitmap> { new Bitmap(100, 100), new Bitmap(200, 200) });

The unit test will fail because it is not retuning the list of images that I created using Mock.Arrange().  Can someone please let me know what I need to do differently to get this to work?
Ricky
Telerik team
 answered on 15 Oct 2012
2 answers
94 views
I'm using the Paid version but can't seem to mock an extension method -- I've tried the following
Mock.Arrange(() => target.SomeExtensionMethod(1)).DoNothing();

where target is a concrete (non-mocked) object as well as just

Mock.Arrange(() => StaticClass.AddLinkableObject(1)).DoNothing();

Where StaticClass is the class where the extension method is defined.

As soon as my code hits the Arrange line I get the following exception-

Profiler must be enabled to mock/assert target blah, blah method.

Thanks
Ricky
Telerik team
 answered on 15 Oct 2012
1 answer
116 views
I am sure I am doing something wrong but I can't for the life of me figure it out.... (of course it doesn't help that I can't debug the application reliably with the profiler enabled....)
So here is my challenge and hopefully someone can help me with it...
I have the following production method:
public TResult CreateEmptyEntity<TResult>() where TResult : IBlockEntity
        {
            var result = DependencyInjector.Get<TResult>();
 
            var setupEntity = (result as IBlockEntitySetup);
            if (setupEntity == null)
            {
                throw new EntitySetupNotSupportedException(
                    "Entity type requested does not support construction through this method.");
            }
            return result = setupEntity.CreateEmptyEntity‎<TResult>();
        }

This method is using Ninject (as an internal property to this class (DependencyInjector is of type IKernel) to get the appropriate object to use for result....

I am trying to unit test this method with the following method:
[TestFixture]
    public class ProtocolABlockTranslatorTestBase
    {
        protected ProtocolABlockTranslator Target;
        protected IKernel KernelMock;
 
        [SetUp]
        public void BaseInitializer()
        {
            KernelMock = new StandardKernel();
            Target = Mock.Create<ProtocolABlockTranslator>(Constructor.Mocked, Behavior.CallOriginal);
        }
 
    }
 
[TestFixture]
    public class CreateEmptyEntityTests : ProtocolABlockTranslatorTestBase
    {
        [SetUp]
        public void MyInitialization()
        {
        }
 
        [Test]
        public void Test0010DependencyInjectionGetMethodCalledOnceWithCorrectType()
        {
            KernelMock.Bind<ITowerConfiguration>().To<MockedTowerConfigSetup>();
            Mock.Arrange(() => KernelMock.Get<ITowerConfiguration>()).OccursOnce();
 
            Target.DependencyInjector = KernelMock;
 
            Target.CreateEmptyEntity<ITowerConfiguration>();
 
            Mock.Assert(KernelMock);
        }
    }

Unfortunately its not working..  I am encountering my custom exception inside the if block (although when I look at result it equals null as I am attempting to debug (which is not working right due to the profiler being enabled).

I am just trying to verify that a call to my production method with a certain templated type then results in a call to get with the same type.
Any thoughts?

Ricky
Telerik team
 answered on 11 Oct 2012
1 answer
94 views
Hello,
we have the following Problem:
We are using the latest version of JustMock. We have a large set of unit- and integrationtests (about 2000 tests). We are running the tests using nunit. Sometimes in our test we have to use real instances of some classes and sometimes mocks of these classes. So to get this work we used the Mock.Initialize<Class>() Method in our test.
In my Example, all tests are green, but when we use the initialization, the runtime of the all test-methods rise from 1.2sec to 25sec. We use a lot of instances in the tests (about 200). The problem is, that the runtime for each testmethod rises from test to test.
In our real test the runtime for one test rises from 30 seconds to  25 minuts. This is an inaccettabile fact.
Is this a known issue for you? Are there any workarounds except not using the Initialize method?

I have included two screenshots from nunit.
Example: Calling the same test-method for 25 times. You can the runtime rising for each method:

(26 tests), [0:25.530] Success JustMockExampleTest (26 tests), [0:25.530] Success PersonManagerTestWithInit (26 tests), [0:25.530] Success _00EditPerson_WhyInitialize_ExpectedBehavior, [0:00.418] Success _01EditPerson_Creating_LotsOfPersons_ExpectedBehavior, [0:00.613] Success _02EditPerson_Creating_LotsOfPersons_ExpectedBehavior, [0:00.602] Success _03EditPerson_Creating_LotsOfPersons_ExpectedBehavior, [0:00.638] Success _04EditPerson_Creating_LotsOfPersons_ExpectedBehavior, [0:00.672] Success _05EditPerson_Creating_LotsOfPersons_ExpectedBehavior, [0:00.714] Success _06EditPerson_Creating_LotsOfPersons_ExpectedBehavior, [0:00.743] Success _07EditPerson_Creating_LotsOfPersons_ExpectedBehavior, [0:00.783] Success _08EditPerson_Creating_LotsOfPersons_ExpectedBehavior, [0:00.822] Success _09EditPerson_Creating_LotsOfPersons_ExpectedBehavior, [0:00.855] Success _10EditPerson_Creating_LotsOfPersons_ExpectedBehavior, [0:00.891] Success _11EditPerson_Creating_LotsOfPersons_ExpectedBehavior, [0:00.922] Success _12EditPerson_Creating_LotsOfPersons_ExpectedBehavior, [0:00.962] Success _13EditPerson_Creating_LotsOfPersons_ExpectedBehavior, [0:00.994] Success _14EditPerson_Creating_LotsOfPersons_ExpectedBehavior, [0:01.029] Success _15EditPerson_Creating_LotsOfPersons_ExpectedBehavior, [0:01.061] Success _16EditPerson_Creating_LotsOfPersons_ExpectedBehavior, [0:01.100] Success _17EditPerson_Creating_LotsOfPersons_ExpectedBehavior, [0:01.139] Success _18EditPerson_Creating_LotsOfPersons_ExpectedBehavior, [0:01.167] Success _19EditPerson_Creating_LotsOfPersons_ExpectedBehavior, [0:01.206] Success _20EditPerson_Creating_LotsOfPersons_ExpectedBehavior, [0:01.252] Success _21EditPerson_Creating_LotsOfPersonsOnlyArrange_ExpectedBehavior, [0:01.272] Success _22EditPerson_Creating_LotsOfPersonsOnlyArrange_ExpectedBehavior, [0:01.269] Success _23EditPerson_Creating_LotsOfPersonsOnlyArrange_ExpectedBehavior, [0:01.276] Success _24EditPerson_Creating_LotsOfPersonsOnlyArrange_ExpectedBehavior, [0:01.290] Success _25EditPerson_Creating_LotsOfPersonsOnlyArrange_ExpectedBehavior, [0:01.299] Success

Thank you very much.
Christian
Ricky
Telerik team
 answered on 10 Oct 2012
4 answers
105 views
Hi,

I have been having problems with version 2012.2.608 of JustMock. TFs build definitions which make use of the JustMock workflow activities fail instantly. Installing the previous version of JM fixes this issue.

What I think is happening is that the Telerik.JustMock.Build.Workflow.dll Assembly now has a dependency on Microsoft.TeamFoundation.Build.Client Version 11.0.0.0 which is part of TFS 11 which I think still is in beta. We don’t have this version of the assembly so the build server fails instantly. Using Reflector I can see that the previous version of JM depended on Microsoft.TeamFoundation.Build.Client Version 10.0.0.0

Please look into this.

Thanks!

Ricky
Telerik team
 answered on 10 Oct 2012
1 answer
215 views
Hi,

I've started using JustMock and I'm wondering how to replicate the example Rhino Mocks sample given here:
http://stackoverflow.com/questions/9364254/verifying-event-handler-exists-in-moq-vs-rhino-mocks

My example is similar to that posted above.
I have an IView that exposes an Event.
I have a Presenter class that takes an IView in its constructor and then attaches to the IView Event.

I want to test that the presenter is actually subscribing to the IView event in its constructor.

Is there a way to do this with JustMock, like how it's shown in the Rhino Mocks example?

Thanks.

Edit Update:

I think I figured it out. Is this correct?

var view = Mock.Create<IView>();
Mock.ArrangeSet(() => view.MyEvent += null).IgnoreArguments().OccursOnce();
 
var presenter = Mock.Create<Presenter>(view);
 
Mock.Assert(view);
Ricky
Telerik team
 answered on 09 Oct 2012
7 answers
129 views
Hi

I'm trying to unit test an ExecuteResult() method of a custom ActionResult. The method uses UrlHelper.GenerateUrl() method to generate the url for given action and controller.
Url = UrlHelper.GenerateUrl(null, Action, Controller, new RouteValueDictionary(RouteValues), RouteTable.Routes, context.RequestContext, true);
In the unit test I'm constructing the ControllerContext like such:
var request = Mock.Create<HttpRequestBase>();
var httpContext = Mock.Create<HttpContextBase>();
Mock.Arrange(() => httpContext.Request).Returns(request);
var controllerContext = new ControllerContext(httpContext, new RouteData(), new TestDummyController());
And then setting static mock for the UrlHelper:
Mock.SetupStatic<UrlHelper>(Behavior.CallOriginal);
When the runtime hots the GenerateUrl method I'm getting the System.Security.VerificationException "Operation could destabilize the runtime.". The stack trace is not very helpful:
at System.Web.Mvc.UrlHelper.GenerateUrl(String routeName, String actionName, String controllerName, RouteValueDictionary routeValues, RouteCollection routeCollection, RequestContext requestContext, Boolean includeImplicitMvcValues)
at Symantec.Web.Mvc.JavaScriptRedirectResult.ExecuteResult(ControllerContext context) in D:\Code\_wsfederation\Applications\IdentityHub\Symantec.Web.Mvc\JavaScriptRedirectResult.cs:line 59
at Symantec.Web.Mvc.Tests.JavaScriptRedirectResultTest.ExecuteResult_Redirecs_To_Action() in D:\Code\_wsfederation\Applications\IdentityHub\Symantec.Web.Mvc.Tests\JavaScriptRedirectResultTest.cs:line 109

The GenerateUrl() method works fine when I remove static mock declaration but that makes the whole test pointless. Any help please?
Ricky
Telerik team
 answered on 04 Oct 2012
1 answer
100 views
I'm trying to mock a method call with a matcher, but JustMock fails to intercept the call properly. This is a test that fails for me:

[Fact]
public void ArrangeDoesNotMatchArguments()
{
    string value1 = "Hello";
    string value2 = "World";
 
    var session = Mock.Create<IMockable>();
 
    Mock.Arrange(() => session.Get<string>(Arg.Matches<string[]>(v => v.Contains("Lol") &&
                                             v.Contains("cakes"))))
        .Returns(new[]
                 {
                     value1,
                     value2,
                 });
 
    var testValues = new[]
                     {
                         "Lol",
                         "cakes"
                     };
 
    var result = session.Get<string>(testValues);
 
    Assert.Contains(value1, result);
    Assert.Contains(value2, result);
}
 
public interface IMockable
{
    T[] Get<T>(params string[] values);
}
I'm using JustMock Q2 2012 SP1 (2012.2.813.9).
Ricky
Telerik team
 answered on 01 Oct 2012
Narrow your results
Selected tags
Tags
+? more
Top users last month
Anislav
Top achievements
Rank 6
Silver
Bronze
Bronze
Jianxian
Top achievements
Rank 1
Iron
Marco
Top achievements
Rank 3
Iron
Iron
Iron
Jim
Top achievements
Rank 2
Iron
Iron
Nurik
Top achievements
Rank 2
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Anislav
Top achievements
Rank 6
Silver
Bronze
Bronze
Jianxian
Top achievements
Rank 1
Iron
Marco
Top achievements
Rank 3
Iron
Iron
Iron
Jim
Top achievements
Rank 2
Iron
Iron
Nurik
Top achievements
Rank 2
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?