Telerik Forums
JustMock Forum
1 answer
219 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
213 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
482 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
3 answers
3.2K+ views
I'm new to JustMock and Unit Testing in general.

I have a method WriteToDisk(object param) that creates a new FileStream, calls FileStream.Write, then sets a bool property in the class to true. I'd like to test that the property is set to true (if no exceptions are thrown) without actually writing to disk.

I'm just not sure how to arrange things in my test to bypass the Filestream instance and the call to FileStream.Write. Can this even be done with JM?
Ivo
Telerik team
 answered on 12 Feb 2021
4 answers
331 views

Hi,

I have been using Justmock for years now without any problem. But lately we started running as our normal users and not as local administrators on our PC's.

When installing Justmock I'm using an elevated admin account and it seems to complete without any errors, afterwards I'm starting VS19 as my normal user and are presented with the dialog shown in the attached file.

The log shows that the assembly could not be found or loaded, when looking in the folder specified in the error, I do not have an <extensions> folder at the location. So I assume that installing the product with my administrator access does not work for my normal user, what to do? 

The activity log shows the following error:

690 ERROR CreateInstance failed for package [JustMockPackage]Source: 'mscorlib' Description: Filen eller assemblyen 'file:///c:\users\foobar\appdata\local\microsoft\visualstudio\16.0_4cd0081b\extensions\alz4b0wd.jii\Telerik.JustMock.VS2017.dll' eller en af dens afhængigheder kunne ikke indlæses. Den angivne fil blev ikke fundet. System.IO.FileNotFoundException: Filen eller assemblyen 'file:///c:\users\foobar\appdata\local\microsoft\visualstudio\16.0_4cd0081b\extensions\alz4b0wd.jii\Telerik.JustMock.VS2017.dll' eller en af dens afhængigheder kunne ikke indlæses. Den angivne fil blev ikke fundet. File name: 'file:///c:\users\foobar\appdata\local\microsoft\visualstudio\16.0_4cd0081b\extensions\alz4b0wd.jii\Telerik.JustMock.VS2017.dll'at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)at System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark)at System.Reflection.Assembly.LoadFrom(String assemblyFile, Evidence securityEvidence)at System.Activator.CreateInstanceFromInternal(String assemblyFile, String typeName, Boolean ignoreCase, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, Evidence securityInfo)at System.AppDomain.CreateInstanceFrom(String assemblyFile, String typeName) WRN: Logføring af assemblybinding er deaktiveret. Logføring af assemblybindingsfejl aktiveres ved at angive registreringsdatabaseværdien [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) til 1. Bemærk! Ydeevnen forringes ved logføring af assemblybindingsfejl. Denne funktion deaktiveres ved at fjerne registreringsdatabaseværdien [HKLM\Software\Microsoft\Fusion!EnableLog].  {0A72E70C-4C0C-4EF0-8212-59ACF681F885} 80004005 - E_FAIL VisualStudio 2020/11/05 06:41:35.043 

 

Mihail
Telerik team
 answered on 23 Nov 2020
1 answer
248 views

Hello!

I have an interesting problem I am trying to solve unit testing Sitecore. I have wrapped myController to get to a dynamic accessor and I am getting an exception way down in the mscorplib System.DefaultBinder. Looking for leads on what I am missing on my setup?

Exception: 

System.ArgumentException: Array may not be empty.
Parameter name: match

 

Code:

    var controllerAccessor = Mock.NonPublic.Wrap(_myController);

 

    Mock.NonPublic.Arrange<IMyParameters>(controllerAccessor.GetRenderingParameters<IMyParameters>()).Returns(_myParameters);

 

Stack trace:

   at System.DefaultBinder.BindToMethod(BindingFlags bindingAttr, MethodBase[] match, Object[]& args, ParameterModifier[] modifiers, CultureInfo cultureInfo, String[] names, Object& state)
   at Telerik.JustMock.Core.MockingUtil.BindToMethod(BindingFlags bindingAttr, MethodBase[] match, Object[]& args, ParameterModifier[] modifiers, CultureInfo culture, String[] names, Object& state)
   at Telerik.JustMock.PrivateAccessor.ResolveProperty(Type type, String name, Boolean ignoreCase, Object[] indexArgs, Boolean hasInstance, Object setterValue, Boolean getter)
   at Telerik.JustMock.Expectations.DynaMock.ExpressionRecorder.DoBindGetMember(Type returnType, String memberName, Boolean ignoreCase)
   at Telerik.JustMock.Expectations.DynaMock.ExpressionRecorder.BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args)
   at System.Dynamic.InvokeMemberBinder.Bind(DynamicMetaObject target, DynamicMetaObject[] args)
   at System.Dynamic.DynamicMetaObjectBinder.Bind(Object[] args, ReadOnlyCollection`1 parameters, LabelTarget returnLabel)
   at System.Runtime.CompilerServices.CallSiteBinder.BindCore[T](CallSite`1 site, Object[] args)
   at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)

