Telerik Forums
JustMock Forum
2 answers
177 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
4 answers
250 views

Both Azure Storage Emulator and JustMock use port 10001 and 10002 as default ports.

Is it possible to change the ports JustMock uses?

Mark
Top achievements
Rank 1
 answered on 13 Aug 2020
2 answers
698 views

Visual Studio Professional 2019 - version 16.6.3

JustMock 2019.1.115.2 (Commercial version)

My solution has 3000+ unit tests and suddenly, 1000+ tests failed with the error :

 Message: 
    Test method Cloee2.Ws.UnitTests.Services.Business.TestConditionsAdmissionSe2.GetClasseGeneriqueNulle threw exception: 
    Telerik.JustMock.Core.ElevatedMockingException: Cannot mock 'Ch.Ne.Ceg.Cloee2.Services.CrudCloee2Helper'. The profiler must be enabled to mock, arrange or execute the specified target.
  Stack Trace: 
    ProfilerInterceptor.ThrowElevatedMockingException(MemberInfo member)
    MocksRepository.InterceptStatics(Type type, MockCreationSettings settings, Boolean mockStaticConstructor)
    MocksRepository.ConvertExpressionToCallPattern(Expression expr, CallPattern callPattern)
    MocksRepository.Arrange[TMethodMock](Expression expr, Func`1 methodMockFactory)
    ProfilerInterceptor.GuardInternal[T](Func`1 guardedAction)
    TestConditionsAdmissionSe2._arrangeSearchFormations() line 523
    TestConditionsAdmissionSe2._mockGetClasseGenerique() line 913
    TestConditionsAdmissionSe2.GetClasseGeneriqueNulle() line 987

They pass in debug, but not in run.

I try to clear bin and obj folder of my solution, but nothing to do.

Any idea ?

Ivo
Telerik team
 answered on 08 Jul 2020
5 answers
335 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
3.1K+ 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
595 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
385 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
98 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
82 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
133 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
Narrow your results
Selected tags
Tags
+? more
Top users last month
Michael
Top achievements
Rank 1
Iron
Wilfred
Top achievements
Rank 1
Alexander
Top achievements
Rank 2
Iron
Iron
Matthew
Top achievements
Rank 1
Iron
ibra
Top achievements
Rank 1
Want to show your ninja superpower to fellow developers?
Top users last month
Michael
Top achievements
Rank 1
Iron
Wilfred
Top achievements
Rank 1
Alexander
Top achievements
Rank 2
Iron
Iron
Matthew
Top achievements
Rank 1
Iron
ibra
Top achievements
Rank 1
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?