Telerik Forums
JustMock Forum
5 answers
25 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
50 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
17 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
11 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
12 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
144 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
16 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
782 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
17 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
3 answers
349 views
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()
Ivo
Telerik team
 answered on 15 Oct 2019
Narrow your results
Selected tags
Tags
+? more
Top users last month
Matthias
Top achievements
Rank 5
Bronze
Bronze
Iron
Psyduck
Top achievements
Rank 4
Bronze
Bronze
Iron
Liu
Top achievements
Rank 1
Iron
Alex
Top achievements
Rank 1
Veteran
Iron
Iron
George C.
Top achievements
Rank 2
Iron
Veteran
Top users last month
Matthias
Top achievements
Rank 5
Bronze
Bronze
Iron
Psyduck
Top achievements
Rank 4
Bronze
Bronze
Iron
Liu
Top achievements
Rank 1
Iron
Alex
Top achievements
Rank 1
Veteran
Iron
Iron
George C.
Top achievements
Rank 2
Iron
Veteran