Telerik Forums
JustMock Forum
5 answers
319 views

Hi,

I'm using JustMock to mock SharePoint objects in some Unit Tests. When I run Unit Tests (I use ReSharper as test runner) and the JustMock profiler is enabled, the unit tests are much slower. Normally, one Unit test runs within seconds. With the JustMock profiler enabled, I have to wait several minutes. Is there something I can do to accelerate this?

 

Thank you very much!

 

Mihail
Telerik team
 answered on 12 Jun 2020
9 answers
2.9K+ views
I have the following in a test (my first ever JustMock test, I might add)...

var template = Mock.Create<MessageType>
Mock.Arrange(() => template.Subject).Returns("This template has Zero tokens.");
Mock.Arrange(() => template.Body).Returns("This template has {{number}} of {{tokens}}.");


The class being Mocked looks like this ...

public class MessageType : BaseBusinessEntity
{
    public string Body { get; set;}
    public int DigestsToBeIncludedOn { get; set; }
    public Guid MessageReference { get; set; }
    public int MessageTypeId { get; set; }
    public string Name { get; set; }
    public int PredefinedRecipients { get; set; }
    public string Subject { get; set; }
}

When I attempt to run the test I get ...

> Error Message: Test method
> Genesis.Service.Implementation.Tests.DigestFixture.ShouldCorrectlyExtractTemplateTokens
> threw exception:  Telerik.JustMock.Core.ElevatedMockingException:
> Cannot mock 'System.String get_Subject()'. The profiler must be
> enabled to mock, arrange or execute the specified target. Stacktrace: 
> at
> Telerik.JustMock.Core.ProfilerInterceptor.ThrowElevatedMockingException(MemberInfo
> member)  at
> Telerik.JustMock.Core.MocksRepository.CheckMethodInterceptorAvailable(IMatcher
> instanceMatcher, MethodBase method)  at
> Telerik.JustMock.Core.MocksRepository.AddArrange(IMethodMock
> methodMock)  at
> Telerik.JustMock.Core.MocksRepository.Arrange[TMethodMock](Expression
> expr, Func`1 methodMockFactory)  at
> Telerik.JustMock.Mock.<>c__DisplayClass8`1.<Arrange>b__6()  at
> Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal[T](Func`1
> guardedAction)  at Telerik.JustMock.Mock.Arrange[TResult](Expression`1
> expression)  at
> Genesis.Service.Implementation.Tests.DigestFixture.ShouldCorrectlyExtractTemplateTokens()
> in
> c:\Genesis\Development\Genesis.Service.Implementation.Tests\DigestFixture.cs:line
> 46

Can anyone point out what I've done wrong?
Rafael
Top achievements
Rank 2
 answered on 18 May 2020
5 answers
553 views

I put out a question on stackoverflow, but did not get any response. So let me link it here: https://stackoverflow.com/questions/61074264/how-can-i-mock-multiple-instances-of-a-struct

For convenience a copy of the text:

 

I have a `struct` that I want to mock. In a more complex test I need several instances of this struct, each with it's own behavior. To facilitate this, I've created a helper method.

    private MyStruct CreateMock(string toString) {
        var mock = Mock.Create<MyStruct>();
        Mock.Arrange(() => mock.toString()).Returns(toString);
        return mock;
    }

When I debug a test where this method is called multiple times, it appears as if the `Arrange` call is overwritten for ALL instances of the struct (or maybe I am using struct mocking instead of instance mocking?). 

I've tried:

    mock.Arrange(m => m.toString()).Returns(toString); // Using Helpers assembly, note the lowercase m at the start of the line.

But to no avail. How can I get multiple instances of a struct?

I'm using: 
Microsoft Visual Studio Enterprise 2017 
Version 15.9.17
VisualStudio.15.Release/15.9.17+28307.905
Microsoft .NET Framework
Version 4.8.03761

Installed Version: Enterprise

JustMock   2020.1.219.1
Telerik JustMock Extension.

**Example added**:
```
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
using Telerik.JustMock.Helpers;

namespace JustMockFramework
{
    public struct MyStruct
    {
        public readonly string Id;

        public MyStruct(string id)
        {
            Id = id;
        }

        public new string ToString()
        {
            return "Never read me!";
        }
    }

    [TestClass]
    public class MWE
    {
        [TestMethod]
        public void TestSimpleStruct()
        {
            var simpleTest = new MyStruct("1");

            Assert.AreEqual("Never read me!", simpleTest.ToString());
        }

        [TestMethod]
        public void TestMockOfStruct()
        {
            var mock = Mock.Create<MyStruct>();
            Mock.Arrange(() => mock.ToString()).Returns("Read me!");

            Assert.AreEqual("Read me!", mock.ToString());
        }

        [TestMethod]
        public void TestTwoMocksOfStruct()
        {
            var firstMock = Mock.Create<MyStruct>();
            Mock.Arrange(() => firstMock.ToString()).Returns("Read me!");

            var secondMock = Mock.Create<MyStruct>();
            Mock.Arrange(() => secondMock.ToString()).Returns("Read me too!");

            Assert.AreEqual("Read me!", firstMock.ToString()); // Fails with "Read me too!"
            Assert.AreEqual("Read me too!", secondMock.ToString());
        }

        [TestMethod]
        public void TestTwoMocksOfStructCreatedInHelper()
        {
            var firstMock = CreateMockOfStruct("Read me!");

            var secondMock = CreateMockOfStruct("Read me too!");

            Assert.AreEqual("Read me!", firstMock.ToString()); // Fails with "Read me too!"
            Assert.AreEqual("Read me too!", secondMock.ToString());
        }

        private MyStruct CreateMockOfStruct(string toString)
        {
            var mock = Mock.Create<MyStruct>();
            Mock.Arrange(() => mock.ToString()).Returns(toString);
            return mock;
        }

        [TestMethod]
        public void TestTwoMocksOfStructCreatedInHelperWithHelper()
        {
            var firstMock = CreateMockOfStructWithHelper("Read me!");

            var secondMock = CreateMockOfStructWithHelper("Read me too!");

            Assert.AreEqual("Read me!", firstMock.ToString()); // Fails with "Read me too!"
            Assert.AreEqual("Read me too!", secondMock.ToString());
        }

        private MyStruct CreateMockOfStructWithHelper(string toString)
        {
            var mock = Mock.Create<MyStruct>();
            mock.Arrange((m) => m.ToString()).Returns(toString);
            return mock;
        }
    }
}
```

 

Ivo
Telerik team
 answered on 23 Apr 2020
5 answers
375 views
I am trying Arrange a  base class method which is override in drive class but I can`t

Here is my Code :

 public class Class1 : Class2
    {
        public bool Class1Call { get; set; }

        public override void Method1()
        {
            Class1Call = true;
           base.Method1();      //<<<<< want to ensure that base.Method1 ic call during Method1 call
        }
    }

    public class Class2
    {
        public bool IsCall { get; set; }

        public virtual void Method1()
        {
            IsCall = true;
        }
    }


    public class TestClass
    {
        [Fact]
        public void Class_1_Test()
        {
            var foo = Mock.Create<Class1>();
            Mock.Arrange(() => (foo as Class2).Method1()).CallOriginal().OccursOnce();
            Mock.Arrange(() => foo.Method1()).CallOriginal().OccursOnce();

            foo.Method1();

            Mock.Assert(foo);

            Assert.True(foo.IsCall);

        }
    } 
Ivo
Telerik team
 answered on 04 Mar 2020
2 answers
94 views

hi mate, I was wondering if it is possible to mock the following case.

 

from school in dbContext.Schools

join student in dbContext.Students

   on school.id equals student.schoolId into students

let firstStudent = students.FirstOrDefault()

select firstStudent.Name;

 

When all the tables are empty and there is no school and no student in the tables, a real sql execution just returns an empty object of IEnuemrable<string> type. If I mock 'dbContext.Schools' and 'dbContext.Students', 'firstStudent.Name' throws a null exception because 'firstStudent' is null.

Is there a way to conditionally mock only in this context of linq to sql so that we can bypass the null exception and get the mocked execution to run smoothly?

Ivo
Telerik team
 answered on 04 Mar 2020
1 answer
76 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
1 answer
123 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
7 answers
744 views

Hello,

We're encountering the following type of error on our build servers:

  X SendFile_GivenValidInformation_ShouldReturnSuccessResult [1ms]
  Error Message:
   Initialization method InsuranceApiLibrary.Syncronizers.<<redacted>>Tests.Setup threw exception. Telerik.JustMock.Core.ElevatedMockingException: Cannot mock '<<redacted>>SoapClient'. The profiler must be enabled to mock, arrange or execute the specified target.
Detected active third-party profilers:
* C:\Users\<<redacted-tfs-agent-service>>\.nuget\packages\microsoft.codecoverage\16.4.0\build\netstandard1.0\CodeCoverage\amd64\covrun64.dll (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:
      at Telerik.JustMock.Core.ProfilerInterceptor.ThrowElevatedMockingException(MemberInfo member)
   at Telerik.JustMock.Core.MocksRepository.Create(Type type, MockCreationSettings settings)
   at Telerik.JustMock.Mock.<>c__DisplayClass47_0`1.<Create>b__0()
   at Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal[T](Func`1 guardedAction)
   at Telerik.JustMock.Mock.Create[T](Object[] args)
   at InsuranceApiLibrary.Syncronizers.<<redacted>>Tests.Setup() in E:\AzDOS\Agents\Alpha\_work\8\s\<<redacted>>\<<redacted>>Test\Syncronizers\<<redacted>>Tests.cs:line 27

When we exclude code coverage, we get very similar errors, but without the lines about detected third-party active profilers.  I have directly verified that the JM profiler settings are correct (see attached images).

Our build servers have Visual Studio Enterprise 2019 16.4.2, .NET Core SDK 3.1.100, and JustMock 2020.1.113.1 installed.  The C# projects in question target .NET Core 3.1.  The path to the JM DLL being referenced by those projects is "C:\Program Files (x86)\Progress\Telerik JustMock\Libraries\netcoreapp2.0\Telerik.JustMock.dll".  I can find no obvious alternative path or DLL for .NET Core 3.x, so I assume that DLL applies to multiple .NET Core major versions.

This problem is blocking new initiatives.  Thanks in advance for any assistance you can provide.

Regards,
Tom Slavens
Platform Configuration Architect, Software Services
Veterans United Home Loans

 

Ivo
Telerik team
 answered on 23 Jan 2020
5 answers
83 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
10 answers
3.8K+ 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
Narrow your results
Selected tags
Tags
+? more
Top users last month
Mark
Top achievements
Rank 1
Yurii
Top achievements
Rank 1
Leland
Top achievements
Rank 2
Iron
Iron
Iron
Hon
Top achievements
Rank 1
Iron
Deltaohm
Top achievements
Rank 3
Bronze
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Mark
Top achievements
Rank 1
Yurii
Top achievements
Rank 1
Leland
Top achievements
Rank 2
Iron
Iron
Iron
Hon
Top achievements
Rank 1
Iron
Deltaohm
Top achievements
Rank 3
Bronze
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?