Telerik Forums
JustMock Forum
1 answer
119 views
I'm currently evaluating JustMock for a Windows Store App that I'm developing.

I've tried this code:

            var mock = Mock.Create<ConnectionProfile>(Constructor.NotMocked);

            Assert.AreEqual(NetworkConnectivityLevel.ConstrainedInternetAccess, mock.GetNetworkConnectivityLevel());

And it fails with the following exception:

Result Message: Test method JustMockWinRtTypes.UnitTest1.MockTest threw exception: 
Telerik.JustMock.MockException: Failed to create instance of type 'Windows.Networking.Connectivity.ConnectionProfile'
Result StackTrace:
at Telerik.JustMock.Core.MocksRepository.CreateExternalMockMixin(Type mockObjectType, Object mockObject, IEnumerable`1 mixins, IEnumerable`1 supplementaryBehaviors, IEnumerable`1 fallbackBehaviors)
   at Telerik.JustMock.Core.MocksRepository.Create(Type type, MockCreationSettings settings)
   at Telerik.JustMock.MockBuilder.Create(MocksRepository repository, Type type, Object[] constructorArgs, Nullable`1 behavior, Type[] additionalMockedInterfaces, Nullable`1 mockConstructorCall, IEnumerable`1 additionalProxyTypeAttributes, List`1 supplementaryBehaviors, List`1 fallbackBehaviors, List`1 mixins, Expression`1 interceptorFilter)
   at Telerik.JustMock.Mock.<>c__DisplayClass81`1.<Create>b__80()
   at Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal[T](Func`1 guardedAction)
   at Telerik.JustMock.Mock.Create[T](Constructor constructor)
   at JustMockWinRtTypes.UnitTest1.MockTest() in c:\Source Code\Spikes\JustMockWinRtTypes\JustMockWinRtTypes\UnitTest1.cs:line 22

Can you tell me what I need to do to make this work?

Thanks

Simon



Kaloyan
Telerik team
 answered on 29 May 2014
1 answer
62 views
Is it possible to let tests fail or throw an exception if a test calls a method that is not mocked?
exmaple:
method A calls method B and C
B is mocked and C is not mocked, but produces a valid result -> the test is ok, but it is not a valid unit-test.
I need a way to force the developer to write valid unit-tests. That means: as soon as a method calls an "unmocked" method the test should fail or generate an exception.
Is there an easy way to do this?

thx
Kaloyan
Telerik team
 answered on 23 May 2014
7 answers
185 views
Hello,

I need to test the handler of a Timer in one class. We are using Future Mocking to mock the Timer inside it.

Is there a way to use the Raise together with the .IgnoreInstance() method? I haven't found it.

Regards.
Nacho
Top achievements
Rank 1
 answered on 07 May 2014
1 answer
843 views
Given:

MyDbContext.GetProjects() which is generated via EntityFramework 6 from a stored procedure.

The return type is ObjectResult<MyProject>

I want to mock the results with a specific collection of Data.

Mock.Arrange(() => MyDbContextMock.GetProjects()).Returns(FakeEmptyList());


trying to use the following:

public ObjectResult<MyProject> FakeEmptyList()
{
  return new ObjectResult<MyProject>();
}


results in:

Error 18 The type 'System.Data.Entity.Core.Objects.ObjectResult<T>' has no constructors defined ............

I am new to JustMock and appreciate the help.  Thanks!
Kaloyan
Telerik team
 answered on 30 Apr 2014
3 answers
156 views
Hi there,
Been trying out the JustMock pro trial and I'm almost ready to buy. However, I have run into an issue which could be a deal breaker. Hoping someone with more knowledge of the product can steer me in the right direction.

I am attempting to test a private static method that resides in the codebehind file of a default.aspx page of a single-page web application (aka default.aspx.cs). The method under test is a very simple one that is a component of a much larger processes involving URL's, see below:

default.aspx.cs

