Telerik Forums
JustMock Forum
1 answer
405 views

Hi everyone,

 

I'm having problems with the profiler of JustMock.

 

The Unit Test 

[Test]
        public void Profiler_IsEnabled()
        {
            Assert.IsTrue(Mock.IsProfilerEnabled);
        }

currently fails.

 

For certain mocks, I get the error message :

Telerik.JustMock.Core.ElevatedMockingException : Cannot mock 'Microsoft.SharePoint.SPContext'. The profiler must be enabled to mock, arrange or execute the specified target.
Detected active third-party profilers:
* {DA7CFC47-3E35-4c4e-B495-534F93B28683} (from global system environment)
* {DA7CFC47-3E35-4c4e-B495-534F93B28683} (from process environment)
Disable the profilers or link them from the JustMock configuration utility. Restart the test runner and, if necessary, Visual Studio after linking.
   bei Telerik.JustMock.Core.ProfilerInterceptor.ThrowElevatedMockingException(MemberInfo member)
   bei Telerik.JustMock.Core.MocksRepository.InterceptStatics(Type type, IEnumerable`1 mixins, IEnumerable`1 supplementaryBehaviors, IEnumerable`1 fallbackBehaviors, Boolean mockStaticConstructor)
   bei Telerik.JustMock.MockBuilder.InterceptStatics(MocksRepository repository, Type type, Nullable`1 behavior, Boolean mockStaticConstructor)
   bei Telerik.JustMock.Core.MocksRepository.ConvertExpressionToCallPattern(Expression expr, CallPattern callPattern)
   bei Telerik.JustMock.Core.MocksRepository.Arrange[TMethodMock](Expression expr, Func`1 methodMockFactory)
   bei Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal[T](Func`1 guardedAction)
   bei Urlaubswesen.Tests.TestsHelper.GetUrlaubsantragSpListItem(SPUser antragsstellerSpUser, DateTime urlaubsbeginnDateTime, DateTime urlaubsendeDateTime, String urlaubstyp, Boolean sonderurlaub, String begruendungSonderurlaub) in C:\_Weist\Urlaubswesen\Urlaubswesen\Urlaubswesen.Tests\TestsHelper.cs:Zeile 74.
   bei Urlaubswesen.Tests.TestsHelperTests.GetUrlaubsantragMock.GetUrlaubsantragMock_KeinSonderurlaub_IsCorrect() in C:\_Weist\Urlaubswesen\Urlaubswesen\Urlaubswesen.Tests\TestsHelperTests.cs:Zeile 36.

In the event log, I get the information

.NET Runtime version 4.0.30319.0 - Der Profiler wurde erfolgreich geladen. Profiler-CLSID: "{DA7CFC47-3E35-4c4e-B495-534F93B28683}".  Prozess-ID (dezimal): 25912. Meldungs-ID: [0x2507].

 

As you can see on the screenshots, the profiler is enabled in the menu. But I don't know if I selected the right profiler. In the list, no profiler corresponding to JustMock is even available. 

How do I select the right profiler in order to solve this problem?

Thank you very much!

 

 

 

Svetlozar
Telerik team
 answered on 21 Jun 2016
3 answers
213 views

Hi,

  I am facing issue, while calling a Generic method with Private accessor. Below is my sample method which, i would like to Call.

private void PopulateCollection<T>(List<IDataItem> fromCollection, ObservableCollection<T> toCollection)

