Telerik Forums
JustMock Forum
2 answers
956 views
I have a unit test trying to mock the generation of an HttpResponseMessage. It fails with what appears to be an internal JustMock error, but I'm not sure what to try. If anybody can recommend a solution or has seen anything similar, I'd appreciate the help. Thanks!

Here's the test:

var actionContext = Mock.Create<HttpActionContext>();
 
var actionDescriptor = Mock.Create<HttpActionDescriptor>();
actionContext.ActionDescriptor = actionDescriptor;
actionDescriptor.Arrange(a => a.GetCustomAttributes<AllowAnonymousAttribute>())
    .Returns(new Collection<AllowAnonymousAttribute>());
 
var controllerContext = Mock.Create<HttpControllerContext>();
actionContext.ControllerContext = controllerContext;
 
var controllerDescriptor = Mock.Create<HttpControllerDescriptor>();
controllerContext.ControllerDescriptor = controllerDescriptor;
controllerDescriptor.Arrange(a => a.GetCustomAttributes<AllowAnonymousAttribute>())
    .Returns(new Collection<AllowAnonymousAttribute>());
 
var requestContext = Mock.Create<HttpRequestContext>();
controllerContext.RequestContext = requestContext;
 
var request = Mock.Create<HttpRequestMessage>();
request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());
 
actionContext.Arrange(x => x.Request).Returns(request);
var principal = Mock.Create<IPrincipal>();
requestContext.Principal = principal;
 
var identity = Mock.Create<IIdentity>();
principal.Arrange(x => x.Identity).Returns(identity);
identity.Arrange(x => x.IsAuthenticated).Returns(true);
 
var attribute = new PermissionsAttribute("TEST_ROLE");
attribute.OnAuthorization(actionContext);
 
Assert.IsNotNull(actionContext.Response);
Assert.AreEqual(HttpStatusCode.Forbidden, actionContext.Response.StatusCode);




There is an error in "OnAuthorization", which just calls HttpRequestMessage.CreateErrorResponse. Here is the error:




Test method Tests.Filters.PermissionsAttributeTests.Test_403 threw exception: <br>System.NullReferenceException: Object reference not set to an instance of an object.<br>    at System.Net.Http.Headers.MediaTypeHeaderValue.GetHashCode()<br>   at System.ValueType.GetHashCode()<br>   at System.Collections.Generic.ObjectEqualityComparer`1.GetHashCode(T obj)<br>   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)<br>   at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)<br>   at Telerik.JustMock.Core.Behaviors.RecursiveMockingBehavior.Process(Invocation invocation)<br>   at Telerik.JustMock.Core.MocksRepository.DispatchInvocation(Invocation invocation)<br>   at Telerik.JustMock.Core.ProfilerInterceptor.Intercept(RuntimeTypeHandle typeHandle, RuntimeMethodHandle methodHandle, Object[] data)<br>   at System.Net.Http.Headers.MediaTypeHeaderValue.get_MediaType()<br>   at System.Net.Http.Formatting.ParsedMediaTypeHeaderValue..ctor(MediaTypeHeaderValue mediaType)<br>   at System.Net.Http.Formatting.MediaTypeHeaderValueExtensions.IsSubsetOf(MediaTypeHeaderValue mediaType1, MediaTypeHeaderValue mediaType2, ref MediaTypeHeaderValueRange mediaType2Range)<br>   at System.Net.Http.Formatting.MediaTypeHeaderValueExtensions.IsSubsetOf(MediaTypeHeaderValue mediaType1, MediaTypeHeaderValue mediaType2)<br>   at System.Net.Http.Formatting.DefaultContentNegotiator.MatchRequestMediaType(HttpRequestMessage request, MediaTypeFormatter formatter)<br>   at System.Net.Http.Formatting.DefaultContentNegotiator.ComputeFormatterMatches(Type type, HttpRequestMessage request, IEnumerable`1 formatters)<br>   at System.Net.Http.Formatting.DefaultContentNegotiator.Negotiate(Type type, HttpRequestMessage request, IEnumerable`1 formatters)<br>   at System.Web.Http.Results.NegotiatedContentResult`1.Execute(HttpStatusCode statusCode, T content, IContentNegotiator contentNegotiator, HttpRequestMessage request, IEnumerable`1 formatters)<br>   at System.Net.Http.HttpRequestMessageExtensions.CreateResponse(HttpRequestMessage request, HttpStatusCode statusCode, T value, HttpConfiguration configuration)<br>   at System.Net.Http.HttpRequestMessageExtensions.CreateErrorResponse(HttpRequestMessage request, HttpStatusCode statusCode, Func`2 errorCreator)<br>   at System.Net.Http.HttpRequestMessageExtensions.CreateErrorResponse(HttpRequestMessage request, HttpStatusCode statusCode, HttpError error)<br>   at System.Net.Http.HttpRequestMessageExtensions.CreateErrorResponse(HttpRequestMessage request, HttpStatusCode statusCode, String message)<br>   at PermissionsAttribute.HandleUnauthorizedRequest(HttpActionContext actionContext) in PermissionsAttribute.cs: line 48<br>   at System.Web.Http.AuthorizeAttribute.OnAuthorization(HttpActionContext actionContext)<br>   at Tests.Filters.PermissionsAttributeTests.Test_403() in PermissionsAttributeTests.cs: line 91

Kaloyan
Telerik team
 answered on 09 Apr 2014
8 answers
132 views
Hello,

I've been trying to create a Thread mock just to check that some methods are called when needed (I don't need to execute anything, just assert that things are called). I've tried the answer from this post but it does not work:

