Telerik Forums
JustMock Forum
7 answers
778 views

Hello,

We're encountering the following type of error on our build servers:

  X SendFile_GivenValidInformation_ShouldReturnSuccessResult [1ms]
  Error Message:
   Initialization method InsuranceApiLibrary.Syncronizers.<<redacted>>Tests.Setup threw exception. Telerik.JustMock.Core.ElevatedMockingException: Cannot mock '<<redacted>>SoapClient'. The profiler must be enabled to mock, arrange or execute the specified target.
Detected active third-party profilers:
* C:\Users\<<redacted-tfs-agent-service>>\.nuget\packages\microsoft.codecoverage\16.4.0\build\netstandard1.0\CodeCoverage\amd64\covrun64.dll (from process environment)
Disable the profilers or link them from the JustMock configuration utility. Restart the test runner and, if necessary, Visual Studio after linking..
  Stack Trace:
      at Telerik.JustMock.Core.ProfilerInterceptor.ThrowElevatedMockingException(MemberInfo member)
   at Telerik.JustMock.Core.MocksRepository.Create(Type type, MockCreationSettings settings)
   at Telerik.JustMock.Mock.<>c__DisplayClass47_0`1.<Create>b__0()
   at Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal[T](Func`1 guardedAction)
   at Telerik.JustMock.Mock.Create[T](Object[] args)
   at InsuranceApiLibrary.Syncronizers.<<redacted>>Tests.Setup() in E:\AzDOS\Agents\Alpha\_work\8\s\<<redacted>>\<<redacted>>Test\Syncronizers\<<redacted>>Tests.cs:line 27

When we exclude code coverage, we get very similar errors, but without the lines about detected third-party active profilers.  I have directly verified that the JM profiler settings are correct (see attached images).

Our build servers have Visual Studio Enterprise 2019 16.4.2, .NET Core SDK 3.1.100, and JustMock 2020.1.113.1 installed.  The C# projects in question target .NET Core 3.1.  The path to the JM DLL being referenced by those projects is "C:\Program Files (x86)\Progress\Telerik JustMock\Libraries\netcoreapp2.0\Telerik.JustMock.dll".  I can find no obvious alternative path or DLL for .NET Core 3.x, so I assume that DLL applies to multiple .NET Core major versions.

This problem is blocking new initiatives.  Thanks in advance for any assistance you can provide.

Regards,
Tom Slavens
Platform Configuration Architect, Software Services
Veterans United Home Loans

 

Ivo
Telerik team
 answered on 23 Jan 2020
5 answers
92 views

Hi ,

I want to write a unit test for a small class where it has following execution paths

 private bool? DetermineCheckState()
        {
            try
            {
               

                //1.where  ProjectsOperationData is a ObservableCollection<ProjectOperationData>{get;set;}

               //2 IsSelected is a public property in ProjectOperationData Class
                bool allChildrenChecked = ProjectsOperationData.Count(x => x.IsSelected == true) == ProjectsOperationData.Count;
                if (allChildrenChecked)
                {
                    return true;
                }

                //2. returns false if any project is not selected in Project Operations Form
                bool allChildrenUnChecked = ProjectsOperationData.Count(x => x.IsSelected == false) == ProjectsOperationData.Count;
                if (allChildrenUnChecked)
                {
                    return false;
                }
            }
            }

            return null;
        }

 

Can anyone suggest a way to write unit test?

Ivo
Telerik team
 answered on 06 Jan 2020
10 answers
3.9K+ views

I am trying to create a new .NET Core project and I am having issues using any JustMock functions/keywords. I have installed the latest available installer (JustMock.2019.1.207.1), we use JustMock in our other projects without any issues but these are all .NET 4.5. I would prefer to use the MSTest project as that is what the other projects use also and would like to keep things consistent. I have also tried creating a new NUnit and XUnit project but keep getting the same error. Solution builds without errors or warnings.

 

My Test Method only has one line in it for arranging, it's trying to mock the service. Here is the code:

var context = Mock.Create<IFileService>();

Here is the error I am getting:
Test method MSTestProject.LayoutControllerTest.FileController_TestCalls threw exception: 
System.TypeInitializationException: The type initializer for 'Telerik.JustMock.Core.ProfilerInterceptor' threw an exception. ---> System.MissingMethodException: Method not found: 'System.Reflection.Emit.AssemblyBuilder System.AppDomain.DefineDynamicAssembly(System.Reflection.AssemblyName, System.Reflection.Emit.AssemblyBuilderAccess)'.

StackTrace: 

