Telerik Forums
JustMock Forum
8 answers
191 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
384 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
114 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
258 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
153 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
181 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
183 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
139 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
1 answer
127 views
Hi,

suppose my applicaiton contains several layers, the lowest one is a DAL (Data Access Layer) interfacing with a DB.
Now, I want to unit-test a method of a class in the upper layer which eventually calls a method in the DAL. Naturally, I want to mock only the DB, not the mid-layer classes.
How should I go about unit-testing a high-layer method as mentioned above?

Thanks,
Michael
Kaloyan
Telerik team
 answered on 08 Aug 2013
1 answer
131 views
Hi, I am running into a small issue with justmock. I am using nunit as my testing framework which allows base classes with multiple TestFixtureSetup methods when running a single test. I will create and inject my common mocks in the base class TestFixtureSetup method. Then my test class(inheriting the base class) will do the arranging and testing.

The issue is when the method being mocked is called, it acts like the arrange never excuted. I can verify that all the code ran in the order expected, but my mocked methods are just returning nulls.

Below I have a simple example of what I'm trying to explain.


[TestFixture]
public abstract class TestBase
{
    public IClientService ClientService;
 
    [TestFixtureSetUp]
    public void InitFixture()
    {
        ClientService = Mock.Create<IClientService>();
    }
}

[TestFixture]
public class ClientServiceTests : TestBase
{
    [Test]
    public void Test()
    {
        Mock.Arrange(() => ClientService.Retrieve(Arg.AnyLong))
            .Returns(() => new Client());
 
        var client = ClientService.Retrieve(0);
 
        Assert.IsNotNull(client);
    }
}

This does work when the test class has a TestFixtureSetUp of its own and calls the base class setup method, but the base class setup method cannot have the TestFixtureSetUp attribute. Does this mean that the arrange has to execute within the same fixture as the create?
Is there a better way to utilize a base class in this manner? Is this intended?

On a side note, this method was working a couple days ago when I had checked my code in. I will revert my tests to see if i stumbled upon some way to get this to work, I may have had the attributes in just the right places possibly?
Kaloyan
Telerik team
 answered on 02 Aug 2013
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?