{  //some code }

 

And my Test method is as below,

[TestMethod]
public void TestPopulateCollection()
{
    var testInstance = new TestVM();
    var privateInstance = new PrivateAccessor(testInstance);
    //declare and set required parameters here for fromCollection & toCollection
    privateInstance.CallMethod("PopulateCollection", fromCollection, toCollection);
    //Assert
}

 

The above code throws exception, "Member not found". 

Is there a possible resolution for it?

 

Thank you,

Sagar

 

Svetlozar
Telerik team
 answered on 02 Jun 2016
12 answers
185 views

The current version of Telerik JustMock Lite does not appear to be supported on the Windows 10 UWP (RTM) platform.

(1) Can you confirm if there is active work underway for JustMock Lite to support this platform?
(2) Can you provide an indication of the estimated release date? I’ll need to make a call to determine if we need to switch to a different mocking framework depending on these timelines.

Background info
Note that UWP (Universal Windows Platform) was referred to as UAP (Universal App Platform) before RTM was released. UWP is the correct term to use for the platform going forwards. Initial project development was on a Windows 10 Universal App (UAP) project in Visual Studio 2015 RC 14.0.22823.1 (Windows 8.1 OS). We can confirm that the mocking behaviour was working with these pre-release tools. After upgrading Windows and Visual Studio from Technical Preview (UAP) to RTM (UWP), we now experience warnings during build output and any tests with mocking behaviour no longer run (throws exception).

Product versions
Microsoft Windows 10 Professional - 10.0.10240.16384 RTM x64 (2015/07/15)
Microsoft Visual Studio 2015 - 14.0.23107.10 RTM (2015/07/10)
Telerik JustMock Lite - 2015.2.715.1 (2015/07/15)

Sample code snippet

1.[TestMethod]
2.public void ExampleTest()
3.{
4.    // This line throws an exception.
5.    var mockLogger = Mock.Create<ILogger>(Behavior.Loose);
6.}

Sample build warning output
C:\Program Files (x86)\Telerik\JustMock Lite\Libraries\Telerik.JustMock.dll : warning MSB3817: The assembly "C:\Program Files (x86)\Telerik\JustMock Lite\Libraries\Telerik.JustMock.dll" does not have a NeutralResourcesLanguageAttribute on it. To be used in an app package, portable libraries must define a NeutralResourcesLanguageAttribute on their main assembly (ie, the one containing code, not a satellite assembly).

Sample debug console output
Exception thrown: 'System.IO.FileLoadException' in MyProj.Win10.Tests.exe
An exception of type 'System.IO.FileLoadException' occurred in MyProj.Win10.Tests.exe but was not handled in user code
Additional information: Could not load file or assembly 'System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
HResult: -2146234304
Source: Telerik.JustMock
Stacktrace: at Telerik.JustMock.Mock.Create[T](Behavior behavior), at MyProj.Win10.ExampleTest()

 

Your feedback would be much appreciated.​ 

Thanks,
Davide

Svetlozar
Telerik team
 answered on 17 May 2016
1 answer
92 views

Hi,

I am trying to do admin area reqistration route unit test.But I have trouble.I asked from stackoverflow but there is no answer yet.Can you look at my question.And Can you help?

Here is my question:http://stackoverflow.com/questions/37117401/asp-net-mvc-arearegistration-route-unit-test-with-telerik-just-mock-lite

Thanks

Svetlozar
Telerik team
 answered on 12 May 2016
1 answer
235 views
Hi,
I can't make OpenCover 4.5.3207.0 profiler work with JustMock 15.1.224
When I run tests I get errors like this:
Cannot mock *. The profiler must be enabled to mock, arrange or execute the specified target.
Detected active third-party profilers:
OpenCover (from process environment)
Disable the profilers or link them from the JustMock configuration utility. Restart the test runner and, if necessary, Visual Studio after linking.

entry from the Event Viewer:
.NET Runtime version 4.0.30319.0 - The profiler was loaded successfully.  Profiler CLSID: '{1542C21D-80C3-45E6-A56C-A9C1E4BEB7B8}'.  Process ID (decimal): 4124.  Message ID: [0x2507].

It looks like profiler is loaded correctly but it's always disabled. Could you advise?
Mihail
Telerik team
 answered on 12 May 2016
1 answer
131 views

Hello,

I am using JustMock with visual studio 2015 (just mock Q3 2015: 2015.3.929.5).

I am getting method not found error when I mocked private method and asserting on private method call as following

public class Foo
{
    private void DoPrivate()
    {
        //Do something
    }

}

Following is test method

[TestMethod]
public void ShouldInvokeNonPublicMember()
{
    Foo foo = new Foo();

    bool called = false;

    // Arrange
    Mock.NonPublic.Arrange(foo, "DoPrivate").DoInstead(() => called = true);

    // Act
    foo.DoPublic();

    // Assert
    Assert.IsTrue(called);
}

Here assert is always failing since DoInstead get not get triggered and method DoPrivate does not get called.

I also tried with Mock.NonPublic.Arrange(foo, "DoPrivate").DoNothing().MustBeCalled(); After asserting this throws error as "DoPrivate()" method not found.

 

Please suggest.

Thanks,

Prasad

 

Svetlozar
Telerik team
 answered on 29 Apr 2016
4 answers
134 views
What is the minimum version of JustMock that is compatible with VS2015?
Sven
Top achievements
Rank 1
 answered on 29 Mar 2016
1 answer
560 views

I have MockupController class with Just Mock and using the template found here

http://blog.johnnyreilly.com/2013/02/unit-testing-mvc-controllers-mocking.html#comment-2562756456

Tthe MockController class file that also includes the ability to mock a custom identity class that inherits from IIdentity.

While this class is useful it's still not mocking all the necessary aspects including routing.

Currently an error is being thrown with these two lines of the application code

 

                        UrlHelper u = new UrlHelper(ControllerContext.RequestContext);
                        string url = u.Action("Results", new { id = v.VerificationID });

 

Any ideas?

 

Here is the MockupController class

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Telerik.JustMock;
using Telerik.JustMock.AutoMock;
using System.Web;
using QmostWeb.Controllers;
using System.Web.Mvc;
using System.Web.Routing;
using System.Security.Principal;
using QmostWeb;
using QmostWeb.Models;
using QmostBase;
using System.Collections.Specialized;

namespace QmostWebTest
{
    public static class ControllerMockup
    {
        #region Mock HttpContext factories
        public static HttpContextBase MockHttpContext()
        {
            var context = Mock.Create<HttpContextBase>();
            var request = Mock.Create<HttpRequestBase>();
            var response = Mock.Create<HttpResponseBase>();
            var session = Mock.Create<HttpSessionStateBase>();
            var server = Mock.Create<HttpServerUtilityBase>();

            Mock.Arrange(() => request.AppRelativeCurrentExecutionFilePath).Returns("/");
            Mock.Arrange(() => request.ApplicationPath).Returns("/");
            Mock.Arrange(() => request.IsAuthenticated).Returns(true);


            Mock.Arrange(() => response.ApplyAppPathModifier(Arg.IsAny<string>())).Returns<string>(s => s);
            Mock.ArrangeSet(() => response.StatusCode = (int) System.Net.HttpStatusCode.OK);


            Mock.Arrange(() => context.Request).Returns(request);
            Mock.Arrange(() => context.Response).Returns(response);
            Mock.Arrange(() => context.Session).Returns(session);
            Mock.Arrange(() => context.Server).Returns(server);

            return context;
        }

        public static HttpContextBase MockHttpContext(string url)
        {
            var context = MockHttpContext();
            context.Request.SetupRequestUrl(url);
            return context;
        }


        #endregion
        public static void SetMockControllerContext(this Controller controller,
            HttpContextBase httpContext = null,
            RouteData routeData = null,
            RouteCollection routes = null)
        {
            routeData = routeData ?? new RouteData();
            routes = routes ?? RouteTable.Routes;
            httpContext = httpContext ?? MockHttpContext();

            var requestContext = new RequestContext(httpContext, routeData);

            var user = new QmostIdentitySerializeModel()
            {
                UserId = 20,
                SecurityToken = new Guid("4223017F-E6F2-4829-A37F-51C42CF1A04C")
            };
            var qmostIdentity = new QmostIdentity("jonathan", user, new QmostWorkflowsSerializeModel());
            var principal = Mock.Create<IPrincipal>();
            Mock.Arrange(() => principal.Identity).Returns(qmostIdentity);

            var context = new ControllerContext(requestContext, controller);

            Mock.Arrange(() => context.HttpContext.User).Returns(principal);
            controller.ControllerContext = context;
        }

        public static void SetupRequestUrl(this HttpRequestBase request, string url)
        {
            if (url == null)
                throw new ArgumentNullException("url");

            if (!url.StartsWith("~/"))
                throw new ArgumentException("Sorry, we expect a virtual url starting with \"~/\".");

            Mock.Arrange(() => request.QueryString).Returns(GetQueryStringParameters(url));
            Mock.Arrange(() => request.AppRelativeCurrentExecutionFilePath).Returns(GetUrlFileName(url));
            Mock.Arrange(() => request.PathInfo).Returns(string.Empty);
        }

        #region Private

        static string GetUrlFileName(string url)
        {
            return (url.Contains("?"))
                ? url.Substring(0, url.IndexOf("?"))
                : url;
        }

        static NameValueCollection GetQueryStringParameters(string url)
        {
            if (url.Contains("?"))
            {
                var parameters = new NameValueCollection();

                var parts = url.Split("?".ToCharArray());
                var keys = parts[1].Split("&".ToCharArray());

                foreach (var key in keys)
                {
                    var part = key.Split("=".ToCharArray());
                    parameters.Add(part[0], part[1]);
                }

                return parameters;
            }

            return null;
        }

        #endregion
    }
}

Kaloyan
Telerik team
 answered on 21 Mar 2016
7 answers
429 views

I have a async method under test and this method calls a rest service asynchronously, I want to test that if the rest service call returns an error then this method under test throws it back, I am guessing because of the way the exception are wrapped in a Task it is not working for me.

If i debug I can see that service.restcall does throw the exception with "Test" but the test method never receives the error.

public async Task CreateDatastore()

{

await service.restcall()

}

 -------------- Test code -----------------

[TestMethod]
        [ExpectedException(typeof(Exception), "Test")] 

public void Should_Throw_Back_The_RestException()
        {
            //Arrange
            var service = Mock.Create<IRestApiServices>();
            var viewModel = new CreateViewModel(service);
            var privViewModel = new PrivateAccessor(viewModel);

            var ex = new Exception("Test");

            Mock.Arrange(() => service.restcall().IgnoreArguments().throws(ex).MustBeCalled();

            //Act            
            privViewModel.CallMethod("Methodundertest", null);

            //Assert
            Mock.Assert(service);
        }

Kaloyan
Telerik team
 answered on 09 Feb 2016
4 answers
1.1K+ views

I have 2 classes Parent and a Child class, child class inherits from parent.

Class under test has an async method that returns Task<parent>.

I am arranging the Test method in my unit test, Mock.Arrange(() => viewmodel.Test()).Returns(Task.FromResult(new child()));

I am getting this error, Why is it having a problem in casting a child to its parenttype

ErrorCS1503Argument 1: cannot convert from 'System.Threading.Tasks.Task<ViewModels.child>' to 'System.Threading.Tasks.Task<ViewModels.parent>'ViewModels.Tests

public class viewmodel{

public async Task<parent> Test()
        {
            await Task.Delay(100);
            return null;              
        }
    }

    public class parent
    {

    }

    public class child : parent
    {

    }

Vikas
Top achievements
Rank 1
 answered on 21 Jan 2016
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?