at Telerik.JustMock.Core.Castle.DynamicProxy.ModuleScope.CreateModule(Boolean signStrongName)
   at Telerik.JustMock.Core.Castle.DynamicProxy.ModuleScope.ObtainDynamicModuleWithStrongName()
   at Telerik.JustMock.Core.MockingUtil.get_ModuleBuilder()
   at Telerik.JustMock.Core.MockingUtil.CreateDynamicMethodWithVisibilityChecks(Type returnType, Type[] parameterTypes, Action`1 ilGen)
   at Telerik.JustMock.Core.ProfilerInterceptor.CreateFieldAssignmentExpression(FieldInfo assignee, ParameterExpression valueParam)
   at Telerik.JustMock.Core.ProfilerInterceptor.InitializeFieldAccessors[TFieldType](String fieldName, Func`1& getter, Action`1& setter)
   at Telerik.JustMock.Core.ProfilerInterceptor..cctor()
--- End of inner exception stack trace ---
    at Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal(Action guardedAction)
   at MSTestProject.LayoutControllerTest.FileController_TestCalls() in C:\Repos\LTA-TelerikUIDotNetCore\MSTestProject\LayoutControllerTest.cs:line 33

 

Ivo
Telerik team
 answered on 19 Nov 2019
3 answers
140 views

I have a complex legacy application that I'm not allowed to refactor.   I am trying to write tests and don't want to repeat the same set up multiple times. I created a helper class which holds the mocks (TargetMocks) with methods to set up most of the logging arrange statements so I could focus the test on a specific aspect of the system under test.

I've created an example NUnit test with a sample set of classes and Interfaces.   All but one of the tests work and I don't understand why the failing test fails. It has the same exact Mock.Arrange statements that are executed in the same order.   The only difference is the failing test has the Mock.Arrange statements in the test method while the working test has the Mock.Arrange methods in the TestMocks helper class.

public class TargetMocks
{
    public ILogger Logger { get; } = Mock.Create<ILogger>();
    public IUtility Util { get; } = Mock.Create<IUtility>();
    public StringBuilder LoggerBuilder {get;} = new StringBuilder();
    public void SetupMocks()
    {
        Mock.Arrange(() => Logger.Info(Arg.AnyString))
            .DoInstead((string msg) =>
            {
                LoggerBuilder.AppendLine(msg);
            });
    }
    public Target CreateTarget()
    {
        var sut = new Target();
        Mock.Arrange(() => sut.Logger).Returns(Logger);
        Mock.Arrange(() => sut.Util).Returns(Util);
        return sut;
    }
    public Target CreateTargetAndSetupUtil()
    {
        var sut = new Target();
        Mock.Arrange(() => sut.Logger).Returns(Logger);
        Mock.Arrange(() => sut.Util).Returns(Util);
        //Mock.Arrange(() => mock.Util.ChangeState(Arg.AnyInt, Arg.AnyString)).MustBeCalled();
        Mock.Arrange(() => Util.SaveState(Arg.AnyInt, Arg.AnyString)).MustBeCalled();
 
        return sut;
    }
}

 

The following test fails

[Test()]
public void x3TestWidgetProcessUtilMethods_Test_TestUsesSeperateClassMocksAndCreatesSUT_But_Fails()
{
    var expectedLog =
        "target message 1\r\n" +
        "Message 1\r\n" +
        "Message 3\r\n" +
        "target message 3\r\n";
 
    var mock = new TargetMocks();
    mock.SetupMocks();
    var sut = mock.CreateTarget();
    Mock.Arrange(() => mock.Util.ChangeState(Arg.AnyInt, Arg.AnyString)).MustBeCalled();
    Mock.Arrange(() => mock.Util.SaveState(Arg.AnyInt, Arg.AnyString)).MustBeCalled();
 
    sut.Process();
 
    var log = mock.LoggerBuilder.ToString();
 
    Assert.AreEqual(expectedLog, log, log);
    Mock.Assert(mock.Util);
}

 

But this test works.

[Test()]
public void x3aTestWidgetProcessUtilMethods_Test_TestUsesSeperateClassMocksAndCreatesSUTAndSetsUpUtilMock_WorksAsExpected()
{
    var expectedLog =
        "target message 1\r\n" +
        "Message 1\r\n" +
        "Message 3\r\n" +
        "target message 3\r\n";
 
    var mock = new TargetMocks();
    mock.SetupMocks();
    var sut = mock.CreateTargetAndSetupUtil();
 
    sut.Process();
 
    var log = mock.LoggerBuilder.ToString();
 
    Assert.AreEqual(expectedLog, log, log);
    Mock.Assert(mock.Util);
}

 

  • Why does the first test fail?

 

 

Ivo
Telerik team
 answered on 24 Oct 2019
2 answers
176 views

I have yet to be able to run my unit tests within my pipeline.

I have installed Telerik JustMock Tests v.2 and I have configured the  profiler paths as described (those paths have been verified to contain the dlls)

 

pathTo64BitJustMockProfiler: '$(System.DefaultWorkingDirectory)/Solution Items/External assemblies/Telerik.JustMock/64/Telerik.CodeWeaver.Profiler.dll'

pathTo32BitJustMockProfiler: '$(System.DefaultWorkingDirectory)/Solution Items/External assemblies/Telerik.JustMock/32/Telerik.CodeWeaver.Profiler.dll'

 

Yet when I run my tests I get this error: Telerik.JustMock.Core.ElevatedMockingException: Cannot mock '...'. The profiler must be enabled to mock, arrange or execute the specified target.

 

On our old build server the same dlls are working fine but not in Azure. Is there a way to get this working?

Allan
Top achievements
Rank 1
 answered on 27 Sep 2019
1 answer
134 views

I am having a lot of trouble understanding the behaviour of static mocking. I have a static class with two static functions, each of which returns a string, I have a test class whose constructor calls both functions on the static class, and I have a set of tests that arrange only one of the static functions, and which call SetupStatic in various ways. The results are as follows:

1. SetupStatic is not called at all: the arranged function uses the mock arrangement and gets the arranged return value, the other function calls the original - as expected;

2. SetupStatic(MyType, Behavior.Strict) is called: the arranged function uses the mock arrangement and gets the arranged return value, the other function throws a "Called unarranged member on strict mock" exception - as expected;

3. SetupStatic(MyType) is called (ie. default Behavior): the arranged function uses the mock arrangement and gets the arranged return value, the other function does not call the original and gets an empty string as the return value - unexpected;

4. SetupStatic(MyType, Behaviour.Loose) is called: the arranged function uses the mock arrangement and gets the arranged return value, the other function does not call the original and gets null as the return value - doubly unexpected as the documented default value of Behavior is Loose;

5. SetupStatic(MyType, Behaviour.RecursiveLoose) is called: the arranged function uses the mock arrangement and gets the arranged return value, the other function does not call the original and gets an empty string as the return value - unexpected;

6. SetupStatic(MyType, Behavior.CallOriginal) is called: the arranged function uses the mock arrangement and gets the arranged return value, the other function calls the original - I'm not sure what I would expect for this;

I am using JustMock version R2 2019 SP1.

I would be grateful if someone could tell me if this is working correctly, and what the logic is behind this behaviour.

Thanks

Mihail
Telerik team
 answered on 26 Aug 2019
1 answer
160 views

I'm running into a situation where I need to enable the profiler however I do NOT have the ability to just open visual studio and click on a profiler choice, as I'm trying to get things to build on a headless build slave which runs as "nt authority\system."

This slave also had some churn on it in terms of having to reinstall visual studio 2015 enterprise (after installing JustMock)?

Currently I'm running Visual Studio 2015 update 3 

Just Mock is version 2015.2.715.1

I also have a diagnostic script to see if the various environment variables are properly set based off some other searches:
write-host "COR_ENABLE_PROFILING: $($env:COR_ENABLE_PROFILING)"
write-host "JUSTMOCK_INSTANCE: $($env:JUSTMOCK_INSTANCE)"
write-host "COR_PROFILER: $($env:COR_PROFILER)"
whoami
When I run this on my build slave it presents me with:
COR_ENABLE_PROFILING: 1
JUSTMOCK_INSTANCE: 1
COR_PROFILER: {B7ABE522-A68F-44F2-925B-81E7488E9EC0}
nt authority\system

Mihail
Telerik team
 answered on 20 Aug 2019
9 answers
560 views

I've recently upgraded to VS2019 and JustMock 2019.508.1 (we have a DevCraft license), and tests requiring elevated mode are no longer functioning. We receive the following error when only linking the VS 2019 Profiler with JustMock:

Telerik.JustMock.Core.ElevatedMockingException: Telerik.JustMock.Core.ElevatedMockingException: Cannot mock 'EL.BusinessLayer.LegacyTaskCloseRequestEntity PostRentScheduleEntitiesToLegacy(EL.BusinessLayer.LegacyTaskCloseRequestEntity, System.String, System.String, System.String, System.String, System.Collections.Generic.ICollection`1[System.String])'. The profiler must be enabled to mock, arrange or execute the specified target.
Detected active third-party profilers:
* {9317ae81-bcd8-47b7-aaa1-a28062e41c71} (from process environment)
Disable the profilers or link them from the JustMock configuration utility. Restart the test runner and, if necessary, Visual Studio after linking..

