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?
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>
In my test I am using both MockingContainer and Mock to do Automocking and create concrete mocks respectively.
At the end of my test I want to ensure all of the functions I setup via Arrange for both the MockingContainer and mocked classes were ran.
Do I need to call .AssertAll() for each mocked object and the MockingContainer or can I simply call Mock.AssertAll() to make sure all Arranged functions were executed? See example below for both approaches.
// Establish mocks
var mockedControllerContainer = new MockingContainer<SomeController>();
var mockedClass = Mock.Create<SomeClass>();
// Establish test variables
IEnumerable<SomeDomainModel> records = new List<SomeDomainModel>();
// Arrange Mocks
mockedControllerContainer
.Arrange<Repository>(repo => repo.FetchRecordsWithName("name"))
.Returns(records);
mockedClass
.Arrange(c => c.SomeFunction())
.Returns(null);
// Assert
mockedControllerContainer.AssertAll();
mockedClass.AssertAll();
// Or can I use the example below to cover all cases?
Mock.AssertAll();
Which approach is best practice to ensure each function was called? This example only had one concrete class but other tests can have many so if I can avoid having to use .AssertAll() for each of them individutally that would be ideal.
The API documentation for Mock.AssertAll() states "Asserts all expected setups in the current context". How is this context defined?
Thank you!
JustMock supports .ReturnsAsync()
when arranging standard mocks, however I am unable to find a way to get this same behavior when Automocking with a MockingContainer<T>
.
A solution I've found is to wrap the return value in Task.FromResult<T>()
. This fulfills the expected Task<T>
return type of the async function, however the syntax is a bit clunky.
service
.Arrange<IRepository>(r => r.SomeAsyncMethod("input"))
.Returns(Task.FromResult<ISomeModel>(resultModel));
Ideally, I would like to avoid building the Task<T>
return values manually and just rely on .ReturnsAsync()
to handle the conversion.
service
.Arrange<IRepository>(r => r.SomeAsyncMethod("input"))
.ReturnsAsync(resultModel);
It's possible the APIs just aren't there, but I want to ensure I'm not just missing some special syntax to get it working.
Hi,
I am trying to run the unit test for my .net 6 and want to see the code coverage using "Analyse Code Coverage for all Tests" in VS2022.
it successfully run all all test cases when I "run all Tests" but when I use "Analyse Code Coverage for all Tests" to run and see the code coverage, there are some test case failed throwing ThrowElevatedMockingException as below.
Message: 
Telerik.JustMock.Core.ElevatedMockingException : Cannot mock 'System.Threading.Tasks.Task`1[System.Collections.Generic.List`1[AppHub.SingleView.AmazonFireStickPromo.Models.AccountPromoToken]] GetAccountPromoTokensAsync(System.String)'. The profiler must be enabled to mock, arrange or execute the specified target.
Detected active third-party profilers:
* {324F817A-7420-4E6D-B3C1-143FBED6D855} (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: 
ProfilerInterceptor.ThrowElevatedMockingException(MemberInfo member)
MocksRepository.CheckMethodInterceptorAvailable(IMatcher instanceMatcher, MethodBase method)
MocksRepository.AddArrange(IMethodMock methodMock)
MocksRepository.Arrange[TMethodMock](Object instance, MethodBase method, Object[] arguments, Func`1 methodMockFactory)
<>c__DisplayClass24_0`1.<Arrange>b__0()
ProfilerInterceptor.GuardInternal[T](Func`1 guardedAction)
NonPublicExpectation.Arrange[TReturn](Object target, String memberName, Object[] args)
PromoCodeManagementServiceTests.GetAllEmailStatusesAsync_WithTokenFromAccount_ExpectedListEmailStatus() line 145
GenericAdapter`1.GetResult()
AsyncToSyncAdapter.Await(Func`1 invoke)
TestMethodCommand.RunTestMethod(TestExecutionContext context)
TestMethodCommand.Execute(TestExecutionContext context)
<>c__DisplayClass1_0.<Execute>b__0()
DelegatingTestCommand.RunTestMethodInThreadAbortSafeZone(TestExecutionContext context, Action action)
I think run all test is successful as I use specify env.runsettings in my project file (attached file).
but the test run in "Analyse Code Coverage for all Tests" failed in some methods.
Package I used
<PackageReference Include="JustMock.Commercial" Version="2023.1.117.1" />
Can someone help me to fix this one ?
Thanks
Hi,
I'm getting the following error for a blazor project using MSTest2 using JustMock flite.
Message:
Test method vx.test.TestsWeb.TestSystemSetup.All_12_Cards_are_found threw exception:
System.TypeInitializationException: The type initializer for 'Telerik.JustMock.Core.Context.MockingContext' threw an exception. ---> System.InvalidOperationException: Some attribute type among Xunit.FactAttribute, xunit.core,Xunit.TheoryAttribute, xunit.core not found.
Stack Trace:
HierarchicalTestFrameworkContextResolver.CreateAttributeMatcher(String[] attributeTypeNames)
HierarchicalTestFrameworkContextResolver.AddRepositoryOperations(String[] attributeTypeNames, Func`2 getKey, Func`3 isInheritingContext, Boolean isLeaf, Boolean isUsedOnAllThreads)
HierarchicalTestFrameworkContextResolver.SetupStandardHierarchicalTestStructure(String[] testMethodAttrs, String[] testSetupAttrs, String[] fixtureSetupAttrs, String[] assemblySetupAttrs, FixtureConstuctorSemantics fixtureConstructorSemantics)
XUnit2xMockingContextResolver.ctor()
MockingContext.cctor()
--- End of inner exception stack trace ---
MockingContext.get_CurrentRepository()
<>c__38`1.<Create>b__38_0()
ProfilerInterceptor.GuardInternal[T](Func`1 guardedAction)
Mock.Create[T]()
TestSystemSetup.All_12_Cards_are_found() line 25
From the following code:
[TestClass]
public class TestSystemSetup : Bunit.TestContext
{
[TestMethod]
public void All_12_Cards_are_found()
{
// Syncfusion setup
JSInterop.Mode = JSRuntimeMode.Loose;
Services.AddSyncfusionBlazor();
// Arrange
IApplicationConfigurationSingleton ApplicationConfigurationSingletonMockObj = Mock.Create<IApplicationConfigurationSingleton>();
Mock.Arrange(() => ApplicationConfigurationSingletonMockObj.Branding_Button_Background_Color).Returns("0xffff");
Mock.Arrange(() => ApplicationConfigurationSingletonMockObj.Branding_Button_Border_Color).Returns("0xffff");
Mock.Arrange(() => ApplicationConfigurationSingletonMockObj.Branding_Button_Color).Returns("0xffff");
Mock.Arrange(() => ApplicationConfigurationSingletonMockObj.IsLicenceExpired).Returns(false);
Mock.Arrange(() => ApplicationConfigurationSingletonMockObj.DaysValidity).Returns(10);
Services.AddSingleton<IApplicationConfigurationSingleton>(ApplicationConfigurationSingletonMockObj);
ISystemSetupRepository SystemSetupRepositoryMockObj = Mock.Create<ISystemSetupRepository>();
Mock.Arrange(() => SystemSetupRepositoryMockObj.GetMenuSummary()).Returns(Task.FromResult(GetSummary_DataSet()));
Services.AddSingleton<ISystemSetupRepository>(SystemSetupRepositoryMockObj);
// Act
IRenderedComponent<SystemSetup> cut = RenderComponent<SystemSetup>();
// Assert all 12 cards are found
cut.Find("#Software_licence");
cut.Find("#Audit_Log");
cut.Find("#Snapshots");
cut.Find("#User_Authentication");
cut.Find("#Source_Of_User_Information");
cut.Find("#Application_Parameters");
cut.Find("#Attachments");
cut.Find("#Data_Export_Profiles");
cut.Find("#Email_Settings");
cut.Find("#Custom_Help");
cut.Find("#Splunk_Settings");
cut.Find("#ServiceNow_Settings");
}
}
A bit puzzled as to why the error references xunit.
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?
There is one interface where when I try to mock it it throws an exceptions
System.IO.FileLoadException : Could not load file or assembly 'MyFramework, Version=2017.12.12.1, Culture=neutral, PublicKeyToken=null' or one of its dependencies. A strongly-named assembly is required.
None of our projects are strong named, and my best guess is that it has something to do with the nature of the interface we're trying to mock. For simplicity sake I'll describe our project like this:
One of the methods in the IMessageLogger interface has an argument where the type is defined in the MyFramework project.
When I call Mock.Create<IMessageLogger>() I get the error above. My only thought is that because the Telerik.JustMock assembly is strong named, it is for some reason having trouble loading the MyFramework assemble even though it can miraculously load the MyFramework.Lib assembly.
I was wondering if there is any workaround I might be able to try so that I can mock this piece. I can live without mocking this specific interface, but I may not be so lucky with others...