Telerik Forums
JustMock Forum
1 answer
671 views

 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.

Ivo
Telerik team
 answered on 05 Oct 2021
1 answer
208 views

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.

Mihail
Telerik team
 answered on 20 Sep 2021
1 answer
949 views

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

Ivo
Telerik team
 answered on 17 Sep 2021
1 answer
200 views

Hi,

we have a class like this.

 

public class MssqlDbConnection : ISecuredDatabaseConnection, IDisposable
    {
        #region Fields
        private SqlConnection _connection = null;

     }

 

And I am creating Private Mock like this

             SqlConnection Sql = new SqlConnection();
            // Connected Mock
            Mock.NonPublic.Arrange<SqlConnection>(typeof(MssqlDbConnection), "_connection").Returns(Sql);

This Statement causes crash with System.MissingMemberException in just mock

 

Please let me know on this.

 

Regards,

Chandra.

Ivo
Telerik team
 answered on 17 Sep 2021
2 answers
437 views

Error when trying to mock Microsoft.ServiceFabric.Services.Client with the following code:


using Microsoft.ServiceFabric.Services.Client;

[Fact]

public void Foo() {

var spr = Mock.Create<ServicePartitionResolver>();

}

When I run this simple test I got:


Message: 
System.TypeLoadException : Could not load type 'System.Runtime.Remoting.Proxies.RealProxy' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

  Stack Trace: 
MocksRepository.Create(Type type, MockCreationSettings settings)
<>c__38`1.<Create>b__38_0()
ProfilerInterceptor.GuardInternal[T](Func`1 guardedAction)
Mock.Create[T]()

 

NovoPath
Top achievements
Rank 1
Iron
 answered on 15 Sep 2021
1 answer
559 views
I have a parent report with 
inline CSV1 
Descr Value
Verified 1
Not-Verified 0

inline CSV2
Descr value
ChartView 0
GridView 1

Report Parameters
Id supplied to report
Verified visible selected from inline CSV1
View visible selected from inline CSV2
Months visible multi-selected from Distinct list of 'FormattedDate' in 'dsMain'
Statuses visible multi-selected from Distinct list of 'Status' in 'dsMain'


I have a stored proc taking params 'Id' and 'Verified' from parent report to populate 'dsMain' datasource.
Stored proc to be called only when 'Id' or 'Verified' change and returning data including.... 
Id
Verified
Date(01-mm-yyyy) 
FormattedDate(MMM yy)
Status (S1,S2,S3,S4,S5)
DataItem1
DataItem2
DataItem3
DataItem4
DataItem5.... etc

I have a sub-report 'Chart' displaying a clustered vertical barchart
'Chart' sub-report is only visible if 'View' parameter of parent report is value of ChartView(0)
'Chart' sub-report to use 'dsMain' from parent report and filtering on 'Months' and 'Statuses' and sorting by 'Date'
'Chart' is grouped on 'FormattedDate' and each series is derived for each value in 'Status', value is Count('Status')

I have a sub-report 'Grid' displaying a datagrid
'Grid' sub-report is only visible if 'View' parameter of parent report is value of GridView(1)
'Grid' sub-report to use 'dsMain' from parent report and filtering on 'Months' and 'Statuses' and sorting by 'Date'

I cannot work out how to access the data source 'dsMain' from the sub-reports.
I cannot work out how to stop the stored proc from being called whenever 'View', 'Months' or 'Status' gets changed by the user.
The key issue here is the cost of running the Stored Proc when it has all the necessary data to filter and populate the controls on either of the sub reports.
The only time the data source should be refreshed is if the 'Id' or 'Verified' parameters of the parent report is changed.
Neli
Telerik team
 answered on 13 Aug 2021
1 answer
1.1K+ views

Hi Team

We tried executing justMock test cases in command prompt using justMock Console (licensed), dotCover and xUnit, but justMock Test execution failed and gave the error "System.InvalidProgramException : Common Language Runtime detected an invalid program." 

The command we use to execute is as follows:

start /wait "" "{PATH}\JustMock\Libraries\Telerik.JustMock.Configuration.exe" /link "dotCover"

"{PATH}\JustMock\Libraries\Telerik.JustMock.Console.exe" runadvanced --profiler-path-64 "{PATH}\JustMock\Libraries\CodeWeaver\64\Telerik.CodeWeaver.Profiler.dll" --command "{PATH}\JetBrains.dotCover.CommandLineTools.2021.1.3\dotCover.exe" --command-args "cover --reporttype=html --output=CodeCoverage\\index.html --targetexecutable=\"{PATH}\xunit.runner.console.2.4.1\tools\net472\xunit.console.exe\" -- \"{PATH}\{PATH_OF_JUSTMOCK_TEST_DLL}\""

start /wait "" "{PATH}\JustMock\Libraries\Telerik.JustMock.Configuration.exe" /unlink "dotCover"

 

Attaching the log and test code.

1 answer
202 views

Hi

I have a function:

    Public Function UpdatePasswordHistory(ByVal mods As DataSource, ByVal StaffCode As String, ByVal Password As String) As Integer


        Dim strSQl As New StringBuilder("Insert into [dbo].[PasswordHistory]([StaffCode],[Password],[DateSet])")
        strSQl.Append($"values('{StaffCode}','{EncryptPassword(UCase(Password))}','{System.DateTime.Today.ToString("yyyy-MM-dd")}')")


        Return mods.SqlDB.ExecuteNonQuery(strSQl.ToString())

    End Function

 

