Telerik Forums
JustMock Forum
10 answers
2.3K+ views

I am trying to create a new .NET Core project and I am having issues using any JustMock functions/keywords. I have installed the latest available installer (JustMock.2019.1.207.1), we use JustMock in our other projects without any issues but these are all .NET 4.5. I would prefer to use the MSTest project as that is what the other projects use also and would like to keep things consistent. I have also tried creating a new NUnit and XUnit project but keep getting the same error. Solution builds without errors or warnings.

 

My Test Method only has one line in it for arranging, it's trying to mock the service. Here is the code:

var context = Mock.Create<IFileService>();

Here is the error I am getting:
Test method MSTestProject.LayoutControllerTest.FileController_TestCalls threw exception: 
System.TypeInitializationException: The type initializer for 'Telerik.JustMock.Core.ProfilerInterceptor' threw an exception. ---> System.MissingMethodException: Method not found: 'System.Reflection.Emit.AssemblyBuilder System.AppDomain.DefineDynamicAssembly(System.Reflection.AssemblyName, System.Reflection.Emit.AssemblyBuilderAccess)'.

StackTrace: 

at Telerik.JustMock.Core.Castle.DynamicProxy.ModuleScope.CreateModule(Boolean signStrongName)
   at Telerik.JustMock.Core.Castle.DynamicProxy.ModuleScope.ObtainDynamicModuleWithStrongName()
   at Telerik.JustMock.Core.MockingUtil.get_ModuleBuilder()
   at Telerik.JustMock.Core.MockingUtil.CreateDynamicMethodWithVisibilityChecks(Type returnType, Type[] parameterTypes, Action`1 ilGen)
   at Telerik.JustMock.Core.ProfilerInterceptor.CreateFieldAssignmentExpression(FieldInfo assignee, ParameterExpression valueParam)
   at Telerik.JustMock.Core.ProfilerInterceptor.InitializeFieldAccessors[TFieldType](String fieldName, Func`1& getter, Action`1& setter)
   at Telerik.JustMock.Core.ProfilerInterceptor..cctor()
--- End of inner exception stack trace ---
    at Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal(Action guardedAction)
   at MSTestProject.LayoutControllerTest.FileController_TestCalls() in C:\Repos\LTA-TelerikUIDotNetCore\MSTestProject\LayoutControllerTest.cs:line 33

 

Ivo
Telerik team
 answered on 19 Nov 2019
3 answers
67 views

I have a complex legacy application that I'm not allowed to refactor.   I am trying to write tests and don't want to repeat the same set up multiple times. I created a helper class which holds the mocks (TargetMocks) with methods to set up most of the logging arrange statements so I could focus the test on a specific aspect of the system under test.

I've created an example NUnit test with a sample set of classes and Interfaces.   All but one of the tests work and I don't understand why the failing test fails. It has the same exact Mock.Arrange statements that are executed in the same order.   The only difference is the failing test has the Mock.Arrange statements in the test method while the working test has the Mock.Arrange methods in the TestMocks helper class.

public class TargetMocks
{
    public ILogger Logger { get; } = Mock.Create<ILogger>();
    public IUtility Util { get; } = Mock.Create<IUtility>();
    public StringBuilder LoggerBuilder {get;} = new StringBuilder();
    public void SetupMocks()
    {
        Mock.Arrange(() => Logger.Info(Arg.AnyString))
            .DoInstead((string msg) =>
            {
                LoggerBuilder.AppendLine(msg);
            });
    }
    public Target CreateTarget()
    {
        var sut = new Target();
        Mock.Arrange(() => sut.Logger).Returns(Logger);
        Mock.Arrange(() => sut.Util).Returns(Util);
        return sut;
    }
    public Target CreateTargetAndSetupUtil()
    {
        var sut = new Target();
        Mock.Arrange(() => sut.Logger).Returns(Logger);
        Mock.Arrange(() => sut.Util).Returns(Util);
        //Mock.Arrange(() => mock.Util.ChangeState(Arg.AnyInt, Arg.AnyString)).MustBeCalled();
        Mock.Arrange(() => Util.SaveState(Arg.AnyInt, Arg.AnyString)).MustBeCalled();
 
        return sut;
    }
}

 

The following test fails

[Test()]
public void x3TestWidgetProcessUtilMethods_Test_TestUsesSeperateClassMocksAndCreatesSUT_But_Fails()
{
    var expectedLog =
        "target message 1\r\n" +
        "Message 1\r\n" +
        "Message 3\r\n" +
        "target message 3\r\n";
 
    var mock = new TargetMocks();
    mock.SetupMocks();
    var sut = mock.CreateTarget();
    Mock.Arrange(() => mock.Util.ChangeState(Arg.AnyInt, Arg.AnyString)).MustBeCalled();
    Mock.Arrange(() => mock.Util.SaveState(Arg.AnyInt, Arg.AnyString)).MustBeCalled();
 
    sut.Process();
 
    var log = mock.LoggerBuilder.ToString();
 
    Assert.AreEqual(expectedLog, log, log);
    Mock.Assert(mock.Util);
}

 

But this test works.

[Test()]
public void x3aTestWidgetProcessUtilMethods_Test_TestUsesSeperateClassMocksAndCreatesSUTAndSetsUpUtilMock_WorksAsExpected()
{
    var expectedLog =
        "target message 1\r\n" +
        "Message 1\r\n" +
        "Message 3\r\n" +
        "target message 3\r\n";
 
    var mock = new TargetMocks();
    mock.SetupMocks();
    var sut = mock.CreateTargetAndSetupUtil();
 
    sut.Process();
 
    var log = mock.LoggerBuilder.ToString();
 
    Assert.AreEqual(expectedLog, log, log);
    Mock.Assert(mock.Util);
}

 

  • Why does the first test fail?

 

 

Ivo
Telerik team
 answered on 24 Oct 2019
2 answers
60 views

I have yet to be able to run my unit tests within my pipeline.

I have installed Telerik JustMock Tests v.2 and I have configured the  profiler paths as described (those paths have been verified to contain the dlls)

 

pathTo64BitJustMockProfiler: '$(System.DefaultWorkingDirectory)/Solution Items/External assemblies/Telerik.JustMock/64/Telerik.CodeWeaver.Profiler.dll'

pathTo32BitJustMockProfiler: '$(System.DefaultWorkingDirectory)/Solution Items/External assemblies/Telerik.JustMock/32/Telerik.CodeWeaver.Profiler.dll'

 

Yet when I run my tests I get this error: Telerik.JustMock.Core.ElevatedMockingException: Cannot mock '...'. The profiler must be enabled to mock, arrange or execute the specified target.

 

On our old build server the same dlls are working fine but not in Azure. Is there a way to get this working?

Allan
Top achievements
Rank 1
 answered on 27 Sep 2019
1 answer
50 views

I am having a lot of trouble understanding the behaviour of static mocking. I have a static class with two static functions, each of which returns a string, I have a test class whose constructor calls both functions on the static class, and I have a set of tests that arrange only one of the static functions, and which call SetupStatic in various ways. The results are as follows:

1. SetupStatic is not called at all: the arranged function uses the mock arrangement and gets the arranged return value, the other function calls the original - as expected;

2. SetupStatic(MyType, Behavior.Strict) is called: the arranged function uses the mock arrangement and gets the arranged return value, the other function throws a "Called unarranged member on strict mock" exception - as expected;

3. SetupStatic(MyType) is called (ie. default Behavior): the arranged function uses the mock arrangement and gets the arranged return value, the other function does not call the original and gets an empty string as the return value - unexpected;

4. SetupStatic(MyType, Behaviour.Loose) is called: the arranged function uses the mock arrangement and gets the arranged return value, the other function does not call the original and gets null as the return value - doubly unexpected as the documented default value of Behavior is Loose;

5. SetupStatic(MyType, Behaviour.RecursiveLoose) is called: the arranged function uses the mock arrangement and gets the arranged return value, the other function does not call the original and gets an empty string as the return value - unexpected;

6. SetupStatic(MyType, Behavior.CallOriginal) is called: the arranged function uses the mock arrangement and gets the arranged return value, the other function calls the original - I'm not sure what I would expect for this;

I am using JustMock version R2 2019 SP1.

I would be grateful if someone could tell me if this is working correctly, and what the logic is behind this behaviour.

Thanks

Mihail
Telerik team
 answered on 26 Aug 2019
1 answer
69 views

I'm running into a situation where I need to enable the profiler however I do NOT have the ability to just open visual studio and click on a profiler choice, as I'm trying to get things to build on a headless build slave which runs as "nt authority\system."

This slave also had some churn on it in terms of having to reinstall visual studio 2015 enterprise (after installing JustMock)?

Currently I'm running Visual Studio 2015 update 3 

Just Mock is version 2015.2.715.1

I also have a diagnostic script to see if the various environment variables are properly set based off some other searches:
write-host "COR_ENABLE_PROFILING: $($env:COR_ENABLE_PROFILING)"
write-host "JUSTMOCK_INSTANCE: $($env:JUSTMOCK_INSTANCE)"
write-host "COR_PROFILER: $($env:COR_PROFILER)"
whoami
When I run this on my build slave it presents me with:
COR_ENABLE_PROFILING: 1
JUSTMOCK_INSTANCE: 1
COR_PROFILER: {B7ABE522-A68F-44F2-925B-81E7488E9EC0}
nt authority\system

Mihail
Telerik team
 answered on 20 Aug 2019
9 answers
357 views

I've recently upgraded to VS2019 and JustMock 2019.508.1 (we have a DevCraft license), and tests requiring elevated mode are no longer functioning. We receive the following error when only linking the VS 2019 Profiler with JustMock:

Telerik.JustMock.Core.ElevatedMockingException: Telerik.JustMock.Core.ElevatedMockingException: Cannot mock 'EL.BusinessLayer.LegacyTaskCloseRequestEntity PostRentScheduleEntitiesToLegacy(EL.BusinessLayer.LegacyTaskCloseRequestEntity, System.String, System.String, System.String, System.String, System.Collections.Generic.ICollection`1[System.String])'. The profiler must be enabled to mock, arrange or execute the specified target.
Detected active third-party profilers:
* {9317ae81-bcd8-47b7-aaa1-a28062e41c71} (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..

That guid refers to the VS Code Coverage profiler, which does appear in the Telerik JustMock Configuration profiler list. However, when I select that profiler then the tests will no longer even start - the progress bar will display its green runner going from left to right, but none of the tests will ever start spinning and after a minute or two the progress bar just stops without displaying any errors or messages.

We had also started .NET Core development in VS2017, and had found that we needed to add dotnet.exe to the Codeweaver ImageBlacklist.cfg file. The behavior we are seeing with tests not ever starting to run reminds me of that behavior with dotnet.exe, and I'm wondering if there is a new VS2019 executable for testing that needs to be added to that blacklist file?

Mihail
Telerik team
 answered on 20 Aug 2019
2 answers
41 views

I have a problem when trying to use a DoInstead of a method that returns an enum value.

The mocked function is indeed called as expected. However, the return value (an enum) is not returned correctly. Instead it always returns the first value of the enum.

Using Progress Telerik.JustMock 2019.2.620.1 (with license).

Here is a way to reproduce it (Console application, VS2017, Link to Telerik.JustMock dll):

 

namespace TelerikJustMockBug
{
    using System;
    using Telerik.JustMock;
 
    class Program
    {
        delegate CompletionCode MockedReadWriteDelegate(byte[] buffer, int count, out int retCount);
 
        static void Main(string[] args)
        {
            new Program().Run();
        }
 
        private void Run()
        {
            ClassToMock session = Mock.Create<ClassToMock>();
 
            Mock.Arrange(() => new ClassToMock()).Returns(session);
 
            Mock.Arrange(() => session.Read(Arg.IsAny<byte[]>(), Arg.AnyInt, out Arg.Ref(Arg.AnyInt).Value)).DoInstead(new MockedReadWriteDelegate(this.MockedRead));
 
            ClassToMock c = new ClassToMock();
            CompletionCode result = c.Read(new byte[2], 2, out int retCount);
 
            if (retCount != 5)
            {
                throw new Exception("retCount was not set correctly");
            }
 
            if (result != CompletionCode.NOT_SUCCESS)
            {
                // this exception is thrown in my case with 'Wrong result: 0'
                throw new Exception($"Wrong result: {result.ToString()}");
            }
        }
 
        private CompletionCode MockedRead(byte[] buffer, int count, out int retCount)
        {
            retCount = 5;
            return CompletionCode.NOT_SUCCESS;
        }
 
        public enum CompletionCode
        {
            SUCCESS = 1,
            NOT_SUCCESS = 2
        }
 
        public class ClassToMock
        {
            public CompletionCode Read(byte[] buffer, int count, out int retCount)
            {
                throw new Exception("Real implementation - should never be called due to mocking");
            }
        }
    }
}
Ivo
Telerik team
 answered on 08 Aug 2019
4 answers
340 views

Hi guys,

I need to test the handler of a Timer in one class. I'm using Future Mocking to mock the Timer inside it.
Is there some way in order to invoke the callback?

Here my class to test:

 

internal class DatabaseCleaner
{
 
      private Timer mobjTimer = null;
 
      internal void Start()
      {
 
            mobjTimer = new Timer(CleanDB, null, 5000, 1000 * 60 * 10);
      }
 
      internal void Stop()
      {
         if (mobjTimer != null)
         {
            mobjTimer.Dispose();
            mobjTimer = null;
         }
      }
 
      private void CleanDB(object state)
      {

       // do stuff to test

        }
}


Thanks a lot.

Stefano

Ivo
Telerik team
 answered on 25 Jun 2019
3 answers
295 views

Hi,

 

I'd like to test the implementation of the my abstract class, but I'm not able to intercept the constructor of the base class.

Here the snippet code:

 

public abstract class Base
{
    public virtual void Start(IContext context)
    {
         \\ do something
    }
}
public class Child : Base
{
    public override void Start(IContext context)
    {
         \\ do something
    }
}

 

I'd like to test it like this:

private Base mBase;
private Child mPlugin;
 
[TestInitialize]
public void Initialize()
{
   mBase = Mock.Create<Base>(Constructor.Mocked);
   mPlugin = new Child();
}
 
[TestMethod]
public void TestStart()
{
    IContext mockContext = Mock.Create<IContext>();
    Mock.Arrange(() => mBase.Start(mockContext)).DoNothing();
     
    // test plugin code
     
    mPlugin.Start(mockContext);
}

 

What is wrong?

 

Thanks,

Ste

 

Mihail
Telerik team
 answered on 10 Jun 2019
2 answers
22 views
Instance creation timed out and aborted 
Lyubomir Rusev
Telerik team
 answered on 28 May 2019
Narrow your results
Selected tags
Tags
+? more
Top users last month
WEI TZE
Top achievements
Rank 1
CHIHPEI
Top achievements
Rank 2
Iron
Iron
Iron
Rob
Top achievements
Rank 1
Iron
Jerry
Top achievements
Rank 1
Iron
Iron
Iron
Sami
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
WEI TZE
Top achievements
Rank 1
CHIHPEI
Top achievements
Rank 2
Iron
Iron
Iron
Rob
Top achievements
Rank 1
Iron
Jerry
Top achievements
Rank 1
Iron
Iron
Iron
Sami
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?