var mock = Mock.Create<Thread>(Constructor.Mocked);
Assert.IsNotNull(mock);

I get the following exception:

Telerik.JustMock.MockException: Cannot create mock for sensitive types.

I've tried using the new call:

AllowedMockableTypes.Add<Thread>();

To no avail. How can I mock a Thread?

Thanks.
Vladi
Telerik team
 answered on 31 Mar 2014
9 answers
793 views
I'm trying to mock a simple example of the SharePoint 2013 Client Side Object Model.  Here's the method from the SUT:
public IEnumerable<string>GetListTitles(){
ClientContext ctx = new ClientContext(SiteUrl);
ctx.Credentials = CredentialCache.DefaultCredentials;
    ListCollection lists = ctx.Web.Lists;
ctx.Load(lists);
         ctx.ExecuteQuery();
    foreach(List list in lists)
      {
         yield return list.Title;
      }
}

I need to be able to specify a collection of Titles.  I've tried everything I can think of but nothing has worked.  The latest code I've tried is:
var mockCtx = Mock.Create<ClientContext>(Constructor.Mocked);
            var mockWeb = Mock.Create<Web>();
            var mockLists = Mock.Create<ListCollection>();
            var mockList = Mock.Create<List>();
 
            
 
            Mock.Arrange( () => mockCtx.Web).Returns(mockWeb);
            Mock.Arrange( () => mockWeb.Lists).Returns(mockLists);
            Mock.Arrange( () => mockLists[Arg.AnyInt]).Returns(mockList);
            Mock.Arrange( () => mockList.Title)).Returnsa("fakeTitle");
            Mock.Arrange( () => mockCtx.Load<ListCollection>(mockLists)).DoNothing();
            Mock.Arrange( () => mockCtx.ExecuteQuery()).DoNothing();
             
             
    
    var actual = SUT.GetListTitlesByCSOM();
 
    Assert.AreEqual(expected, actual);

Any ideas?


Thanks,

Dave



Martin
Telerik team
 answered on 14 Mar 2014
3 answers
603 views
Hello,

we need to mock Type.GetMethod() but seems that is not directly possible as when we are doing:

Mock.Arrange(() => fakeType.GetMethod("Validate")).Returns(fakeDelegate);

we are getting the following exception:

Telerik.JustMock.MockException: Cannot mock non-inheritable member 'System.Reflection.MethodInfo GetMethod(System.String)' on type 'System.Type' due to CLR limitations.

Anyway I a support ticket one of your team members told me something that can be useful (the question was related with another thing). He said:

" ... for these classes [talking about MethodIndo] we support only non-elevated mocking, through Mock.Create<T>() ..."

Not sure if this can help in our current problem or not. Is there any way to mock what we need?

Thanks in advance.



Todor
Telerik team
 answered on 14 Mar 2014
3 answers
116 views
Hello, 

I'm trying to test the following code:

public ICollection<RawCatalog> ReadCatalog(string familyName)
{
    // Root folder for the family
    string familyFolder = this.GetFamilyFolder(familyName);
    DirectoryInfo familyFolderInfo = new DirectoryInfo(familyFolder);
 
    foreach (DirectoryInfo subFamilyFolderInfo in familyFolderInfo.EnumerateDirectories())
    {
        // Do stuff
    }
}

I expected that this would work:

// Arrange
DirectoryInfo fakeDirectoryInfo = Mock.Create<DirectoryInfo>(Constructor.Mocked);
Mock.Arrange(() => new DirectoryInfo(@"testRoot\DrivesData\TestFamily")).Returns(fakeDirectoryInfo);
Mock.Arrange(() => directoryInfo.EnumerateDirectories()).Returns(new DirectoryInfo[] { });