That guid refers to the VS Code Coverage profiler, which does appear in the Telerik JustMock Configuration profiler list. However, when I select that profiler then the tests will no longer even start - the progress bar will display its green runner going from left to right, but none of the tests will ever start spinning and after a minute or two the progress bar just stops without displaying any errors or messages.

We had also started .NET Core development in VS2017, and had found that we needed to add dotnet.exe to the Codeweaver ImageBlacklist.cfg file. The behavior we are seeing with tests not ever starting to run reminds me of that behavior with dotnet.exe, and I'm wondering if there is a new VS2019 executable for testing that needs to be added to that blacklist file?

Mihail
Telerik team
 answered on 20 Aug 2019
2 answers
111 views

I have a problem when trying to use a DoInstead of a method that returns an enum value.

The mocked function is indeed called as expected. However, the return value (an enum) is not returned correctly. Instead it always returns the first value of the enum.

Using Progress Telerik.JustMock 2019.2.620.1 (with license).

Here is a way to reproduce it (Console application, VS2017, Link to Telerik.JustMock dll):

 

namespace TelerikJustMockBug
{
    using System;
    using Telerik.JustMock;
 
    class Program
    {
        delegate CompletionCode MockedReadWriteDelegate(byte[] buffer, int count, out int retCount);
 