namespace Company.Project
{
public partial class _default : System.Web.UI.Page
{
private static string CleanupURL(String theUrl)
{
theUrl = theUrl.ToLower();
theUrl = theUrl.Replace(@"\", "/");
while (!theUrl.IndexOf(".aspx").Equals(-1))
{
theUrl = theUrl.Substring(0, theUrl.IndexOf(".aspx"));
while (!theUrl.EndsWith("/") && theUrl.Length > 0)
{
theUrl = theUrl.Substring(0, theUrl.Length - 1);
}
}
return theUrl;
}
}
}

here is the test I have written (using nunit/justmock/dotcover test runner)

[Test]
        public void WillCleanupUrl()
        {
            var instance = PrivateAccessor.ForType(typeof(_default));
            string given = "server/subsite/default.aspx";
            var expected = "server/subsite";
            var returned = instance.CallMethod("CleanpUrl", given);
            Assert.AreEqual(expected, returned);
        }

My implementation is a copy/pasta of the example shown in the documentation regarding static methods with private accessors however the returned var is always null.

Other information:
This test is being executed inside of a virtual machine that has IIS/SQL/Sharepoint installed on it and it also communicates with a neighboring domain controller vm. Essentially, everything the project needs to run the entire application is running locally or nearby on the virtual lan, there is no true connection to the internet. I notice, using fiddler2, that requests are being sent  to various URL's (monitor.ashx?) by the jetbrains dotcover test runner. Obviously, these requests fail. Not sure if this has something to do with it? Possible bug?

Any help or guidance on the issue would be greatly appreciated!



Stefan
Telerik team
 answered on 23 Apr 2014
7 answers
339 views
After installing JustMock I get the following message:

        Token 0x02000001 resolves to the special module type representing this module. Parameter name: metadataToken

after I have started a Web Project (this message is shown in Internet Explorer).

I have reinstalled my machine, but it still happens.

Cheers Harry

PS More Information shown in Internet Explorer:

Server Error in '/' Application.

Token 0x02000001 resolves to the special module type representing this module.
Parameter name: metadataToken

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Token 0x02000001 resolves to the special module type representing this module.
Parameter name: metadataToken

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[ArgumentException: Token 0x02000001 resolves to the special module type representing this module. Parameter name: metadataToken] System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) +820 System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg) +878 System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecoratedTargetSecurityTransparent) +917 System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean isDecoratedTargetSecurityTransparent) +364 System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType) +345 System.Reflection.RuntimeAssembly.GetCustomAttributes(Type attributeType, Boolean inherit) +339 WebActivator.AssemblyExtensions.GetActivationAttributes(Assembly assembly) +388 WebActivator.ActivationManager.RunActivationMethods() +411 WebActivator.ActivationManager.RunPreStartMethods() +224 WebActivator.ActivationManager.Run() +243 [InvalidOperationException: The pre-application start initialization method Run on type WebActivator.ActivationManager threw an exception with the following error message: Token 0x02000001 resolves to the special module type representing this module. Parameter name: metadataToken.] System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +748 System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +290 System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath) +309 System.Web.Compilation.BuildManager.ExecutePreAppStart() +288 System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +895 [HttpException (0x80004005): The pre-application start initialization method Run on type WebActivator.ActivationManager threw an exception with the following error message: Token 0x02000001 resolves to the special module type representing this module. Parameter name: metadataToken.] System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +725 System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +283 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +420 


Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18045             
    
Kaloyan
Telerik team
 answered on 10 Apr 2014
1 answer
95 views
Even after installing JustMock Software, I'm not able to mock the objects.

A piece of code works on other machine but the same doesn't works on mine.

To Mock a object I wrote:

 Class obj = Mock.Create<Class>(Constructor.Mocked);

But when I try to execute this statement, ideally the debugger should not go inside the constructor but unfortunately it does.

Any suggestion would be of great help.
Kaloyan
Telerik team
 answered on 10 Apr 2014
1 answer
342 views
Public  class Baseclass{

protected void Setting (int y) {
y=10;

 }
}

public class ChildClass :Baseclass{

public void setvalue (int x){
Setting(x);
}
}

How we mock Setting method of Base Class ??
Mock.NonPublic.Arrange(new Baseclass() , "Setting", ArgExpr.IsAny<int>()).DoNothing();  //  Mock.NonPublic not working for Protected methods
Kaloyan
Telerik team
 answered on 10 Apr 2014
2 answers
280 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
527 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
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?