Telerik Forums
JustMock Forum
10 answers
223 views
Hello.  I am having some difficulty getting an update to JustMock working for our existing unit test library. 

Details:
We were on 2013.2.611 and have upgraded to 2014.2.811.1. 
We use TFS Build to run unit tests (under MSTest).  I have already set up the code activity (including environmental settings) from the last version based on the JustMock guide and it was working with 100% success rate on the old version. 
I updated the library to latest one from the new JustMock installation. 

Builds completes and most of the JustMock related unit tests are failing with many similar error messages such as:
Telerik.JustMock.MockException: Arranging the return value of a constructor call is not supported.
Telerik.JustMock.MockException: Can not instantiate proxy of class: Could not find a parameterless constructor.

Are there any major changes between the versions that could be causing this?  Something I forgot to update?

Sven
Top achievements
Rank 1
 answered on 18 Sep 2014
3 answers
149 views
Hi, I've been having some trouble passing a list to a class that is the instance of a MockingContainer. 
01.using System.Collections.Generic;
02. 
03.namespace JustMock_AutoContainer
04.{
05.    public interface IWorker
06.    {
07.        void DoSomething();
08.    }
09. 
10.    public interface IService
11.    {
12.        string Moo { get; }
13. 
14.        void DoLotsOfThings();
15.    }
16. 
17.    public class Service : IService
18.    {
19.        private readonly IList<IWorker> workers;
20. 
21.        public Service(IList<IWorker> workers, string moo)
22.        {
23.            this.workers = workers;
24.            this.Moo = moo;
25.        }
26. 
27.        public string Moo { get; private set; }
28. 
29.        public void DoLotsOfThings()
30.        {
31.            foreach (var worker in this.workers)
32.            {
33.                worker.DoSomething();
34.            }
35.        }
36.    }
37.}

And the test class is:
01.using JustMock_AutoContainer;
02.using Microsoft.VisualStudio.TestTools.UnitTesting;
03.using System.Collections.Generic;
04.using Telerik.JustMock;
05.using Telerik.JustMock.AutoMock;
06.using Telerik.JustMock.Helpers;
07. 
08.namespace JustMock_AutoContainer_Tests
09.{
10.    [TestClass]
11.    public class ServiceTest
12.    {
13.        #region Fields
14.        private MockingContainer<Service> container;
15.        #endregion
16. 
17.        #region Test Configuration
18.        [TestInitialize]
19.        public void CreateTargetContainer()
20.        {
21.            this.container = new MockingContainer<Service>();
22.        }
23.        #endregion
24. 
25.        [TestMethod]
26.        public void DoLotsOfWork_TwoWorkers_AllWorkersCalled()
27.        {
28.            // Arrange
29.            var provider1 = StubWorker();
30.            var provider2 = StubWorker();
31.            var target = this.CreateTarget(provider1, provider2);
32. 
33.            // Act
34.            target.DoLotsOfThings();
35. 
36.            // Assert
37.            Assert.AreEqual("moo", target.Moo);
38.            provider1.Assert(p => p.DoSomething()); // Fails here :(
39.            provider2.Assert(p => p.DoSomething());
40.        }
41. 
42.        #region Support Methods
43.        private static IWorker StubWorker()
44.        {
45.            var dataTraceProvider = Mock.Create<IWorker>();
46.            return dataTraceProvider;
47.        }
48. 
49.        private IService CreateTarget(params IWorker[] providers)
50.        {
51.            this.container
52.                    .Bind<IList<IWorker>>()
53.                    .ToConstant((IList<IWorker>)providers);
54. 
55.            //TODO: fix line above; the list is not being picked up in the target.
56.            // JustMock seems keen on giving us a list with one and only one item in it, rather than
57.            // what we've registered above.
58.            this.container
59.                    .Bind<string>()
60.                    .ToConstant("moo");
61. 
62.            return this.container.Instance;
63.        }
64. 
65.        #endregion
66.    }
67.}

The registration on line 51 seems to be ignored.  Is there something else I should be doing?
Stefan
Telerik team
 answered on 10 Sep 2014
1 answer
97 views
Hi,
The following code does not work...
public interface IService2
{
    string MethodWithArgs(string one, string two);
}
 
[TestMethod]
public void SubbingMethodwithArgs_DontCareAboutValues_StubbedMethodCalled()
{
    var service = StubMethodWithArgs("rv");
    var actual = service.MethodWithArgs("a", "b");
    Assert.AreEqual("rv", actual);
}
 