I want to create 2 tests.

The staffcode is a foreign key so must exists.

If no issues it should return 1. else 0.

My 2 tests always return 0.

I probably done this all wrong

   public void UpdatePasswordHistory_Staffcodeexists()
        {
            // Arrange
      var mockDS = Mock.Create<DataSource>();
            clsSecurity clsSecurity = Mock.Create<clsSecurity>();

            string Staffcode = "sahmed";
            string password = "test";
            Int32 rowsaffetced = 1;
            Int32 actualRowsaffected;

            Mock.Arrange(() => clsSecurity.UpdatePasswordHistory(mockDS, Staffcode, password)).Returns(rowsaffetced);

            actualRowsaffected = new clsSecurity().UpdatePasswordHistory(mockDS, Staffcode, password);

            Assert.AreEqual(rowsaffetced,actualRowsaffected);
        }

        [TestMethod]
        public void UpdatePasswordHistory_Staffcodedoesnotexist()
        {
            // Arrange
            var mockDS = Mock.Create<DataSource>();
            clsSecurity clsSecurity = Mock.Create<clsSecurity>();

            string Staffcode = "InvalidUser";
            string password = "test";
            Int32 rowsaffetced = 0;
            Int32 actualRowsaffected;

            Mock.Arrange(() => clsSecurity.UpdatePasswordHistory(mockDS, Staffcode, password)).Returns(rowsaffetced);

            actualRowsaffected = new clsSecurity().UpdatePasswordHistory(mockDS, Staffcode, password);

            Assert.AreEqual(rowsaffetced, actualRowsaffected);
        }

 

Ivo
Telerik team
 answered on 15 Jun 2021
1 answer
200 views

Over the weekend Visual Studio was upgraded to 16.10.0 on our self-hosted Azure DevOps agent server. This has caused all of our unit tests that rely on the JustMock profiler to begin failing with the Exception:

Failed {METHODNAME} [6 ms]
  Error Message:
   Test method {NAMESPACE}.{CLASSNAME}.{METHODNAME} threw exception: 
System.InvalidProgramException: Common Language Runtime detected an invalid program.
  Stack Trace:
      at {NAMESPACE}.{CLASSNAME}.{METHODNAME}()
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[TStateMachine](TStateMachine& stateMachine)
   at {NAMESPACE}.{CLASSNAME}.{METHODNAME}()

We are using JustMock R2 2021, the Telerik JustMock VSTest v.2 (v2.6.1) pipeline task, and our test projects are targeting netcore3.1.

The tests run and pass when executed locally through Visual Studio (16.10.0) Test Explorer, but fail during pipeline execution. Nothing else has changed on the agent server except for the Visual Studio upgrade that I am aware of.

Pipeline YAML:

jobBuildAndPublishWebsite_${{ parameters.jobName }}
  displayName'Build and Publish Website - ${{ parameters.jobName }}'
  steps:
    - checkoutself
      cleantrue
      fetchDepth10
    - taskDotNetCoreCLI@2
      displayName'dotnet restore'
      inputs:
        commandrestore
        projects'**/*.csproj'
        vstsFeed${{ parameters.vstsFeedId }}
    - taskDotNetCoreCLI@2
      displayName'dotnet build'
      inputs:
        projects'**/*.csproj'
        arguments'--no-restore --nologo --configuration ${{ parameters.buildConfiguration }}'
taskJustMockVSTest@2
      displayName'Run Unit Tests'
      inputs:
        testAssemblyVer2: |
          **\*tests*.dll
          **\*Tests*.dll
          !**\*TestAdapter.dll
          !**\obj\**
          !**\packages\**
        pathTo64BitJustMockProfiler'$(System.DefaultWorkingDirectory)\lib\Telerik\JustMock\CodeWeaver\64\Telerik.CodeWeaver.Profiler.dll'
        pathTo32BitJustMockProfiler'$(System.DefaultWorkingDirectory)\lib\Telerik\JustMock\CodeWeaver\32\Telerik.CodeWeaver.Profiler.dll'
        vsTestVersionlatest
        runInParalleltrue
        codeCoverageEnabledtrue

 

Mihail
Telerik team
 answered on 04 Jun 2021
1 answer
462 views

I am new to JustMock, I try to use it in .NET5 but failed, I have seen some articles related to this kind of problem but I failed to resolve it. At the same time, I use MOQ for this project, I have tried TypeMock before but have already uninstalled.

Message: 
    Test method  threw exception: 
    Telerik.JustMock.Core.ElevatedMockingException: Cannot mock 'BitCoinLib.Database.Connection'. 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.InterceptStatics(Type type, MockCreationSettings settings, Boolean mockStaticConstructor)
    <>c__DisplayClass67_0.<SetupStatic>b__0()
    ProfilerInterceptor.GuardInternal(Action guardedAction)
    Mock.SetupStatic(Type staticType, StaticConstructor staticConstructor)

 
Ivo
Telerik team
 answered on 10 May 2021
Narrow your results
Selected tags
Tags
+? more
Top users last month
Dominik
Top achievements
Rank 1
Giuliano
Top achievements
Rank 1
Dominic
Top achievements
Rank 1
Glendys
Top achievements
Rank 1
Iron
NoobMaster
Top achievements
Rank 2
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Dominik
Top achievements
Rank 1
Giuliano
Top achievements
Rank 1
Dominic
Top achievements
Rank 1
Glendys
Top achievements
Rank 1
Iron
NoobMaster
Top achievements
Rank 2
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?