Hi,
I'm interested in Telerik JustMock, so I'm installing and testing a trial version of JustMock.I want the Mock to return the SQL statement and Not execute the statement. This is what i have done but it keeps running the "connection.execution(SQL)".
string SQL = "";
Mock.Arrange(() => connection.Execute(Arg.AnyString, null, null, null, null)).DoInstead((string arg1) => { SQL = arg1; }).IgnoreInstance().Returns(1);
WebApiProject.Controllers.DeleteController dc = new WebApiProject.Controllers.DeleteController();
dc.Post(mockedDeleteObject);
Assert.IsTrue(SQL == $"DELETE FROM TEST WHERE 1=1");
Post{
string SQL;
SQL = $"delete from {TableName} where {WhereClause} ";
con.Execute(SQL,parameters );}
But it keeps running the sql executable statement
01.
[Fact]
02.
public
void
Reconcile_LocationGroupChangedEvent_ReconcileSuccessfully()
03.
{
04.
using
(var container =
new
MockingContainer<Assignment>(settings))
05.
{
06.
//Arrange
07.
container.Arrange<IFacade>(x =>x.Initialize()).OccursAtMost(1);
08.
09.
//Act
10.
container.Instance.Reconcile();
11.
12.
//Assert
13.
container.AssertAll();
14.
}
15.
}
16.
17.
// Method under test
18.
19.
public
void
Reconcile()
20.
{
21.
Task.Factory.StartNew(() => facade.Initialize());
22.
}
I am getting intermittent errors when running the above Test. It fails so infrequently that I am unable to debug. When it fails, here is what I see in the logs.
Reconcile_Test [FAIL]
System.InvalidOperationException : Collection was modified; enumeration operation may not execute.
Stack Trace:
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Enumerator.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.<
SelectManyIterator
>d__23`3.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Telerik.JustMock.Core.MocksRepository.GetDebugView(Object mock)
at Telerik.JustMock.DebugView.<>c.<
get_CurrentState
>b__1_0()
at Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal[T](Func`1 guardedAction)
at Telerik.JustMock.DebugView.TraceEvent(IndentLevel traceLevel, Func`1 message)
at Telerik.JustMock.Core.Context.MockingContext.ResolveRepository(UnresolvedContextBehavior unresolvedContextBehavior)
at Telerik.JustMock.Helpers.FluentHelper.<>c__DisplayClass13_0`1.<
AssertAll
>b__0()
at Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal(Action guardedAction)
at Telerik.JustMock.AutoMock.MockResolver.ForEachMock(Action`1 action)
at Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal(Action guardedAction)
E:\agt01\COM-CN-JOB1\AssignmentTest.cs(14,0): at AssignmentTest.Reconcile_Test()
Unfortunately my JustMock does not work anymore. I get this exception:
Message:Some background:
- I started of with VS2019 version 16.10.4 and JustMock version 2019.2.620.1
- Profiler is enabled in Extensions->JustMock
- tried to reinstall -> no effect
- upgraded VS2019 to 16.11.9 -> no effect
- upgraded to JustMock 2022.1.119.1 -> no effect
- Above is just a sample, all of my unit tests that use JustMock fail
- I checked a colleague and he had exactly the same problem
Any setting/config I might have missed?
Regards,
Dirk
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 am trying to run to Dotnet Test command for .NetCore dll in Azure Devops and It throws exception for some tests saying elevated Mocking Exception.
Comand Used is
Hi,
Please let me know on how do we mock a private constructor.
Example:
public class Test public class Sum
{
public int GetSum()
{
return SumBy2.Add1(10,5);
}
public int GetSum2()
{
SumBy1 by1 = new SumBy1();
return by1.Add(10, 5);
}
private class SumBy1
{
public int Add(int a, int b)
{
return a + b;
}
}
private static class SumBy2
{
public static int Add1(int a, int b)
{
return a + b;
}
}
}
Need to create Unit tests for Sum class.
I added C# JustMock Test Project (.NET Framework) to my solution. The resulting project has five references Microsoft.VisualStudio.TestPlatform.TestFramework, Microsoft.VisualStudio.TestPlatform.TestFrameworkExtensions, System, System.Core and Telerik.JustMock. All of the references had the yellow alert icon next to them. Looking at the properties, none showed a Path.
I was surprised to see System.Core as a reference, since I selected the .NET Framework project. To verify, I removed that project and added a new Test Project, verifying I selected the .NET Framework. Same results.
As a test, I added a VB.NET JustMock Test Project (.NET Framework). It had two erroring references – the Microsoft TestPlatforms. Using NuGet Package Manager, I updated them both from 1.4.0 to 2.2.7. That eliminated the error.
I used NuGet to update the same two references in my C# project, but they still show errors. I also tried removing the reference to Telerik.JustMock.dll and re-adding it by browsing to the file. Still shows error.
Finally, my VB.NET project builds, but my C# build errors with this message: “This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is ..\packages\MSTest.TestAdapter.1.3.2\build”. Doing the package restore does not resolve this message.
Any thoughts as to how I can resolve this? Thanks in advance.
Steve.
Hi,
I'm trying to create a pipeline on Azure for test/coverage using JustMock, my application is Core 5.0*
After a long journey to make the build work, now I'm encountering an issue with the test (JustMockVSTestV2)
steps:
- task: vs-publisher-443.jm-vstest-2.JustMockVSTest-2.JustMockVSTest@2
displayName: 'VsTest - testAssemblies'
inputs:
testAssemblyVer2: |
**\bin\**\*test*.dll
!**\*TestAdapter.dll
!**\*TestPlatform*
!**\obj\**
!**\bin\**\ref\**
pathTo64BitJustMockProfiler: '[correctpath]\bin\Release\net5.0\runtimes\win-x64\native\Telerik.CodeWeaver.Profiler.dll'
pathTo32BitJustMockProfiler: '[correctpath]\bin\Release\net5.0\runtimes\win-x86\native\Telerik.CodeWeaver.Profiler.dll'
vsTestVersion: toolsInstaller
runTestsInIsolation: true
codeCoverageEnabled: true
otherConsoleOptions: '/Framework:.NETCoreApp,Version=v5.0.401 /Enablecodecoverage /logger:trx'
platform: '$(BuildPlatform)'
configuration: '$(BuildConfiguration)'
My Test functions requires elevation:
Mock.SetupStatic(typeof(AStaticClass));
var response = Mock.Create<IRestResponse<string>>(); //this is restsharp
Mock.Arrange(() => response.Data)
.Returns("SomeData");
var client = Mock.Create<RestClient>(Constructor.Mocked);
Mock.Arrange(() => client.ExecuteAsync<string>(Arg.IsAny<IRestRequest>(), Arg.IsAny<CancellationToken>()))
.IgnoreInstance()
.TaskResult(response);
My test project works fine on my local machine when I enable JustMock profile, however I get a bunch of errors on Azure pipeline:
##[error][xUnit.net 00:00:03.76] ProjectTests.GetAsync_StateUnderTest_ExpectedBehavior [FAIL]
[xUnit.net 00:00:03.76] System.InvalidProgramException : Common Language Runtime detected an invalid program.
[xUnit.net 00:00:03.76] Stack Trace:
[xUnit.net 00:00:03.79] at ProjectTests.GetAsync_StateUnderTest_ExpectedBehavior()
[xUnit.net 00:00:03.79] at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
[xUnit.net 00:00:03.79] at ProjectTests.GetAsync_StateUnderTest_ExpectedBehavior()
ALSO
##[error]Testhost process exited with error: Cannot use file stream for [PATH\bin\Release\net5.0\testhost.deps.json]: No such file or directory
##[error]A fatal error was encountered. The library 'hostpolicy.dll' required to execute the application was not found in 'C:\hostedtoolcache\windows\dotnet'.
##[error]Failed to run as a self-contained app.
##[error] - The application was run as a self-contained app because 'PATH\bin\Release\net5.0\testhost.runtimeconfig.json' was not found.
##[error] - If this should be a framework-dependent app, add the 'PATH\bin\Release\net5.0\testhost.runtimeconfig.json' file and specify the appropriate framework.
##[error]. Please check the diagnostic logs for more information.
Please advice, I'm not able to make JustMock to work with Azure Pipeline.
Thanks