Telerik Forums
JustMock Forum
3 answers
167 views
Hi,

First of all, I'm newbie with Just Mock and after a few weeks working with it I think you are doing a great job. So, congratulations!!

Maybe this question is already answered but, if so, I didn't find it. I'd like to intercept a call to a generi method similar to:
public  class MyClass
{
    public void MyMethod<T>()
    {
        //
    }
}

Now I want to arrange a MyClass instance so I can assert that the method has been call only once for an specific type and never for any other type. I'm tryig to do something similar to:
var service = Mock.Create<MyClass>();
 Mock.Arrange(() => service.MyMethod<T>()).OccursNever();

So I can assert the generic method is never called
Kaloyan
Telerik team
 answered on 09 Nov 2017
1 answer
84 views

So I have a method that I'm trying to test that looks something like the following:

        public void MethodToTest(List<Object> importEntities, short id)
        {
            var relevantObjects = importEntities.Select(some code).Distinct();

            var list1= new Dictionary<string, NewTenantRange>();

            var list2= new Dictionary<string, NewTenantRange>();

            var list3= new Dictionary<string, NewTenantRange>();

            foreach (var obj in relevantObjects)
            {
                if (!list1.ContainsKey(obj.key))
                {
                    var item1 = NewTenantRange.GetBwTenantRange(obj);
                    list1.Add(item1.Number, item1);
                }

                if (!list2.ContainsKey(obj.key))
                {
                    var item2 = NewTenantRange.GetBbTenantRange(obj);
                    list2.Add(item2.Number, item2);
                }

                if (!list3.ContainsKey(obj.key))
                {
                    var item3 = NewTenantRange.GetVsTenantRange(obj);
                    list3.Add(item3.Number, item3);
                }
            }

            InsertRange(list1.Values, tenantId, Ranges.Range1);
            InsertRange(list2.Values, tenantId, Ranges.Range2);
            InsertRange(list3.Values, tenantId, Ranges.Range3);
        }

And my test so far:

[TestMethod]
        public void TestMethodToTest()
        {
            //Arrange
            var service = Mock.Create<myService>(Constructor.Mocked, Behavior.CallOriginal);

            var entities = FakeLf10Orders().ToList(); //returns list of fake objects

            Mock.NonPublic.Arrange(service, "InsertRange",
                    ArgExpr.IsAny<IEnumerable<TenantRangeService.NewTenantRange>>(), Arg.AnyShort, Arg.IsAny<Ranges>())
                .DoNothing().Occurs(3);

            //Act 
            service.MethodToTest(entities, Arg.AnyShort);

            //Assert
            Mock.AssertAll(service);
        }

Now, everuthing is working fine until the method InsertRange is called for the second time. Then instead of DoNothing(), the code is executed and therefore fails. Anyone with any ideas?

 

Thank you!

//Petter

Petter
Top achievements
Rank 1
 answered on 06 Nov 2017
3 answers
90 views

I have a class which has a large number of properties each of which returns a double, and a method under test which takes a string, and an instance of the class, and calls one of these properties based on the value of the string (effectively, it calls the property whose name is the string). I am using NUnit, which provides for parameterised testing. I would like to test the method with a set strings, but this means arranging for the specific property call. I am quite close, but I can't quite get it to work.

So far I have the following. A set of test parameters, defined as a Dictionary:

public static Dictionary<string, System.Linq.Expressions.Expression<Func<IMyClass, double>>> SpecialProperties = new Dictionary<string, System.Linq.Expressions.Expression<Func<IMyClass, double>>>()
{
    {"InlineLength", x=>x.InLineLength},
    {"BranchLength", x=>x.BranchLength},
    {"TotalLength", x=>x.TotalLength},
    {"CentreLineLength", x=>x.CentreLineLength},
    {"SurfaceArea", x=>x.SurfaceArea},

}

 

Then I have the test method:

[Test]
[TestCaseSource("SpecialProperties")]
public void SpecialProperties_Test(string specialPropertyName, System.Linq.Expressions.Expression<Func<IMyClass, double>> specialProperty)
{
    IMyClass mockMyClass = Mock.Create<IMyClass>(Behavior.Strict);

    mockMyClass.Arrange(specialProperty).Returns(9.99);

   double result =  _concreteInstanceOnTest.MethodOnTest(specialPropertyName, mockMyClass);

    Assert.AreEqual(9.99, result);

}

