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!
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
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 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
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
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
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
}
}
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);
}
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
{
}