Telerik Forums
JustMock Forum
1 answer
14 views

I am trying to mock async static methods,

so I decided to download the trial version.

downloaded the file JustMock_2025_1_211_365_x64_Trial.tar

it seems that the .dll included in the archive is not compatible with .NET Framework 4.8

can you provide justmock trial version dll which is compatible with .NET Framework 4.8?

Ivo
Telerik team
 answered on 17 Mar 2025
2 answers
23 views

The following attached test works without enabling the profiler with the runsettings attached to the .csproj.
If we enable it, the DoInstead doesn't run, and the test fails in Visual Studio and vstest console runner.

runsettings:

<?xml version="1.0" encoding="utf-8" ?>
<RunSettings>
	<RunConfiguration> 
		<EnvironmentVariables> 
			<JUSTMOCK_INSTANCE>1</JUSTMOCK_INSTANCE>
			<COR_ENABLE_PROFILING>1</COR_ENABLE_PROFILING>
			<COR_PROFILER>{B7ABE522-A68F-44F2-925B-81E7488E9EC0}</COR_PROFILER>		
			<COR_PROFILER_PATH_64>c:\work\client-dependencies\NuGet\repo\justmock.commercial\2024.4.1203.350\runtimes\win-x64\native\Telerik.CodeWeaver.Profiler.dll</COR_PROFILER_PATH_64>
		</EnvironmentVariables> 
	</RunConfiguration> 
</RunSettings>

Change COR_ENABLE_PROFILING to 0, and test works.

Production Code:

  /// <summary>
  /// Pregunta la ruta de la carpeta de exportación.
  /// </summary>
  /// <param name="exportPDFDafaultPath">Ruta por defecto para exportar PDF.</param>
  /// <returns>Ruta de la carpeta de exportación.</returns>
  public string AskExportFolderPath(string exportPDFDafaultPath = null)
  {
      this.systemDialogAdapter.ShowFolderBrowserDialog(Environment.NewLine + "Seleccione una ruta.", exportPDFDafaultPath, out string folderPath, true);
      return folderPath;
  }


Test Code:

[Fact] public void AskExportFolderPath_ShouldReturnFolderPath_WhenDialogResultIsOK() { // Arrange

var sutAndMocks = GetSutAndMocks(); var exportSharedServiceSut = sutAndMocks.Sut; string folderPath; Mock.Arrange(() => sutAndMocks.Mock<ISystemDialogAdapter>().ShowFolderBrowserDialog(Arg.AnyString, Arg.AnyString, out folderPath, Arg.AnyBool, Arg.IsAny<Action<IMessageBoxDialogVM>>(), Arg.IsAny<Action<IMessageBoxDialogVM>>())) .DoInstead((string descriptionMessage, string startFolderUbicacion, outstring selectedFolder) => { selectedFolder = "test"; }); // Act

var result = exportSharedServiceSut.AskExportFolderPath(); // Assert Assert.Equal("test", result); }

private static SutAndMocks<ExportSharedService> GetSutAndMocks()
{
   SutAndMocks<ExportSharedService> result = new SutAndMocks<ExportSharedService>();
   result.AddMock(Mock.Create<ISystemDialogAdapter>());
   result.AddMock(Mock.Create<IFileWrapper>());
   result.AddMock(Mock.Create<SaveFileDialog>());
   result.AddMock(Mock.Create<BackgroundWorker>());

   result.Sut = new ExportSharedService(
          result.Mock<ISystemDialogAdapter>(),
          result.Mock<IFileWrapper>(),
          result.Mock<SaveFileDialog>(),
          result.Mock<BackgroundWorker>());

   return result;

}

I download last version 2025.1.211.365, same result.

If I mock directly without SutAndMock class works with profiler

Seems profiler change something when we use:

public TMock Mock<TMock>()
{
   return (TMock)mocks[typeof(TMock)]; //here the problem (Unboxing)
}
 public class SutAndMocks<T>
 {
     private readonly Dictionary<Type, object> mocks = new Dictionary<Type, object>();
     private readonly Dictionary<Type, Dictionary<string, object>> mocksWithName = new Dictionary<Type, Dictionary<string, object>>();

     /// <summary>
     /// System under test.
     /// </summary>
     public T Sut { get; set; }

     /// <summary>
     /// Retorna el Mock de un tipo.
     /// </summary>
     /// <typeparam name="TMock">Tipo de mock.</typeparam>
     public TMock Mock<TMock>()
     {
         return (TMock)mocks[typeof(TMock)];
     }

     /// <summary>
     /// Retorna el Mock con su name.
     /// </summary>
     /// <typeparam name="TMock">Tipo de mock con su name</typeparam>
     public TMock Mock<TMock>(string name)
     {
         return (TMock)mocksWithName[typeof(TMock)][name];
     }

     /// <summary>
     /// Añade un mock.
     /// </summary>
     /// <typeparam name="TMock">Tipo de mock.</typeparam>
     public void AddMock<TMock>(TMock mock)
     {
         this.mocks[typeof(TMock)] = mock;
     }

     /// <summary>
     /// Añade un mock.
     /// </summary>
     /// <typeparam name="TMock">Tipo de mock.</typeparam>>
     /// <param name="name">Nombre de la clase</param>
     public void AddMock<TMock>(TMock mock, string name)
     {
         if (this.mocksWithName.ContainsKey(typeof(TMock)))
         {
             this.mocksWithName[typeof(TMock)][name] = mock;
         }
         else
         {
             this.mocksWithName[typeof(TMock)] = new Dictionary<string, object> { { name, mock } };
         }
     }

 }

Works saving mock into a var, out of arrange delegate:

ISystemDialogAdapter sa = sutAndMocks.Mock<ISystemDialogAdapter>();
Mock.Arrange(() => sa.ShowFolderBrowserDialog(Arg.AnyString, Arg.AnyString, out folderPath, Arg.AnyBool, Arg.IsAny<Action<IMessageBoxDialogVM>>(), Arg.IsAny<Action<IMessageBoxDialogVM>>()))
        .DoInstead((string descriptionMessage, string startFolderUbicacion, outstring selectedFolder) =>
        {
            selectedFolder = "test";
        });

Any help? this problem force to change all test of our commercial application, we buy commercial JustMock because need profiler activation for some test, like static class, etc

Javier
Top achievements
Rank 1
Iron
 answered on 13 Mar 2025
1 answer
27 views
Recently started using JustMock to create unit tests so my knowledge is limited at time. I have the below test code with occurrence expectations on a few arrangements for different objects set. The intention was that the mocked ItemCollection and mocked RadComboBox objects were to be used 3 times to avoid having to create them again, since nothing about the calls change and the mocked SelectionChangedEventArgs object was to be recreated each time with different arrangements.

However, when I assert the expectations on mockSelectionChangedEventArgs, somehow that is also asserting the expectations on itemCollection_Single and radComboBox_Single which both fail because at the time there has only been one call on each of Count and Items. By the end when I do assert the expectations on itemCollection_Single  and radComboBox_Single it would be 3 as in my expectations since I would have used them 3 times.

Why does asserting all expectations on mockSelectionChangedEventArgs assert them on the other two objects? I cannot find any documentation on this scenario. I can avoid this issue by specifically mocking mockSelectionChangedEventArgs.AddedItems and mockSelectionChangedEventArgs.OriginalSource, but I don't see why that is necessary.

            ItemCollection itemCollection_Single = Mock.Create<ItemCollection>(Behavior.Strict);
            Mock.Arrange(() => itemCollection_Single.Count).Returns(2).Occurs(3, nameof(itemCollection_Single.Count));

            RadComboBox radComboBox_Single = Mock.Create<RadComboBox>(Behavior.Strict);
            Mock.Arrange(() => radComboBox_Single.Items).Returns(itemCollection_Single).Occurs(3, nameof(radComboBox_Single.Items));

            mockSelectionChangedEventArgs = Mock.Create<SelectionChangedEventArgs>(Behavior.Strict);
            Mock.Arrange(() => mockSelectionChangedEventArgs.AddedItems).Returns(new List<ParameterValue>() { selectionRuleRow.AllowedValues[0] }).Occurs(2, nameof(mockSelectionChangedEventArgs.AddedItems));
            Mock.Arrange(() => mockSelectionChangedEventArgs.OriginalSource).Returns(radComboBox_Single).Occurs(1, nameof(mockSelectionChangedEventArgs.OriginalSource));

            selectionRuleRow.MultipleEnumSelectionChanged.Execute(mockSelectionChangedEventArgs);

            Assert.AreEqual(expected: "Yes", actual: selectionRuleRow.Value);
            Assert.IsTrue(selectionRuleRow.CanApply);

            Mock.Assert(mockSelectionChangedEventArgs); // ==> fails because of set expectations on itemCollection_Single and radComboBox_Single 
            //Mock.Assert(() => mockSelectionChangedEventArgs.AddedItems, Occurs.Exactly(1));
            //Mock.Assert(() => mockSelectionChangedEventArgs.OriginalSource, Occurs.Exactly(1));

Ivo
Telerik team
 answered on 12 Feb 2025
1 answer
47 views

Hey, 

I'm using the method Ivo created here https://www.telerik.com/forums/vs2022---justmock-throwelevatedmockingexception-with-net-6

to build my runsettings file and generate code coverage in the command line with .net8. 

Using 

dotnet test my.sln --configuration Release --no-build --no-restore --settings test-coverage.runsettings

I would like to exclude dlls with Test in the name and also output xml or cobertura if possible but I can't seem to get it to work. Any ideas? Run settings below

<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
  <RunConfiguration>
    <ResultsDirectory>\CodeCoverageTestResults</ResultsDirectory>
    <TestAdaptersPaths>C:\JustMock\Libraries\DataCollectors;C:\Users\GitHubRunner\.nuget\packages\microsoft.codecoverage\17.11.0\build\netstandard2.0</TestAdaptersPaths>
  </RunConfiguration>

  <DataCollectionRunSettings>
    <DataCollectors>
      <DataCollector friendlyName="Code Coverage Wrapper">
        <Configuration>
          <JustMockSettings>
            <ProfilerPath32>C:\JustMock\Libraries\32\Telerik.CodeWeaver.Profiler.dll</ProfilerPath32>
            <ProfilerPath64>C:\JustMock\Libraries\64\Telerik.CodeWeaver.Profiler.dll</ProfilerPath64>
          </JustMockSettings>
          <SinkDataCollector friendlyName="Code Coverage" uri="datacollector://Microsoft/CodeCoverage/2.0" isLinked="true">
            <!-- Exclude DLLs with ".tests." in the name -->
            <CodeCoverage>
              <Exclude>
                <ModuleFilePattern>*\.Tests\.*</ModuleFilePattern>
              </Exclude>
            </CodeCoverage>
          </SinkDataCollector>
        </Configuration>
      </DataCollector>
      <DataCollector friendlyName="JustMockDataCollector" />
    </DataCollectors>
  </DataCollectionRunSettings>
</RunSettings>

Ivo
Telerik team
 answered on 03 Feb 2025
2 answers
55 views

Hi,

on a new build server with only Visual Studio 2022, a pipeline with a task Telerik JustMock VSTest v.2 failed. On another build server the task runs fine but this server has Visual Studio 2017 and 2019.

With only Visual Studio 2022, I see this in the logs :

2024-10-29T08:40:10.1079920Z ##[debug]E:\AzureDevOps\Agents\Cloee2Agent1\_work\_tasks\JustMockVSTest_dfc18792-8901-4297-a4de-6edef6796070\2.4.1\vswhere.exe arg: -version [16.0,17.0) -latest -products * -requires Microsoft.VisualStudio.PackageGroup.TestTools.Core -property installationPath
2024-10-29T08:40:10.1080395Z ##[debug]exec tool: E:\AzureDevOps\Agents\Cloee2Agent1\_work\_tasks\JustMockVSTest_dfc18792-8901-4297-a4de-6edef6796070\2.4.1\vswhere.exe
2024-10-29T08:40:10.1080699Z ##[debug]arguments:
2024-10-29T08:40:10.1080925Z ##[debug]   -version
2024-10-29T08:40:10.1081156Z ##[debug]   [16.0,17.0)
2024-10-29T08:40:10.1081399Z ##[debug]   -latest
2024-10-29T08:40:10.1081624Z ##[debug]   -products
2024-10-29T08:40:10.1081840Z ##[debug]   *
2024-10-29T08:40:10.1082053Z ##[debug]   -requires
2024-10-29T08:40:10.1082310Z ##[debug]   Microsoft.VisualStudio.PackageGroup.TestTools.Core
2024-10-29T08:40:10.1082557Z ##[debug]   -property
2024-10-29T08:40:10.1082780Z ##[debug]   installationPath

 

The call to vswhere ask for version "[16.0,17.0)". In the properties of the task I specify "Test Plateform Version : Latest". So why is vswhere searching only for version 16 and 17 ?

Thank you

 

SIEN
Top achievements
Rank 1
Iron
Iron
 answered on 06 Nov 2024
1 answer
69 views
The latest version of JustMock contains a reference to System.Drawing.Common 5.0.0.   That component has a critical severity security alert associated with it.  I know I could add a reference to the latest System.Drawing.Common package to every project that is referencing JustMock, but since this is dozens of projects and I will never remember to remove this hard reference to the drawing package once it is fixed, it would be better if JustMock updated its reference.  Is this possible to get into the next release?
Ivo
Telerik team
 answered on 24 Jul 2024
1 answer
60 views

For the sake of brevity, I've included a minimal example below. An async event MyEventAsync is defined in class MyClass. An event handler OnMyEventAsync is also defined.


public class MyClass
{
    // Event.
    public event Func<EventArgs, Task>? MyEventAsync;
}

// Event handler.
private Task OnMyEventAsync(EventArgs args) => Task.CompletedTask;

I then create a mock of MyClass and register the event handler OnMyEventAsync with the event MyEventAsync. Then Raise the event with the syntax given in the documentation.

// Create mock.
var mockClass = Mock.Create<MyClass>(Behavior.Strict);

// Register event handler.
mockClass.MyEventAsync += OnMyEventAsync;

// Raise event on mock.
Mock.Raise(() => mockClass.MyEventAsync += null, EventArgs.Empty);

But I receive the following error:

Telerik.JustMock.Core.MockException : Event signature System.Threading.Tasks.Task OnMyEventAsync(System.EventArgs) is incompatible with argument types (Castle.Proxies.ExternalMockMixinProxy, System.EventArgs)

I've probably missed something very obvious here. I know the above syntax should work with an event of type EventHandler<EventArgs>, but I'm not sure how to modify it to work with event of type Func<EventArgs, Task>. If anyone could clear up my confusion, I'd be most grateful. Thanks! =)

 

Ivo
Telerik team
 answered on 25 Jun 2024
1 answer
195 views

Support,

I am attempting to use JustMock to mock ServiceSecurityContext based on this article here.

If I am understanding this Telerik article, I should be able to use the NuGet package and configure a profiler using a ".runsettings" file without needing to install the configuration tool.

Here is the .runsettings file I have added to my test project:

<RunSettings>
    <RunConfiguration>
      <EnvironmentVariables>
        <JUSTMOCK_INSTANCE>1</JUSTMOCK_INSTANCE>
        <CORECLR_ENABLE_PROFILING>1</CORECLR_ENABLE_PROFILING>
        <CORECLR_PROFILER>{B7ABE522-A68F-44F2-925B-81E7488E9EC0}</CORECLR_PROFILER>
        <CORECLR_PROFILER_PATH>..\packages\justmock.commercial\2024.2.514.325\runtimes\win-x64\native\Telerik.CodeWeaver.Profiler.dll</CORECLR_PROFILER_PATH>
      </EnvironmentVariables>
    </RunConfiguration>
</RunSettings>

Unfortunately, this did not work and I am still getting the following error when running my tests.

Telerik.JustMock.Core.ElevatedMockingException: Cannot mock 'System.ServiceModel.ServiceSecurityContext'. The profiler must be enabled to mock, arrange or execute the specified target.
Detected active third-party profilers:
* {865fc36f-7fab-44b6-bbb7-c2baea8d9ad2} (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.

 

What am I missing to get this configured?

 

Thanks,
-Scott

Ivo
Telerik team
 answered on 17 Jun 2024
1 answer
145 views

Hello,

I am currently trying to mock a service I have set up (let's call it ObjectService). It's fairly straightforward - I'm just trying to verify the user is authenticated, and then the response will return an object. This is roughly what it looks like:

private Object _object;

public virtual async Task<Object> GetObject(string token,string url)
{
    var client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
    var response = await client.GetStringAsync(url);
    client.Dispose();
    _object = JsonConvert.DeserializeObject<Object>(response);
    
    return _object;
}
I'm running into issues trying to use JustMock to mock this service.  What would be the best way for me to write a unit test for this? 
Ivo
Telerik team
 answered on 14 Jun 2024
1 answer
73 views

We've started seeing the above error on our build server.  It seems to have appeared out of nowhere.

xUnit.net Console Runner v2.4.1 (64-bit Desktop .NET 4.7.2, runtime: 4.0.30319.42000)
      Discovering: IRONSolutions.Core.Tests
      Discovered:  IRONSolutions.Core.Tests
      Starting:    IRONSolutions.Core.Tests
        [FATAL ERROR] System.ArgumentException
          System.ArgumentException : 'this' type cannot be an interface itself.
          Stack Trace:
               at System.RuntimeTypeHandle.VerifyInterfaceIsImplemented(RuntimeTypeHandle handle, RuntimeTypeHandle interfaceHandle)
               at System.RuntimeTypeHandle.VerifyInterfaceIsImplemented(RuntimeTypeHandle interfaceHandle)
               at System.RuntimeType.GetInterfaceMap(Type ifaceType)
               at Telerik.JustMock.Core.MockingUtil.IsImplementedBy(MethodInfo interfaceMethod, MethodBase implMethod)
               at Telerik.JustMock.Core.Context.HierarchicalTestFrameworkContextResolver.MatchTestClassDispose(MethodBase method, String[] testMethodAttributes)
               at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source, Func`2 predicate)
               at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
               at System.Linq.Enumerable.<DistinctIterator>d__64`1.MoveNext()
               at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
               at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
               at Telerik.JustMock.Core.Context.HierarchicalTestFrameworkContextResolver.GetTestMethod()
               at Telerik.JustMock.Core.Context.HierarchicalTestFrameworkContextResolver.FindTestMethod(Int32& repoIdx, RepositoryOperationsBase& entryOps)
               at Telerik.JustMock.Core.Context.HierarchicalTestFrameworkContextResolver.ResolveRepository(UnresolvedContextBehavior unresolvedContextBehavior)
               at Telerik.JustMock.Core.Context.MockingContext.ResolveRepository(UnresolvedContextBehavior unresolvedContextBehavior)
               at Telerik.JustMock.Core.MocksRepository.GetMockMixin(Object obj, Type objType)
               at Telerik.JustMock.Core.Invocation..ctor(Object instance, MethodBase method, Object[] args)
               at Telerik.JustMock.Core.ProfilerInterceptor.InterceptCall(RuntimeTypeHandle typeHandle, RuntimeMethodHandle methodHandle, Object[] data)
               at System.Environment.get_NewLine()
               at System.Exception.PrepForRemoting()
               at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
               at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
        [FATAL ERROR] System.ArgumentException
          System.ArgumentException : 'this' type cannot be an interface itself.


Has anyone seen this error before and know of a fix?  Any help would be greatly appreciated.  We're using JustMock_2023_1_117_1_Dev.

Martin
Telerik team
 answered on 01 May 2024
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?