This very nearly works, but I get an Inconsistent Accessibility error - Expression<Func<IMyclass, double>> is less accessible than SpecialProperties_Test(). I'm obviously not doing it quite right. Can anybody help?

Mihail
Telerik team
 answered on 27 Sep 2017
1 answer
355 views

I'm not sure if this is a JustMock question, but it may be. I'm trying to test a Kendo datasource 'read' method which is implemented in my MVC controller. The datasource is actually part of a grid definition, but I have others that are in auto-complete controls.

The following is a fragment of my grid definition in the view.

.DataSource(dataSource => dataSource
    .Ajax()
    .PageSize(10)
    .Events(events => events.Error("error_handler").RequestEnd("onGridRequestEnd"))
    .Model(model =>
    {
        model.Id(p => p.Id);
        model.Field(p => p.Id).Editable(false);
        model.Field(p => p.PostedStr).Editable(false);
        model.Field(p => p.UpdatedStr).Editable(false);
    })
    .Read(read => read.Action("_GetBulletins", "Bulletins").Type(HttpVerbs.Get))
    .Create(create => create.Action("_CreateBulletin", "Bulletins").Type(HttpVerbs.Post).Data("sendAntiForgery"))
    .Update(update => update.Action("_UpdateBulletin", "Bulletins").Type(HttpVerbs.Post).Data("sendAntiForgery"))
    .Destroy(update => update.Action("_DeleteBulletin", "Bulletins").Type(HttpVerbs.Post).Data("sendAntiForgery"))
)

 

My controller methods is:

[AcceptVerbs(HttpVerbs.Get)]
[AjaxOnly]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult _GetBulletins(DataSourceRequest request)
{
    var model = (BulletinsViewModel)ViewModels.GetModel(HttpContext, Constants.Session.Model.BulletinsViewModelId);
    var enumerableModel = model.Bulletins.AsEnumerable();
    return Json(enumerableModel.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}

 

and a fragment of my test is:

var request = new DataSourceRequest()
{
    Aggregates = new List<AggregateDescriptor>(),
    Filters = new List<IFilterDescriptor>(),
    Groups = new List<GroupDescriptor>(),
    Sorts = new List<SortDescriptor>(),
    Page = 1,
    PageSize = 10
};
 
// Act
var result = controller._GetBulletins(request) as JsonResult;
var model = result.Data as BulletinsViewModel;

 

When I run my test, the controller throws and exception:

 

 

System.ArgumentNullException: 'Value cannot be null.'  Message:"Value cannot be null.\r\nParameter name: source"

Obviously I'm not setting up the 'request' properly, althought I don't exactly know what's wrong.

Rather than spin my wheels trying to figure that out, I wonder if you can advise me on the recomended approach to testing datasources.

TIA

Dave


 

 

 

Mihail
Telerik team
 answered on 27 Sep 2017
5 answers
152 views

Hi there, I'm trying to profile a very slow unit test using Visual Studio 2015 Enterprise, but this unit test uses JustMock.

 When I try to profile the test, it returns with the following exception:

"Telerik.JustMock.Core.ElevatedMockingException: Cannot mock 'ActuIT.Futurama.Config.Settings'. The profiler must be enabled to mock, arrange or execute the specified target.
Detected active third-party profilers:
* {C60A40F7-B6A2-428C-8E87-E1BF6563F650} (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."

 I've already linked the "Visual Studio 2015 Code Coverage/IntelliTrace" profiler in the Justmock settings, but this didn't change a thing.

 Does anyone have a solution?

 

Kamen Ivanov
Telerik team
 answered on 07 Aug 2017
3 answers
153 views

Hi

 

Does JustMock support unit testing for ASP .Net Core projects?

I am facing some dependency issues when i use JustMock to test ASP .Net Core project.

 

Thanks and Regards

Sujin

Kamen Ivanov
Telerik team
 answered on 21 Jul 2017
3 answers
99 views
01.using System;
02.using System.Collections.Generic;
03.using Microsoft.VisualStudio.TestTools.UnitTesting;
04.using Telerik.JustMock;
05. 
06.namespace JustMockTestProject
07.{
08.    public interface IFoo
09.    {
10.        IBar Bar { get; }
11.    }
12. 
13.    public interface IBar : IEnumerable<Object>
14.    {
15.        IBaz GetBaz();
16.    }
17. 
18.    public interface IBaz {}
19. 
20.    [TestClass]
21.    public class JustMockTest
22.    {
23.        [TestMethod]
24.        public void TestMethod1()
25.        {
26.            var foo = Mock.Create<IFoo>(Behavior.RecursiveLoose);
27.            var bar = Mock.Create<IBar>(Behavior.RecursiveLoose);
28. 
29.            Assert.IsNotNull(bar.GetBaz()); // passes
30.            Assert.IsNotNull(foo.Bar.GetBaz()); // fails
31.        }
32.    }
33.}


Expected Behavior: RecursiveLoose mocking behavior will cause every method to return a mocked object for reference types.
Actual Behavior: When RecursiveLoose runs into an interface that derives from IEnumerable<T>, the returned mocked object does not get recursively mocked causing NullReferenceException when a test attempts to access members on the mocked object (IBaz in the example above).

The above is a simplified test case to narrow down the source of the bug.  If I have an IEnumerable<T> property on IFoo instead, then the returned object is correctly mocked (GetEnumerator doesn't return null).

As shown in the above example on line 29, mocking an IBar directly works.  It is only when attempting to recursively mock an object that derives from IEnumerable that the problem occurs.
Kamen Ivanov
Telerik team
 answered on 13 Jul 2017
1 answer
83 views
Does JustMock has smart unit test suggestions feature like TypeMock Suggest? Please let me know
Kamen Ivanov
Telerik team
 answered on 28 Jun 2017
5 answers
858 views

I am trying to test async method but i am getting null reference exception.

I have a service that has a GetAll method which is async: public async Task<IQueryable<T>> GetAll()

and the method under test is calling this method: await _service.GetAll();

I am mocking the service and then doing an arrange on the getAll method, but i get a null reference exception when the method is called in the code under test.

Mock.Arrange(() => mockService.GetAll()).Returns(Task.FromResult<IQueryable<Models.VM>>(vms.AsQueryable()));

 

Thanks

Vikas Mittal

Kamen Ivanov
Telerik team
 answered on 23 Jun 2017
5 answers
320 views

Sorry if this is a noob question on JustMock, but I'm still learning the package.  

 

VS 2017 Enterprise 15.2(26430.6) Release
.NET Framework 4.6.01586
XUnit.net 2.2.0
JustMock 2017.2.502.1

 

Created a unit test for testing an email module where I'm mocking the SmtpClient to keep it from actually sending emails in unit tests.  When I run the tests either all together or individually, they run properly.  When I attempt to use the Test->Analyze Code Coverage, several of them fail with:

Message: Telerik.JustMock.Core.ElevatedMockingException : Cannot mock 'Void Send(System.Net.Mail.MailMessage)'. 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.

I've tried some of the suggestions I've found in other forum topics like disabling Intellitrace, running VS elevated and enabling the VS2015 Intellitrace option in the JustMock Options menu.  None of these combinations appear to make any difference.  As it is, I'm unable to view code coverage using these unit tests which limits the usability.

 

Here's the code that passes except under Analyze Code Coverage:

var log = Mock.Create<ILog>();
           Mock.Arrange(() => log.InfoFormat(EMailModule.Properties.Resources.Email_Send_log_SendingMessage,
               _validSubject)).OccursAtLeast(1);
 
           var smtpClient = Mock.Create<SmtpClient>(Behavior.CallOriginal);
           Mock.Arrange(() => smtpClient.Send(Arg.IsAny<MailMessage>()))
               .IgnoreArguments()
               .IgnoreInstance()
               .DoNothing()
               .OccursOnce();
 
           var mail = new Email(log, _testSMTPServer);
           mail.Sender = new MailAddress(_validSender);
           mail.EmailAddressesTo.Add(new MailAddress(_validEmail));
           mail.Subject = _validSubject;
           mail.Send();
 
           Mock.Assert(smtpClient);
           Mock.Assert(log);

 

Anyone have any suggestions?  Is this a bug, a known issue with VS2017 and JustMock or just me being too new to JustMock a.k.a.I screwed something up?

 

 

David
Top achievements
Rank 2
 answered on 04 Jun 2017
Narrow your results
Selected tags
Tags
+? more
Top users last month
Michael
Top achievements
Rank 2
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 2
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?