Telerik Forums
JustMock Forum
3 answers
138 views

Hi. I try to run simple test with JustMock on build machine:

Mock.SetupStatic(typeof(ConsoleApplication1.MyClass));

Mock.Arrange(() => ConsoleApplication1.MyClass.GetNumber()).Returns(777);

Assert.AreEqual(777, ConsoleApplication1.MyClass.GetNumber());

The test failed with message:

«Telerik.JustMock.MockException: Profiler must be enabled to mock/assert target MyClass.GetNumber() method.»

Error Stack Trace:

Telerik.JustMock.Handlers.InterceptorHandler.Create(Object target, MethodInfo methodInfo, Boolean privateMethod)

Telerik.JustMock.MockContext`1.SetupMock(MockExpression`1 expression)

Telerik.JustMock.Mock.<>c__DisplayClass1`1.<Arrange>b__0(MockContext`1 x)

Telerik.JustMock.MockContext.Setup[TDelgate,TReturn](Instruction instruction, Func`2 function)

Telerik.JustMock.Mock.Arrange[TResult](Expression`1 expression)

JustMockTestProject1.JustMockTest1.TestMethod1()

Messages from Event Viewer:

.NET Runtime version 4.0.30319.261 - The profiler was loaded successfully.  Profiler CLSID: '{B7ABE522-A68F-44F2-925B-81E7488E9EC0}'.  Process ID (decimal): 1044.  Message ID: [0x2507].

.NET Runtime version 4.0.30319.261 - Loading profiler failed during CoCreateInstance.  Profiler CLSID: '{D1087F67-BEE8-4f53-B27A-4E01F64F3DA8}'.  HRESULT: 0x80070002.  Process ID (decimal): 3028.  Message ID: [0x2504].

My build environment:

Windows Server 2008 R2 Standard Service Pack 1

Team Foundation Server - Standard Edition

JustMock Version Q3 2012 (2012.3.1016.3)

To solve this problem I was trying:

Followed this instruction from  next link: http://www.telerik.com/help/justmock/integration-code-activity-workflow.html.

But I couldn’t drop JustMockTestRunner activity to build template.

Then I added the text shown below to test project

<Import Project="C:\Program Files (x86)\Telerik\JustMock\Libraries\JustMock.targets" />

  <Target Name="BeforeTest">

    <JustMockStart />

  </Target>

  <Target Name="AfterTest">

    <JustMockStop />

  </Target>

Also I tried to modify workflow template in the way the next post adwises http://www.telerik.com/community/forums/justmock/general-discussions/setupstatic---mockexception-opps-there-were-some-error-intercepting-target-call.aspx#1259708

Also tried this http://www.telerik.com/community/forums/justmock/general-discussions/use-justmock-in-msbuild.aspx#2309253 and this http://www.telerik.com/community/forums/justmock/general-discussions/profiler-must-be-enabled-error.aspx#2254776

So I don’t know what else I can do to run tests on the build environment.

Could you advise some decision?

Best regards,

Eugene Ozerov

Stefan
Telerik team
 answered on 03 Dec 2013
1 answer
118 views
If I have a MockingContainer and use Get<T> on it, and then try to Mock.Raise on an event of T, I receive an error: Unable to specify which event was deduced in the parameter. If I replace that with the same type generated by Mock.Create<T>, it works.
Kaloyan
Telerik team
 answered on 22 Nov 2013
1 answer
74 views
I have a simple event which does not derive from event args. It seems that there is no way to raise these events on mocked objects: -

public interface IFoo
{
   event EventHandler<string> Message;
}
 
[Fact]
public void Sample()
{
    bool fired = false;
    var create = Mock.Create<IFoo>();
    create.Message += (o,e) => fired = true;
 
    Mock.Raise(() => create.Message += null, "Test"); //bang
 
    Assert.True(fired);
}

It appears that either (a) you must create a custom delegate rather than using EventHandler<T>, or (b) create a full class that inherits from EventArgs. If so - this is slightly cumbersome to use. It would be much better if there were no restriction that the type of T on EventHandler must derive from EventArgs.
Kaloyan
Telerik team
 answered on 22 Nov 2013
1 answer
181 views
Hi I am trying to Raise an event but I am getting this exception:

System.NotImplementedException: You can't call the original implementation of a method that does not have one (abstract or interface method).
StorageAndInventoryService is the class that raises the event.
BatchManager is the class subscribed to that event