private static IService2 StubMethodWithArgs(string returnValue, string expectedOne = null, string expectedTwo = null)
{
    var service = Mock.Create<IService2>();
    service
       .Arrange(s => s.MethodWithArgs(
            null != expectedOne ? Arg.Is(expectedOne) : Arg.AnyString,  // null coalesance (??) doesn't work either
            null != expectedTwo ? Arg.Is(expectedTwo) : Arg.AnyString))
       .Returns(returnValue);
    return service;
}


Is this a limitation of JustMock?

Regards,

Nick
Stefan
Telerik team
 answered on 26 Aug 2014
1 answer
192 views
Hi, is it possible to use MockingContainer<T> where T is an abstract class, such as the following:

01.public abstract class SimpleBaseClass
02.{
03.    private readonly IService service;
04.    protected SimpleBaseClass(IService service)
05.    {
06.        this.service = service;
07.    }
08.    public void CallServiceMethod()
09.    {
10.        this.service.DoLotsOfThings();
11.    }
12.}

I've tried the following, the latter works as expected. 
01.[TestMethod]
02.public void AutoMock_AbstractClass_CallsMethod()
03.{
04.    var container = new MockingContainer<SimpleBaseClass>();
05.    //container.Bind<SimpleBaseClass>().ToMock(); // Still fails :(
06.    container.Arrange<IService>(s => s.DoLotsOfThings()).MustBeCalled();
07. 
08.    container.Instance.CallServiceMethod();
09. 
10.    container.AssertAll();
11.}
12. 
13.[TestMethod]
14.public void CreateMock_AbstractClass_CallsMethod()
15.{
16.    var service = Mock.Create<IService>();
17.    var target = Mock.Create<SimpleBaseClass>(Behavior.CallOriginal, service);
18. 
19.    target.CallServiceMethod();
20. 
21.    service.Assert(s => s.DoLotsOfThings());
22.}

I've tried configuring with AutoMockSettings using CallOriginal, but it just seems like NInject always jumps in and fails to find a suitable constructor.
Tsvetomir
Telerik team
 answered on 22 Aug 2014
2 answers
454 views
Can I (or does it make sense) call a private method from a unit test? 

