Telerik Forums
JustMock Forum
1 answer
100 views
We have some mission critical code that catches all exceptions and recovers from them in various ways.  I would like to be able to use Mock.Create<MyClass>(Behavior.Strict) so that I can know that none of the methods on MyClass are being called besides the ones I explicitly Mock.Arrange.  However, this results in the methods throwing exceptions which are then caught by my application and recovered from so I never see them.

I would like something like this, but where I didn't have to manually arrange every method on the class and instead have some Behavior that I could give to Mock.Create that would result in all of the arranges being auto-generated.  I could then manually arrange anything I didn't want to have OccursNever on, just like you can override the exceptions thrown by Behavior.Strict.
class MyClass
{
    public void Method1() { }
    public void Method2() { }
    public void Method3() { }
}
 
class ClassUnderTest
{
    public void DoSomething(MyClass myClass)
    {
        myClass.Method3();
    }
}
 
[Test]
void MyClass_methods_are_never_called()
{
    // ARRANGE
    var myClass = Mock.Create<MyClass>();
    Mock.Arrange(() => myClass.Method1()).OccursNever();
    Mock.Arrange(() => myClass.Method2()).OccursNever();
    Mock.Arrange(() => myClass.Method3()).OccursNever();
 
    // ACT
    var classUnderTest = new ClassUnderTest();
    classUnderTest.DoSomething(myClass);
 
    // ASSERT
    Mock.Assert(myClass); // this will fail
}
Kaloyan
Telerik team
 answered on 21 Aug 2013
0 answers
47 views
Nevermind.  It was a problem with having a static that was being re-used, not a problem with JustMock.  (please delete this post if possible)
Micah
Top achievements
Rank 1
 asked on 21 Aug 2013
8 answers
200 views
Hello,

similiary to Alexander in http://www.telerik.com/community/forums/justmock/general-discussions/justmock-dotcover-teamcity-problem.aspx thread i'm trying to make satup for unit test running nunit+justMock+dotcover, and i'm facing problems similiar to Alexander's, thus i created simple test as suggested in mentioned thread:

Assert.IsTrue(Mock.IsProfilerEnabled);


which results in following output:
[16:41:15][Step 6/7] NuSoft.Printer.Rs232.Tests.dll
 
[16:41:15][NuSoft.Printer.Rs232.Tests.dll] NuSoft.Printer.Rs232.Tests.PrinterTest.AssertStringPrinted
 
[16:41:15][NuSoft.Printer.Rs232.Tests.PrinterTest.AssertStringPrinted] Test(s) failed.   Expected: True
 
  But was:  False
 
[16:41:15][NuSoft.Printer.Rs232.Tests.PrinterTest.AssertStringPrinted] Test(s) failed.   Expected: True
 
  But was:  False
 
   at NUnit.Framework.Assert.That(Object actual, IResolveConstraint expression, String message, Object[] args)
 
   at NUnit.Framework.Assert.IsTrue(Boolean condition)
 
   at NuSoft.Printer.Rs232.Tests.PrinterTest.CheckProfiler() in c:\TeamCity\buildAgent\work\64cb9cb36a4269ed\NuSoft.Printer.Rs232.Tests\PrinterTest.cs:line 18
 
   at NuSoft.Printer.Rs232.Tests.PrinterTest.AssertStringPrinted() in c:\TeamCity\buildAgent\work\64cb9cb36a4269ed\NuSoft.Printer.Rs232.Tests\PrinterTest.cs:line 24

I followed manual http://www.telerik.com/help/justmock/integration-teamcity.html section Integrating JustMock within TeamCity using MS Test or NUnit build steps with dotCover and Profiler is linked to dotCover (the only one installed is the one bundled with TeamCity) and JUSTMOCK_INSTANCE=1 variable is present in build parameters.

tests run in VS2012, also when configured accordingly to Integrating JustMock within TeamCity using MS Test or NUnit build steps.

Telerik.JustMock - 2013.2.611.0
TeamCity - 7.1.5 (build 24400)

is there any thing that can be done in order to configure justmock to run on teamcity with nUint and dotCover?

Pawel Paluch
Top achievements
Rank 1
 answered on 19 Aug 2013
2 answers
403 views
Hello,

I have the following code:

var mockDocumentRepository = Mock.Create<IDocumentRepository>();
  
Mock.Arrange(() => mockDocumentRepository.FetchDocumentsByListCriteria(Arg.IsAny<ListCriteria>(),  Arg.AnyInt, Arg.AnyInt, out virtualCount)).Returns(GetFakeDocumentListWithChildren_OneChildLevel());