My test:

[TestMethod]
        public void DestinationUnLockUpdatesBatchesStatus()
        {
            batchManager = Mock.Create<BatchManager>(Behavior.CallOriginal);
            batchManager.StorageInventoryService = Mock.Create<StorageInventoryService>();
 
            //Mock data
            List<DestinationStatus> destinationStatuses = new List<DestinationStatus>
                {
                    new DestinationStatus("D1", false, 1, 2, new List<string>())
                };
 
            Mock.Arrange(() => batchManager.StorageInventoryService.GetDestinationStatus(Arg.IsAny<List<string>>())).Returns(destinationStatuses).OccursOnce();
 
            batchManager.AddLoadCarrierRequestToBatch(materialFlowContext).Wait();
 
            DestinationInfo destinationInfo = batchManager.BatchRepository.GetDestination("D1");
            List<BatchInfo> batchInfos = batchManager.BatchRepository.GetBatchesByDestination(destinationInfo, 99).ToList();
 
            batchManager.SelectAndReserveLoadCarrierRequests(new string[] { "D1" }).Wait();
 
            Assert.IsTrue(destinationInfo.IsAvailable == false);
            Assert.IsTrue(batchInfos.FirstOrDefault().Status == BatchStatus.Suspended);
 
            MfsLocationLockChangedDataEventArgs mfsLocationLockChangedDataEventArgs = new MfsLocationLockChangedDataEventArgs(new MfsLocationLockChangedData("D1", true, string.Empty));
 
            Mock.Raise(() => batchManager.StorageInventoryService.LocationLockChanged += null, mfsLocationLockChangedDataEventArgs);
 
            Assert.IsTrue(batchInfos.FirstOrDefault().Status == BatchStatus.InProgress);
 
        }
I know that the issue is that we are Mocking as CallOriginal the BatchManager, but we are looking for an alternative, because as you can see is the class that we are trying to unit test. This is the callBack that I want to be executed in the BatchManager class:
private void StorageInventoryServiceOnLocationLockChanged(object sender, MfsLocationLockChangedDataEventArgs mfsLocationLockChangedDataEventArgs)
        {
 
            Log.Debug("** StorageInventoryServiceOnLocationLockChanged has changed**");
            if (!mfsLocationLockChangedDataEventArgs.MfsLocationLockChangedData.IsLocked)
            {
                DestinationInfo destinationInfo = BatchRepository.GetDestination(mfsLocationLockChangedDataEventArgs.MfsLocationLockChangedData.AddressName);
 
                if (destinationInfo != null)
                {
                    BatchRepository.UpdateDestinationAvailability(destinationInfo.Address, true);
                    List<BatchInfo> batchInfos = BatchRepository.GetBatchesByDestination(destinationInfo, 99).ToList();
                     
                    foreach (BatchInfo batch in batchInfos)
                    {
                        BatchRepository.UpdateBatchStatus(batch.BatchId, BatchStatus.InProgress);
                        foreach (string loadCarrier in batch.LoadCarriers)
                        {
                            BatchRepository.UpdateLoadCarrierRequestStatus(loadCarrier, LoadCarrierRequestStatus.New);    
                        }
                         
                    }
 
                    OnDestinationUnLocked(new DestinationStatusChangedEventArgs
                        {
                            Destinations = new List<string>
                                {
                                    mfsLocationLockChangedDataEventArgs.MfsLocationLockChangedData.AddressName
                                }
                        });
                }
 
            }
 
 
        }
Kaloyan
Telerik team
 answered on 20 Nov 2013
3 answers
179 views
Hello Telerik Team,

I am working with JustMock and I need to Mock a method that creates 5 instances of PerformanceCounters (MSFT object).  My method under test then performs calculations and sets each of these 5 counters with various values.  I need to check and Assert on these values in my Unit Test.

However, since these 5 objects get created inside my method under test (and I cannot change that code), I am wondering how to get access to these instances during my JustMock test. Specifically, I need to capture the RawValue property (both get and set) to make sure that the right values are sent into and returned from the property.  Without any access to the actual instances, I can;t see how this is done.

As a point of reference, Microsoft Fakes has a technique that specifies 'AllInstances' and this passes in the current object as one of the parameters  (see below, the 'counter' parameter)

                ShimPerformanceCounter.AllInstances.IncrementByInt64 =
                    (counter, l) => ShimsContext.ExecuteWithoutShims(() => counter.IncrementBy(l));