The setup code is getting really big to test a little piece of code within a private method. Instead it seems like it might be a good idea to just mock the parameters and then call the private method as follows (incomplete since I don't know if this works). I want to call a piece of the private implementation with defined parameters and then test for results. This would be a replacement for having to walk through the code in the debugger over and over again. 

// Arrange mock data.
var service = new ScheduledTaskService();
var start = new DateTime(2014, 08, 15);
var due = start.Next(DayOfWeek.Thursday);
var assignee = new SimpleEmployeeView {Id = 1, LastNameFirstName = "Test User", IsActive = true};
var taskModel = new ScheduledTaskModel()
{
    DaysBeforeDue = 5,
    Start = start,
    End = due,
    Title = "Test Subject",
    Description = "Test Description",
    Id = 999
};
 
// This is the method I would like to call somehow if possible. 
Mock.NonPublic.Arrange(service, "CreateTaskForAssignee", taskModel, assignee);
 
// Ignore db changes. 
var database = Mock.Create<Database>();
Mock.Arrange(database, d => d.SaveChanges()).DoNothing();

// TODO test for changes in the result.


Todor
Telerik team
 answered on 21 Aug 2014
4 answers
78 views
I figure this out... but I know it won't be very complicated.
I am calling this method and I want to mock the string "alpha" 

public void Request()
{
     if (string.isNullOrEmpty(alpha))
      {
           Do somthing bad
      }
     else
     {
          Do somthing good
      }

Pretty much I want alpha to be mocked so that it passes the if statement and goes on to do something good.
Kaloyan
Telerik team
 answered on 14 Aug 2014
11 answers
166 views
I'm using JustMock to mock out the HttpContext when testing an ASP.Net MVC  controller, below are snapshots of  the stack when I pause the execution:


 Telerik.JustMock.dll!Telerik.JustMock.Core.Context.HierarchicalTestFrameworkContextResolver.CreateAttributeMatcher.AnonymousMethod__26 Normal
  [External Code]  
  XXXXXXXX.Web.Application.dll!XXXXXXXX.Web.Application.Controllers.TransportController.Index() Line 44  
  XXXXXXXX.Tests.dll!XXXXXXTests.Transport.TransportControllerTests.IndexPageTest() Line 36  
  [External Code]  

Telerik.JustMock.dll!Telerik.JustMock.Core.Context.HierarchicalTestFrameworkContextResolver.FindTestMethod Normal
  [External Code]  
XXXXXXXX.Web.Application.dll!XXXXXXXX.Web.Application.Controllers.TransportController.Index() Line 44  
  XXXXXXXX.Tests.dll!XXXXXXXX.Tests.Transport.TransportControllerTests.IndexPageTest() Line 36  
  [External Code]  
Stefan
Telerik team
 answered on 06 Aug 2014
1 answer
102 views
Hi,

Does JustMock support Windows Phone 8.1 WinRT apps? I tried referenced Telerik.JustMock.dll in my project and wrote a sample test, it compiles fine but I get the below runtime error:

UnitTests.SetupTest threw exception. System.IO.FileNotFoundException: System.IO.FileNotFoundException: Could not load file or assembly 'System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified..

Is it a Justmock not supporting WP 8.1 WinRT issue? Or am I missing something?

Thanks,
Tarun
Stefan
Telerik team
 answered on 04 Aug 2014
3 answers
234 views
I'm using Visual Studio 2013. 

I've configured JustMock to "run together with JustMock" all detected profilers, however I'm seeing this exception:

Test Name: IndexPageTest
Test FullName: XXXXXXX.XXXX.Tests.Transport.TransportControllerTests.IndexPageTest
Test Source: c:\XXXXXXXXXXX\XXXXXweb\User Interface\Tests\Transport\TransportControllerTests.cs : line 24
Test Outcome: Failed
Test Duration: 0:00:00

Result Message: Unable to create instance of class XXXXXXX.XXXX.Tests.Transport.TransportControllerTests. 
Error: Telerik.JustMock.Core.ElevatedMockingException: Cannot mock 'XXXXXXX.XXXX.Web.Application.Core.Providers.UserProfileProvider'. 
The profiler must be enabled to mock, arrange or execute the specified target.
Detected active third-party profilers:
* {B61B010D-1035-48A9-9833-32C2A2CDC294} (from process environment)
Disable the profilers or link them from the JustMock configuration utility. Restart Visual Studio and/or the test runner after linking..
Result StackTrace:
at Telerik.JustMock.Core.ProfilerInterceptor.ThrowElevatedMockingException(MemberInfo member)
   at Telerik.JustMock.Core.MocksRepository.InterceptStatics(Type type, IEnumerable`1 mixins, IEnumerable`1 supplementaryBehaviors, IEnumerable`1 fallbackBehaviors, Boolean mockStaticConstructor)
   at Telerik.JustMock.MockBuilder.InterceptStatics(MocksRepository repository, Type type, Nullable`1 behavior, Boolean mockStaticConstructor)
   at Telerik.JustMock.Mock.<>c__DisplayClass67.<SetupStatic>b__66()
   at Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal(Action guardedAction)
   at Telerik.JustMock.Mock.SetupStatic(Type staticType, StaticConstructor staticConstructor)
   at XXXXXXX.XXXX.Tests.Common.ControllerTestBase..ctor() in c:\XXXXXXXXXXX\XXXXXweb\User Interface\Tests\Patient\TransportTest.cs:line 75
   at XXXXXXX.XXXX.Tests.Transport.TransportControllerTests..ctor()


Help!

Thanks in advance,
-bill 
Stefan
Telerik team
 answered on 31 Jul 2014
5 answers
171 views
I am trying to mock this for a unit test... I need help getting all items in here mocked. what I have done does not work and it seems like that the mocks never get hit when they are supposed to. I know that a few of the items are part of our library and may not work on your  machines but if you could help please get it on track and I can run it and straighten it out if needed.

public static string GetEnumDisplayName<T>(string enumName)
        {
            string retVal = null;
            MemberInfo memberInfo = typeof(T).GetMember(enumName).FirstOrDefault();
            if (memberInfo != null)

            {
                object[] customAtts = memberInfo.GetCustomAttributes(typeof(IDisplayName), false);
                if (customAtts != null && customAtts.Length > 0)
                {
                    retVal = ((IDisplayName)customAtts[0]).DisplayName;
                }
                //
                if (retVal == null)
                {
                    customAtts = memberInfo.GetCustomAttributes(typeof(GeneralDisplayNameAttribute), false);
                    if (customAtts != null && customAtts.Length > 0)
                    {
                        retVal = ((GeneralDisplayNameAttribute)customAtts[0]).DisplayName;
                    }
                }
            }
            return retVal;
        }
Matthew
Top achievements
Rank 1
 answered on 29 Jul 2014
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?