        static void Main(string[] args)
        {
            new Program().Run();
        }
 
        private void Run()
        {
            ClassToMock session = Mock.Create<ClassToMock>();
 
            Mock.Arrange(() => new ClassToMock()).Returns(session);
 
            Mock.Arrange(() => session.Read(Arg.IsAny<byte[]>(), Arg.AnyInt, out Arg.Ref(Arg.AnyInt).Value)).DoInstead(new MockedReadWriteDelegate(this.MockedRead));
 
            ClassToMock c = new ClassToMock();
            CompletionCode result = c.Read(new byte[2], 2, out int retCount);
 
            if (retCount != 5)
            {
                throw new Exception("retCount was not set correctly");
            }
 
            if (result != CompletionCode.NOT_SUCCESS)
            {
                // this exception is thrown in my case with 'Wrong result: 0'
                throw new Exception($"Wrong result: {result.ToString()}");
            }
        }
 
        private CompletionCode MockedRead(byte[] buffer, int count, out int retCount)
        {
            retCount = 5;
            return CompletionCode.NOT_SUCCESS;
        }
 
        public enum CompletionCode
        {
            SUCCESS = 1,
            NOT_SUCCESS = 2
        }
 
        public class ClassToMock
        {
            public CompletionCode Read(byte[] buffer, int count, out int retCount)
            {
                throw new Exception("Real implementation - should never be called due to mocking");
            }
        }
    }
}
Ivo
Telerik team
 answered on 08 Aug 2019
4 answers
613 views

Hi guys,

I need to test the handler of a Timer in one class. I'm using Future Mocking to mock the Timer inside it.
Is there some way in order to invoke the callback?

Here my class to test:

 

internal class DatabaseCleaner
{
 
      private Timer mobjTimer = null;
 
      internal void Start()
      {
 
            mobjTimer = new Timer(CleanDB, null, 5000, 1000 * 60 * 10);
      }
 
      internal void Stop()
      {
         if (mobjTimer != null)
         {
            mobjTimer.Dispose();
            mobjTimer = null;
         }
      }
 
      private void CleanDB(object state)
      {

       // do stuff to test

        }
}


Thanks a lot.

Stefano

Ivo
Telerik team
 answered on 25 Jun 2019
Narrow your results
Selected tags
Tags
+? more
Top users last month
Michael
Top achievements
Rank 1
Iron
Wilfred
Top achievements
Rank 1
Alexander
Top achievements
Rank 2
Iron
Iron
Matthew
Top achievements
Rank 1
Iron
ibra
Top achievements
Rank 1
Want to show your ninja superpower to fellow developers?
Top users last month
Michael
Top achievements
Rank 1
Iron
Wilfred
Top achievements
Rank 1
Alexander
Top achievements
Rank 2
Iron
Iron
Matthew
Top achievements
Rank 1
Iron
ibra
Top achievements
Rank 1
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?