Any ideas ?

Kaloyan
Telerik team
 answered on 20 Nov 2013
1 answer
62 views
I have a recursive mock. I'm doing an arrangement on the child mock, but this has an unintended side effect in that the call count of the parent mock is incremented - this should not be happening.

public interface IMyInterface
{
   IOther GetOther();
}
public interface IOther
{
   int Foo(string test);
}
 
[Fact]
public void TestMethod()
{
   var myInterface = Mock.Create<IMyInterface>();
    
   Mock.Assert(() => myInterface.GetOther(), Occurs.Never());
   Mock.Arrange(() => myInterface.GetOther().Foo(null)).IgnoreArguments().Returns(1);
   Mock.Assert(() => myInterface.GetOther(), Occurs.Never()); // BANG
}
Kaloyan
Telerik team
 answered on 18 Nov 2013
6 answers
137 views
Hi,

we encountered following problem with the JustMock profiler.
We have an Outlook VSTO addin. If I start the VSTO addin with debug mode from VS with running JustMock profiler VSTO throws me following error:

************** Exception Text **************
System.MethodAccessException: UnsafeNativeMethods._AxlGetIssuerPublicKeyHash(IntPtr, Microsoft.Win32.SafeHandles.SafeAxlBufferHandle ByRef)
   bei System.Security.Cryptography.X509Certificates.X509Native.UnsafeNativeMethods._AxlGetIssuerPublicKeyHash(IntPtr pCertContext, SafeAxlBufferHandle& ppwszPublicKeyHash)
   bei System.Security.Cryptography.Xml.ManifestSignedXml.VerifyAuthenticodePublisher(X509Certificate2 publisherCertificate)
   bei System.Security.Cryptography.Xml.ManifestSignedXml.VerifyAuthenticodeSignature(XmlElement signatureNode, X509RevocationFlag revocationFlag, X509RevocationMode revocationMode)
   bei System.Security.Cryptography.Xml.ManifestSignedXml.VerifySignature(X509RevocationFlag revocationFlag, X509RevocationMode revocationMode)
   bei System.Security.Cryptography.ManifestSignatureInformation.VerifySignature(ActivationContext application, ManifestKinds manifests, X509RevocationFlag revocationFlag, X509RevocationMode revocationMode)
   bei Microsoft.VisualStudio.Tools.Applications.Deployment.ClickOnceAddInTrustEvaluator.VerifyCertificateSignature(ActivationContext context, OnlineOfflineState offlineState, String productName, DeploymentSignatureInformation& signatureInformation)
   bei Microsoft.VisualStudio.Tools.Applications.Deployment.ClickOnceAddInDeploymentManager.VerifySecurity(ActivationContext context, Uri manifest, AddInInstallationStatus installState)
   bei Microsoft.VisualStudio.Tools.Applications.Deployment.ClickOnceAddInDeploymentManager.InstallAddIn()


************** Loaded Assemblies **************
mscorlib
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.5472 (Win7SP1GDR.050727-5400)
    CodeBase: file:///C:/Windows/Microsoft.NET/Framework/v2.0.50727/mscorlib.dll
