Telerik Forums
JustMock Forum
1 answer
6 views

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!

Ivo
Telerik team
 answered on 21 Mar 2024
1 answer
24 views

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.

Tsvetko
Telerik team
 answered on 03 Jan 2024
2 answers
132 views

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

Minh
Top achievements
Rank 1
Iron
 updated answer on 20 Apr 2023
2 answers
391 views

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.

 

michael
Top achievements
Rank 1
Iron
 answered on 21 Oct 2021
1 answer
69 views
Hi ,

I am actually intended to write a UT  for the following code.
Private void GetVersion(){
string version=GetLatest();
if(string.IsNullOrEmpty(version))
Throw new InvalidException("Ivalid version");

How to write a unit test for the above code?
Mihail
Telerik team
 answered on 07 Feb 2020
5 answers
74 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
5 answers
170 views
I have installed JustMock free edition to work with some code another dev left behind him. No tests run, they all complain:
"There were some problems intercepting the mock call. Optionally, please make sure that you have turned on JustMock's profiler while mocking concrete members."

I need a DETAILED, PICTORIAL description of how to enable the profiler, because everything I see in these forums just says "oh, the solution is to enable the profiler." HOW? WHERE? I can read the message, but I see NOTHING that looks vaguely appropriate.

Is there supposed to be a JustMock menu? Button? Dancing bear? I've attached a screenshot, please diagnose what's going on. I've 

I've wasted an hour of time beating my head against this, and I'm extremely frustrated with it. Is the profiler not included with the Free edition?

Mihail
Telerik team
 answered on 26 Apr 2018
1 answer
90 views

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:

  • Processor --the project I'm actually testing
  • Processor.Tests --The project the tests are running from
  • MyFramework.Lib --The project that contains the interface (IMessageLogger) I'm trying to mock
  • MyFramework --internal dll that all projects reference

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...

Lyubomir Rusev
Telerik team
 answered on 04 Apr 2018
2 answers
62 views

Hi,

 

I have 2 interfaces (I1 and I2) that have a property called FileName. Another interface is inheriting these two interfaces. Let us call it I3.In I3, I am using new modifier (this is C#) so that in my code I do not get FileName property displayed twice and prevent compiler ambiguity errors.

When I mock interface I3 and set the FileName value, this value does not propagate to interfaces I1 and I2. This is not an issue in my actual code. 

I have attached a sample pictures of the code. The first assert works. Second and third fail.

Assert.IsTrue(toTest.FileName == @"test file name", "FileName missing"); //1
Assert.IsTrue((toTest as Interface1).FileName== @"test file name","FileName missing"); //2
Assert.IsTrue((toTest as Interface2).FileName == @"test file name", "FileName missing"); //3

Am I doing something wrong OR is this a bug with the lite version of JustMock?

Thank you for time taken to read and any direction to resolve my challenge.

Sainath

 

Sainath
Top achievements
Rank 1
 answered on 31 May 2017
1 answer
90 views

I had a first try with JustMock on a Linux build machine (Jenkins) and xunit (Mono 4.6 is installed there). Unfortuntely, I get the following exception (one of them):

01.Tnsa.Foundation.Test.Composition.Internal.CompositionContextServiceProviderAdapterTest.GetService_ExportFactories_enumerable_generic_2_success [FAIL]
02.  System.Runtime.Remoting.RemotingException : Cannot get the real proxy from an object that is not a transparent proxy.
03.  Stack Trace:
04.      at System.Runtime.Remoting.RemotingServices.GetRealProxy (System.Object proxy) [0x0000b] in <94fd79a3b7144c54b4cb162b50fc7761>:0
05.      at Telerik.JustMock.Core.TransparentProxy.MockingProxy.GetRealProxy (System.Object instance) [0x00005] in <45764d21e4e34d73b89fbb0a6b2e6054>:0
06.      at Telerik.JustMock.Core.TransparentProxy.MockingProxy.GetMockMixin (System.Object instance) [0x00000] in <45764d21e4e34d73b89fbb0a6b2e6054>:0
07.      at Telerik.JustMock.Core.MocksRepository.GetMockMixinFromAnyMock (System.Object mock) [0x00000] in <45764d21e4e34d73b89fbb0a6b2e6054>:0
08.      at Telerik.JustMock.Core.MocksRepository.GetMockMixin (System.Object obj, System.Type objType) [0x00000] in <45764d21e4e34d73b89fbb0a6b2e6054>:0
09.      at Telerik.JustMock.Core.MocksRepository.ConvertExpressionToCallPattern (System.Linq.Expressions.Expression expr, Telerik.JustMock.Core.CallPattern callPattern) [0x00564] in <45764d21e4e34d73b89fbb0a6b2e6054>:0
10.      at Telerik.JustMock.Core.MocksRepository.Arrange[TMethodMock] (System.Linq.Expressions.Expression expr, System.Func`1[TResult] methodMockFactory) [0x00049] in <45764d21e4e34d73b89fbb0a6b2e6054>:0
11.      at Telerik.JustMock.Helpers.FluentHelper.DoArrange[TContainer] (System.Object obj, System.Type objType, System.Linq.Expressions.LambdaExpression expression, System.Func`1[TResult] containerFactory) [0x00036] in <45764d21e4e34d73b89fbb0a6b2e6054>:0
12.      at Telerik.JustMock.Helpers.FluentHelper+<>c__DisplayClass2`2[T,TResult].<Arrange>b__0 () [0x0002e] in <45764d21e4e34d73b89fbb0a6b2e6054>:0
13.      at Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal[T] (System.Func`1[TResult] guardedAction) [0x0000c] in <45764d21e4e34d73b89fbb0a6b2e6054>:0
14.      at Telerik.JustMock.Helpers.FluentHelper.Arrange[T,TResult] (T obj, System.Linq.Expressions.Expression`1[TDelegate] expression) [0x00020] in <45764d21e4e34d73b89fbb0a6b2e6054>:0
15.      at Tnsa.Foundation.Test.Composition.Internal.CompositionContextServiceProviderAdapterTest.GetService_ExportFactories_enumerable_generic_2_success () [0x0006f] in <e1aa8dcdd51045fda2db8ea7350c0c44>:0
16.      at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
17.      at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00038] in <94fd79a3b7144c54b4cb162b50fc7761>:0

 

Is this scenario supported on Linux/Mono at all? Can I do something to make this work?

Thanks, Ioan

Svetlozar
Telerik team
 answered on 12 Dec 2016
Narrow your results
Selected tags
Tags
+? more
Top users last month
horváth
Top achievements
Rank 2
Iron
Iron
Steve
Top achievements
Rank 2
Iron
Erkki
Top achievements
Rank 1
Iron
Mark
Top achievements
Rank 2
Iron
Iron
Veteran
Jakub
Top achievements
Rank 1
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
horváth
Top achievements
Rank 2
Iron
Iron
Steve
Top achievements
Rank 2
Iron
Erkki
Top achievements
Rank 1
Iron
Mark
Top achievements
Rank 2
Iron
Iron
Veteran
Jakub
Top achievements
Rank 1
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?