Telerik Forums
JustMock Forum
2 answers
290 views
Hello,

I'm trying to do the following:

[TestClass]
public class JustMockTest
{
    [TestMethod]
    public void TestMethod()
    {
        Mock.SetupStatic(typeof(Real));
 
        IntPtr test;
         Mock.Arrange(() => Real.RealMethod(Arg.IsAny<int>(), out test)).IgnoreArguments().Returns((int a, IntPtr b) => Fake.FakeMethod(a, out b));
 
        IntPtr expected;
        int result = Real.RealMethod(1, out expected);
    }
}
 
public static class Real
{
    public static int RealMethod(int a, out IntPtr b)
    {
        b = new IntPtr(222);
 
        return a*2;
    }
}
 
public static class Fake
{
    public static int FakeMethod(int a, out IntPtr b)
    {
        b = new IntPtr(111);
 
        return a * 4;
    }
}

The problem is that b is always empty. How can I get the value? I've checking the ​Arg.OutRefResult class but the documentation does not say anything about it.

Thanks.
Nacho
Top achievements
Rank 1
 answered on 10 Apr 2014
1 answer
547 views
Trying to find an example for mocking a repository that uses the Microsoft.Practices.EnterpriseLibrary.Data.

C# code.  Pretty sure I can create the Unit Test, just cannot determine how to create a Mock for the Database object from Microsoft.Practices.EnterpriseLibrary.Data.

01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Text;
05.using System.Threading.Tasks;
06.using Microsoft.Practices.EnterpriseLibrary.Data;
07.using System.Data;
08.using System.Data.Common;
09.// Other using statements for Models
10. 
11.namespace Test.Repository
12.{
13.    public class MyDatabaseRepo : IMyDatabaseRepo
14.    {
15.        // Microsoft.Practices.EnterpriseLibrary.Data 'Database' object
16.        readonly Database _database;
17. 
18.        public MyDatabaseRepo(Database dataSource)
19.        {
20.            _database = dataSource;
21.        }
22. 
23.        public int InsertNewCustomer(ClientEntity client)
24.        {
25.            int ClientRecordId = 0;
26.            using (DbCommand dbCmd = _da.GetStoredProcCommand("usp_InsertNewCustomers"))
27.            {
28.                _database.AddInParameter(dbCmd, "@Address1", DbType.String, client.Address1);
29.                _database.AddInParameter(dbCmd, "@Address2", DbType.String, client.Address2);
30.                _database.AddInParameter(dbCmd, "@City", DbType.String, client.City);
31.                _database.AddInParameter(dbCmd, "@State", DbType.String, client.State);
32.                _database.AddInParameter(dbCmd, "PostalCode", DbType.String, client.PostalCode);
33.                _database.AddOutParameter(dbCmd, "@recordID", DbType.Int32, 0);
34. 
35.                using (IDataReader reader = _database.ExecuteReader(dbCmd))
36.                {
37.                    reader.Read();
38.                    ClientRecordId = Convert.ToInt32(dbCmd.Parameters["@recordID"].Value);
39.                }
40.            }
41. 
42.            return ClientRecordId;
43.        }
44.    }
45.}


Kaloyan
Telerik team
 answered on 09 Apr 2014
2 answers
980 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
140 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
833 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
612 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
123 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
200 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
134 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
Narrow your results
Selected tags
Tags
+? more
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?