As you can see I have an out parameter, I have not figure out how to mock virtualCount, what I did is created a variable in my test method which I do not like.   Can you provide an example of how to do that?

Also, if you can provide an example how to mock a ref parameter as well please?

Also, how can Mock a delegate that I pass into method under test, right now I create a method in my test class that matches the delegate signature and pass that across, is there a better option?

I am using 2013.2.701.0 version.

Kaloyan
Telerik team
 answered on 19 Aug 2013
4 answers
125 views
I'm using/implementing JustMock for the first time.  I've watched the webnair, but I can't seem to get the Mocked object working properly.  We have a full paid version of JustMock.

I have an internal database access layer object, "OperationsData", and an "ComponentException" object with a private constructor.  I'm trying to write the unit test method for the Persist method of the ComponentException object.  The unit tests are all in a separate project so the internal class and the private constructor use a "_Accessor".

When I run the unit test it complains that OperationsData connection string isn't instantiated.  Why isn't it just using the mocked object and return the expectedExceptionId that I want?  Thanks.

This is the ComponentException.Persist() ...
public void Persist()
{
   try
   {
      OperationsData data = new OperationsData();
      this.ExceptionId = data.PersistException(this.Id, this.ExceptionCode, this.ComponentName, this.SeverityIndicator.ToString(), this.ProcessName, this.BusinessExceptionDetail, this.StackTrace);
   }
   catch (Exception ex)
   {...}
}
This is the UnitTest...
[TestMethod()]
public void SuccessfulPersistTest()
{
    /// Arrange
    long expectedExceptionID = 12345;
    long ID = 678901;
    string exceptionCode = string.Empty;
    string componentName = string.Empty;
    string severityIndicator = string.Empty;
    string processName = string.Empty;
    string businessExceptionDetail = string.Empty;
    string stackTrace = string.Empty;
 
    OperationsData_Accessor operationsData = new OperationsData_Accessor();
    operationsData.Arrange(od => od.PersistException(ID, exceptionCode, componentName, severityIndicator, processName, businessExceptionDetail, stackTrace))
        .IgnoreInstance()
        .Returns(expectedExceptionID);
 
    ///Action
    ComponentException_Accessor target = new ComponentException_Accessor();
    target.Persist();
 
    ///Assert
    Assert.AreEqual(expectedExceptionID, target.ExceptionId);
    operationsData.Assert();
}

PS.  I also tried...
OperationsData_Accessor operationsData = Mock.Create<OperationsData_Accessor>(Constructor.Mocked);
Kaloyan
Telerik team
 answered on 14 Aug 2013
12 answers
274 views
I'm calling a mock on multiple threads. Sometimes this works just fine. But sometimes the mock call fails with a System.ArgumentException "An item with the same key has already been added.". Here's the end of the stack trace: -

at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue value)
at    .  .   (MethodInfo   )
at    .   .   (MockInvocation    )
at    .   .Intercept(MockInvocation    )
at    .   .Intercept(MockInvocation    )
at    .   .Intercept(IInvocation    )

Now I'm not using any dictionaries in my code - is it possible that this is happening somewhere inside the mock?
Isaac Abraham
Top achievements
Rank 1
 answered on 14 Aug 2013
1 answer
161 views
I'm trying to create a mock version of UserProfileManager in order to effectively unit test a Sharepoint 2010 Web Part
Every time I run this code, I get the the exception being thrown below. I've verified that the feature works when I debug the code that calls UserProfileManager on the Sharepoint machine - two different Sharepoint machines, in fact.
Here is the code in question:
var _mockServiceContext = Mock.Create<SPServiceContext>();
var _mockUserProfileManager = Mock.Create<UserProfileManager>(new object[] {_mockServiceContext});


