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?
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
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));
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>
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 :
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
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! =)
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
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;
}
We've started seeing the above error on our build server. It seems to have appeared out of nowhere.
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.