But is not working as seems that fakeDirectoryInfo is not being returned in the constructor. How should I do the test? (I should not change the source code as it's working code if possible).

I've read something about future mocking and using DoNothing() but not sure if this apply to my own situation.

Thanks in advance.
Kaloyan
Telerik team
 answered on 19 Feb 2014
2 answers
1.1K+ views
I'm not sure what has changed on my computer, but at this point I don't have any means of enabling the JustMock profiler any longer from within Visual Studio.  I've installed some VS updates (currently up to date as far as The Extensions and Updates VS dialog says) since it was last working for me. And I've used the Telerik Control Panel to do a Repair for JustMock and also tried uninstalling and reinstalling JustMock completely, all to no avail.  See attachments below for my current install state.

I'm sure I'm just "doing it wrong", but don't know where I've gotten off the path.
Matt
Top achievements
Rank 1
 answered on 19 Feb 2014
1 answer
196 views
using System;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
 
namespace JustMockThreadIssue
{
    public class Helper
    {
        public static void DoSomething()
        {
            Console.WriteLine("DoSomething");
        }
    }
 
    public class Worker
    {
        public void Do()
        {
            Task.Factory.StartNew(DoMyJob);
            //DoMyJob();
        }
 
        private void DoMyJob()
        {
            Helper.DoSomething();
        }
    }
 
    [TestClass]
    public class JustMockThreadIssueTest
    {
        [TestMethod]
        public void Worker_Do()
        {
            var called = false;
            Mock.Arrange(() => Helper.DoSomething()).DoInstead(() => called = true);
 
            var worker = new Worker();
            worker.Do();
            Assert.IsTrue(called);
        }
    }
}

I mocked Hepler.DoSomething() method, but if it is called in another thread, Mock.Arrange doesn't work. How can i resolve it?
JustMock dll version is 2014.1.1317.4.
Kaloyan
Telerik team
 answered on 18 Feb 2014
1 answer
129 views
Hello,

I'm attempting to use the following code to arrange that all TcpClients return true for having a valid connection:
            TcpClient localClient = Mock.Create<TcpClient>(Constructor.Mocked, Behavior.Strict);
            Mock.Arrange(() => localClient.Connected).IgnoreInstance().Returns(true);
This code seems to work fine when I'm on the same thread, but if the access to Connected occurs on a different thread, this does not seem to function correctly.

My best guess is it has something to do with the use of either IgnoreInstance in conjunction with a property instead of a method (something I can't seem to find examples of so I wonder if it's supported or not), the fact that Threadpool mocking is not supported on the trial version, something I'm doing wrong, or a bug.

I've also attempted to mock the containing class such that it will always return a mocked instance of the TcpClient for any instance and that does not seem to function correctly on a thread either:
            Mock.NonPublic.Arrange<TcpClient>(typeof(CustomConnectionHandler), "TcpConnection").IgnoreInstance().Returns(localClient);
On the thread I always seem to get a different instance of the TcpClient - not localClient

Any thoughts,

Thanks
Stefan
Telerik team
 answered on 11 Feb 2014
19 answers
183 views
Hello,

I want to mock a large interface (~630 methods). The following line takes several minutes and several GBytes of memory:

Dim mJob As IJobInterface = Mock.Create(Of IJobInterface)()

Am I doing something wrong or is there another way to mock that object. I need this mock for every unit test so I need a faster way to do this.

Cheers
Stefan
Telerik team
 answered on 11 Feb 2014
10 answers
428 views
I'm trying to get JustMock working in an MSBuild unit test task. I keep getting the dreaded 'Profiler must be enabled' error.

It works in Visual Studio 2012 using the ReSharper test runner. xUnit.net is used as unit testing framework. I'm calling a .msbuild file, which looks like this:

<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <Import Project="C:\Program Files (x86)\Telerik\JustMock\Libraries\JustMock.targets" />
 
    <UsingTask AssemblyFile="$(MSBuildProjectDirectory)\..\packages\xunit.runners.1.9.1\tools\xunit.runner.msbuild.dll" TaskName="Xunit.Runner.MSBuild.xunit" />
 
    <Target Name="Build">
        <JustMockStart />
        <xunit Assembly="bin\Release\WebshopNG.Tests.dll" />
        <JustMockStop />
    </Target>
</Project>

Superfluously, before calling msbuild.exe I set the following environment variables:

COR_ENABLE_PROFILING=0x1
COR_PROFILER={b7abe522-a68f-44f2-925b-81e7488e9ec0}

I keep getting the following error in the event log:

.NET Runtime version 4.0.30319.17929 - Loading profiler failed.  COR_PROFILER is set to an invalid CLSID: '{b7abe522-a68f-44f2-925b-81e7488e9ec0}'.  HRESULT: 0x800401f3.  Process ID (decimal): 5576.  Message ID: [0x2502].

I've tried re-registering the Telerik.CodeWeaver.Profiler.dlls, but that did nothing. Googling the error yields nothing concrete, so I'm at a loss where to start.
Kaloyan
Telerik team
 answered on 30 Jan 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?