Unable to create instance of class SharePoint.MyWebPart.Test.MyTest. Error: Microsoft.SharePoint.SPException: The trial period for this product has expired..
    at Microsoft.Office.Server.UserProfiles.ProfileManagerBase.ValidateLicensing()
   at Microsoft.Office.Server.UserProfiles.ProfileManagerBase..ctor(SPServiceContext serviceContext)
   at Microsoft.Office.Server.UserProfiles.ProfileManagerBase..ctor(SPServiceContext serviceContext, Boolean ignorePrivacy)
   at Microsoft.Office.Server.UserProfiles.UserProfileManager..ctor(SPServiceContext serviceContext, Boolean IgnoreUserPrivacy, Boolean backwardCompatible)
   at Microsoft.Office.Server.UserProfiles.UserProfileManager..ctor(SPServiceContext serviceContext)
   at Castle.Proxies.UserProfileManagerProxy..ctor(IEventsMixin, IMockReplicator, IMockMixin, IInterceptor[], SPServiceContext)
   at DynamicMethod_6f2d60ffa4f94cb4ba57556150461ef9(Object[])
   at “•.—.Ÿ.€()
   at “•.’•.Œ•[–](Func`1 ‹•)
   at “•.—.ˆ—(Type ‹, Object[] €)
   at –.”.(Type , List`1 ‘, Type Ž, Object[] “)
   at –.”.(Type Ž, Type[] , ProxyGenerationOptions Š“, Object[] “, IInterceptor[] )
   at Telerik.JustMock.Core.MocksRepository.Create(Type ‹, Object[] €, IEnumerable`1 ˆ–, IEnumerable`1 ‰–, IEnumerable`1 Š–, Type[] ‚–, Boolean ƒ–, Boolean €, IEnumerable`1 ˆ)
   at .‹–.Create(MocksRepository €–, Type ‹, Object[] –, Nullable`1 , Type[] ‚–, Nullable`1 ƒ–, IEnumerable`1 ˆ, List`1 ‰–, List`1 Š–, List`1 ˆ–)
   at Telerik.JustMock.Mock.›.’Ÿ()
   at “•.’•.Š•[–](Func`1 ‹•)
   at Telerik.JustMock.Mock.Create(Object[] args)

Has anyone else seen this issuue?
Stefan
Telerik team
 answered on 14 Aug 2013
9 answers
188 views
I'm trying to write some unit tests for a Sharepoint 2010 Webpart that uses UserProfile manager.
In order to mock UserProfileManager, I also need to mock SPServiceContext.

When I try to assign my mock variable, like this:

_mockServiceContext = Mock.Create<SPServiceContext>();

The following exception is thrown:

Type 'Telerik.JustMock.MockException' in assembly 'Telerik.JustMock, Version=2013.1.507.0, Culture=neutral, PublicKeyToken=721b6c5bc0326b3a' is not marked as serializable.

Any idea what I'm doing wrong?
Nathanael
Top achievements
Rank 1
 answered on 13 Aug 2013
8 answers
191 views

I am using the Professional version of JustMock and cannot seem to raise events.  Version 2013.1.220.3

When I call Mock.Raise() I receive 
  • NullReferenceException was unhandled by user code.  Object reference not set to an instance of an object 



using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MockEvent;
using Telerik.JustMock;
 
namespace TestEvent
    [TestClass]
    public class JustMockTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            var mc = new MyClass();
            var args = new EventArgs();
 
            Mock.Raise(() => mc.TestEvent += null, args);
        }
    }
}



using System;
using System.Linq;
 
namespace MockEvent
{
    public class MyClass
    {
        public event TestMethod TestEvent;
        public delegate void TestMethod(object sender, EventArgs args);       
 
        public MyClass()
        {
            TestEvent += MyClass_TestEvent;
        }
 
        void MyClass_TestEvent(object sender, EventArgs args)
        {
            Console.WriteLine("Running Event");
        }
    }
}
Zeeshan
Top achievements
Rank 1
 answered on 13 Aug 2013
0 answers
144 views
Recently, there were several client reports about interference between some of the default JustMock shortcuts inside Visual Studio. The conflicting shortcuts were the ones, used for enabling and disabling the JustMock profiler (JustMock.EnableProfiler and JustMock.DisableProfiler). The default keys for these commands were:
  • Ctrl + Alt + [
  • Ctrl + Alt + ]
It appeared these combinations are commonly used for typing the following symbols: { or [ and } or ]. The issue is possible to appear only on a certain keyboard layouts (e.g. Italian, Canadian-French, etc.)

This is already fixed in the upcoming JustMock official release. We have changed the shortcuts to not interfere with the user environment in such ways. The new shortcuts for enabling and disabling the profiler will be:
  • Ctrl + Shift + [     -     for JustMock.EnableProfiler
  • Ctrl + Shift + ]     -     for JustMock.DisableProfiler

As a workaround, until the next version is out, you can change the shortcuts from inside Visual Studio by performing the following:
  1. From Tools menu, go to Options;
  2. Navigate to Environment > Keyboard;
  3. Inside the "Show commands containing" text box write: JustMock
  4. Then find JustMock.EnableProfiler and JustMock.DisableProfiler and remove or change their shortcuts as you want (you can also change the rest of the JustMock shortcuts if required). Note that, you will need to remove the old shortcuts in order to disable them.
Telerik Admin
Top achievements
Rank 1
Iron
 asked on 08 Aug 2013
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?