at <my code line Mock.NonPublic.Arrange<IMyParameters>(controllerAccessor.GetRenderingParameters<IMyParameters>()).Returns(_myParameters)> 

 

System.DefaultBinder code snippet:

// Decompiled with JetBrains decompiler
// Type: System.DefaultBinder
// Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// MVID: CACD6C6A-C61D-45CD-B58B-92E86EE53F52
// Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\mscorlib.dll

using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;

namespace System
{
  [Serializable]
  internal class DefaultBinder : Binder
  {
    [SecuritySafeCritical]
    public override MethodBase BindToMethod(
      BindingFlags bindingAttr,
      MethodBase[] match,
      ref object[] args,
      ParameterModifier[] modifiers,
      CultureInfo cultureInfo,
      string[] names,
      out object state)
    {
      MethodBase[] methodBaseArray = match != null && match.Length != 0 ? (MethodBase[]) match.Clone() : throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), nameof (match));

etc etc 

}

Ivo
Telerik team
 answered on 20 Nov 2020
4 answers
229 views
Is there a way to mock non virtual public/protected methods? I see it's possible for private but not for protected and public.
Ivo
Telerik team
 answered on 16 Nov 2020
7 answers
1.4K+ views
In a couple of my tests, I want to prove that the calling code can handle a null being returned, but whenever I tell the Returns method to return null, I get an instance of the returned type.

So for example lets says I have a method signature like:

public interface ExampleInterface
{
IList<IBob> GetMeAllTheBobs(ISomeParameter someParameter)
}

When I mock like so:

var stubExampleClass = Mock.Create<IExampleClass>();
Mock.Arrange(() => stubExampleClass.GetMeAllThyeBobs(Arg.Any<ISomeParameter>()).Returns(null);

I will get an instance of IList<IBob> back instead of null.

Any suggestions?
Ivo
Telerik team
 answered on 06 Oct 2020
3 answers
308 views
Visual Studio Professional 2019 16.6.5
JustMock 2020.2.616.1
.Net Core 3.1

How can I mock an interface with default implementations? The following test fails:

using Telerik.JustMock;
using Xunit;
 
namespace XUnitTestProject1
{
    public interface IMyInterface
    {
        bool SomeCheck() => false;
    }
 
    public class UnitTest1
    {
        [Fact]
        public void Test1()
        {
            var mock = Mock.Create<IMyInterface>();
            Mock.Arrange(() => mock.SomeCheck()).Returns(true);
 
            Assert.True(mock.SomeCheck());
        }
    }
}

Ivo
Telerik team
 answered on 21 Sep 2020
2 answers
175 views
Was looking for ways to pull the lambda expressions I mock up....this way I could reuse them during the assertion portion of my test.

However when I pass the value in via a variable I get a test exception:
Telerik.JustMock.Core.MockException: The arranged function is not set up to return a value of type Account


Here is a sanitized version of what I'm trying to do?


public Interface IAccountManagement{
   public Account GetAccount(string acctId);
}
........

public void MyTest()
{
   IAccountManagement actMgrMock = Mock.Create<IAccountManagement>();
   Account acct = TestHelpers.AutoGenerateAccount;  //generate an acct object with Ploeh.AutoFixture

   Expression<Action> GetAccount = () => actMgrMock.GetAccount(Arg.IsAny<string>());

  //Mock.Arrange(GetAccount).Returns(e);   //<------this call will not work when I invoke the test?

  Mock.Arrange(() => actMgrMock.GetAccount(Arg.IsAny<string>())).Returns(e); //  This one works?

  // invoke
  
  //Assert
  //Mock.Assert(GetAccount,Occurs.Once());

}
  


Ivo
Telerik team
 answered on 21 Sep 2020
Narrow your results
Selected tags
Tags
+? more
Top users last month
Patrick
Top achievements
Rank 1
Iron
Iron
Iron
MIS
Top achievements
Rank 1
Ross
Top achievements
Rank 1
Marcin
Top achievements
Rank 1
Iron
Iron
Sean
Top achievements
Rank 2
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Patrick
Top achievements
Rank 1
Iron
Iron
Iron
MIS
Top achievements
Rank 1
Ross
Top achievements
Rank 1
Marcin
Top achievements
Rank 1
Iron
Iron
Sean
Top achievements
Rank 2
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?