----------------------------------------
Microsoft.VisualStudio.Tools.Office.Runtime.v10.0
    Assembly Version: 10.0.0.0
    Win32 Version: 10.0.40305.0
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/Microsoft.VisualStudio.Tools.Office.Runtime.v10.0/10.0.0.0__b03f5f7f11d50a3a/Microsoft.VisualStudio.Tools.Office.Runtime.v10.0.dll
----------------------------------------
Microsoft.VisualStudio.Tools.Applications.Hosting.v10.0
    Assembly Version: 10.0.0.0
    Win32 Version: 10.0.40305.0
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/Microsoft.VisualStudio.Tools.Applications.Hosting.v10.0/10.0.0.0__b03f5f7f11d50a3a/Microsoft.VisualStudio.Tools.Applications.Hosting.v10.0.dll
----------------------------------------
Microsoft.VisualStudio.Tools.Applications.ServerDocument.v10.0
    Assembly Version: 10.0.0.0
    Win32 Version: 10.0.40305.0
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/Microsoft.VisualStudio.Tools.Applications.ServerDocument.v10.0/10.0.0.0__b03f5f7f11d50a3a/Microsoft.VisualStudio.Tools.Applications.ServerDocument.v10.0.dll
----------------------------------------
Microsoft.VisualStudio.Tools.Applications.Runtime.v9.0
    Assembly Version: 9.0.0.0
    Win32 Version: 9.0.30729.5806
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/Microsoft.VisualStudio.Tools.Applications.Runtime.v9.0/9.0.0.0__b03f5f7f11d50a3a/Microsoft.VisualStudio.Tools.Applications.Runtime.v9.0.dll
----------------------------------------
System
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.5467 (Win7SP1GDR.050727-5400)
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System/2.0.0.0__b77a5c561934e089/System.dll
----------------------------------------
Microsoft.VisualStudio.Tools.Applications.Runtime.v10.0
    Assembly Version: 10.0.0.0
    Win32 Version: 10.0.40305.0
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/Microsoft.VisualStudio.Tools.Applications.Runtime.v10.0/10.0.0.0__b03f5f7f11d50a3a/Microsoft.VisualStudio.Tools.Applications.Runtime.v10.0.dll
----------------------------------------
System.Windows.Forms
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.5468 (Win7SP1GDR.050727-5400)
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Windows.Forms/2.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
System.Drawing
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.5467 (Win7SP1GDR.050727-5400)
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Drawing/2.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
----------------------------------------
System.Core
    Assembly Version: 3.5.0.0
    Win32 Version: 3.5.30729.5420 built by: Win7SP1
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Core/3.5.0.0__b77a5c561934e089/System.Core.dll
----------------------------------------
Accessibility
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900)
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/Accessibility/2.0.0.0__b03f5f7f11d50a3a/Accessibility.dll
----------------------------------------
System.Deployment
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.5420 (Win7SP1.050727-5400)
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Deployment/2.0.0.0__b03f5f7f11d50a3a/System.Deployment.dll
----------------------------------------
System.Configuration
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.5476 (Win7SP1GDR.050727-5400)
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Configuration/2.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll
----------------------------------------
System.Xml
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.5476 (Win7SP1GDR.050727-5400)
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Xml/2.0.0.0__b77a5c561934e089/System.Xml.dll
----------------------------------------
System.Security
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.5475 (Win7SP1GDR.050727-5400)
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Security/2.0.0.0__b03f5f7f11d50a3a/System.Security.dll
----------------------------------------
System.Deployment.resources
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900)
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Deployment.resources/2.0.0.0_de_b03f5f7f11d50a3a/System.Deployment.resources.dll
----------------------------------------
mscorlib.resources
    Assembly Version: 2.0.0.0
    Win32 Version: 2.0.50727.5472 (Win7SP1GDR.050727-5400)
    CodeBase: file:///C:/Windows/Microsoft.NET/Framework/v2.0.50727/mscorlib.dll
----------------------------------------
System.Xml.Linq
    Assembly Version: 3.5.0.0
    Win32 Version: 3.5.30729.5420 built by: Win7SP1
    CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Xml.Linq/3.5.0.0__b77a5c561934e089/System.Xml.Linq.dll
----------------------------------------

VSTO Error:

NET Runtime version 2.0.50727.5472 - Failed to CoCreate profiler.


If I deactivate the profiler everything works fine.

Best regards
Kaloyan
Telerik team
 answered on 18 Nov 2013
3 answers
108 views
Hi,

I would like to Mock a Property of a class that has some protected methods , to do so I have created a Mock for exposing those methods in my tests:


public class BatchManager
{
 
public IStorageInventoryService StorageInventoryService { get; set; }
  protected virtual void AddOrUpdateLoadCarrierRequest(LoadCarrierRequest loadCarrierRequest)
        {
            List<DestinationStatus> destinationStatuses = StorageInventoryService.GetDestinationStatus(new List<string> { loadCarrierRequest.DestinationAddress });
  
            AddOrUpdateDestinationDictionary(destinationStatuses, loadCarrierRequest);
            AddOrUpdateBatchDictionary(loadCarrierRequest);
            AddOrUpdateLoadCarrierRequestDictionary(loadCarrierRequest);
  
  
            ExecuteNextTransport(destinationStatuses.Select(d => d.Address).ToList());
        }
 
 
}


And this is the Mock:
public class MockBatchManager : BatchManager
{
    public new  void AddOrUpdateLoadCarrierRequest(LoadCarrierRequest loadCarrierRequest)
        {
            base.AddOrUpdateLoadCarrierRequest(loadCarrierRequest);
        }
 
 
}
My test:
[TestMethod]
       public void AddOrUpdateLoadCarrierRequestAddsAnElementToEveryDictionary()
       {
           //Arrenge
           MockBatchManager mockBatchManager = new MockBatchManager
               {
                   StorageInventoryService = Mock.Create<StorageInventoryService>()
               };
 
           //Mock.Arrange(() => mockBatchManager.ExecuteNextTransport(Arg.IsAny<List<string>>())).DoNothing();
 
           Mock.Arrange(() => mockBatchManager.StorageInventoryService.GetDestinationStatus(Arg.IsAny<List<string>>()))
               .ReturnsCollection(new List<DestinationStatus>());
 
           //Act
           mockBatchManager.AddOrUpdateLoadCarrierRequest(loadCarrierRequest);
 
           //Assert
 
           Assert.IsTrue(mockBatchManager.DestinationDic.Count == 1);
           Assert.IsTrue(mockBatchManager.LoadCarrierRequestsDic.Count == 1);
           Assert.IsTrue(mockBatchManager.ConcurrentDestinationStatuses.Count == 1);
           Assert.IsTrue(mockBatchManager.BatchDic.Count == 1);
            
       }
if I take a look on the line:
List<DestinationStatus> destinationStatuses = StorageInventoryService.GetDestinationStatus(new List<string> { loadCarrierRequest.DestinationAddress });
I am getting a null, instead of a List initialized..
Kaloyan
Telerik team
 answered on 14 Nov 2013
3 answers
155 views
I have a protected static sub-class that I use for DataAccess.  Its locked down so that no other part of the application/code can access or is aware of the database.  I'm doing the unit tests for the host class and I need to Mock the protected static sub-class so that there are no database calls in the unit test.  How do I do that and check occurances? Thanks.
public partial class Manager
{
    protected static class DataAccess
    {
        public static void CallMyStoredProcedure()
        { }
    }
}
Kaloyan
Telerik team
 answered on 12 Nov 2013
6 answers
676 views
Hello,

I'm trying to mock a controller.ControllerContext and everything is working until the system tries to GetDisplayMode on the context.  Since it is null, it blows up.

Here are two functions, the first creates the controller and the second uses the controller and blows up.

Any help would be appreciated!

Lee
private static LogonController CreateLogonController()
        {
            var controller = new LogonController();
            var response = Mock.Create<HttpResponseBase>();
            var httpContext = Mock.Create<HttpContextBase>();
            var routeData = new RouteData();
            var request = Mock.Create<HttpRequestBase>();
            var cookies = new HttpCookieCollection();
            var context = new ControllerContext(httpContext, routeData, Mock.Create<ControllerBase>());
            var browser = Mock.Create<HttpBrowserCapabilitiesBase>();
 
            response.Output = new StringWriter();
 
            Mock.Arrange(() => browser.IsMobileDevice).Returns(false);
 
            Mock.Arrange(() => request.Cookies).Returns(cookies);
            Mock.Arrange(() => request.ValidateInput());
            Mock.Arrange(() => request.UserAgent).Returns("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11");
            Mock.Arrange(() => request.Browser).Returns(browser);
 
            Mock.Arrange(() => response.Cookies).Returns(cookies);
 
            Mock.Arrange(() => httpContext.Request).Returns(request);
            Mock.Arrange(() => httpContext.Response).Returns(response);
 
            routeData.Values.Add("controller", "LogonController");
            routeData.Values.Add("action", "Index");
            controller.ControllerContext = context;
 
            return controller;
        }


And here I am trying to use it to generate  the output of a view:

public static class ApiExtensionMethods
{
    public static string Render(this ViewResult result, Controller controller)
    {
        controller.ViewData.Model = result.Model;
        try
        {
            using (var sw = new StringWriter())
            {
                var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, result.ViewName);
                var context = new ViewContext(controller.ControllerContext, viewResult.View, result.ViewData, result.TempData, sw);
 
                viewResult.View.Render(context, sw);
 
                return sw.GetStringBuilder().ToString();
            }
        }
        catch (Exception e)
        {
            return e.ToString();
        }
    }
}
Kaloyan
Telerik team
 answered on 11 Nov 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?