Telerik Forums
JustMock Forum
1 answer
124 views
Hi there,

I'm new to JustMock and I'm looking into writing unit tests. Below i have copied the code i'm trying to test and will also copy what i have so far for unit testing. Looking at the test covarage within Visual Studio i aren't testing the catch exceptions and i don't know how to do this. Most my tests are structured this way and any help to get me moving again will be appreciated.

[HttpGet]
 [Route("api/DealBuilder/GetSession")]
 public IHttpActionResult NewVersion(string sessionId)
 {
     try
     {
         if (!String.IsNullOrEmpty(sessionId))
         {
             try
             {
                 return Ok(dealbuilderRepository.GetTemplateAndXml(new Guid(sessionId)));
             }
             catch (Exception ex)
             {
                 return InternalServerError(ex);
             }
         }
         else
         {
             return BadRequest("No Session ID was passed.");
         }
 
     }
     catch (Exception ex)
     {
         // TODO: logger.Error(ex.Message, ex);
         return InternalServerError(ex);
     }
 }

This is what i have so far for tests on my code above.

[TestMethod]
  public void NewVersion()
  {
      var repo = Mock.Create<IDealBuilderRepository>();
 
      var controller = new DealBuilderController(repo);
 
      Mock.Arrange(() => repo.Equals(Arg.IsAny<String>()));
 
      var result = controller.NewVersion(Arg.IsAny<String>());
 
      Mock.Assert(repo);
  }
 
 
  [TestMethod]
  public void GetNewVersionFail()
  {
      var repo = Mock.Create<IDealBuilderRepository>();
 
      var controller = new DealBuilderController(repo);
 
      Mock.Arrange(() => repo.Equals(Arg.IsAny<Guid>())); // .Returns(null);
 
      var result = controller.NewVersion(new Guid().ToString()) as InternalServerErrorResult ;
 
      Mock.Assert(typeof(InternalServerErrorResult));
  }



Thanks again,

Tommy
Stefan
Telerik team
 answered on 01 Oct 2014
1 answer
256 views
try to Mock setUtcOffset method . But after await Request.Content.ReadAsMultipartAsync... Mock doesnot work . Please tell how it'll fix ??

[TestMethod]
public async Task TestUploadEntity()
{
    IContainer container = (IContainer)TestContext.Properties["IContainer"];
    BaseApiController apicontroller = container.Resolve<BaseApiController>();
    Mock.NonPublic.Arrange(apicontroller, "setUtcOffset").IgnoreArguments().IgnoreInstance();
      
    var config = new HttpConfiguration();
    var route = config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");
    var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "Mobile" } });
    MultipartFormDataContent formDataContent = new MultipartFormDataContent();
    formDataContent.Add(new StringContent(Guid.NewGuid().ToString()), name: "EntityID");
    controller.Request = request;
    controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
    var result = await controller.addUpdateMessage();
}
  
[HttpPost]
 public async Task<string> addUpdateMessage()
 {
   if (!Request.Content.IsMimeMultipartContent())
    {
       throw new HttpResponseException(HttpStatusCode.BadRequest);
    }
     var provider = await Request.Content.ReadAsMultipartAsync<InMemoryMultipartFormDataStreamProvider>(new InMemoryMultipartFormDataStreamProvider());
     setUtcOffset();
     return "Success";
 }

Stefan
Telerik team
 answered on 29 Sep 2014
10 answers
239 views
Hello.  I am having some difficulty getting an update to JustMock working for our existing unit test library. 

Details:
We were on 2013.2.611 and have upgraded to 2014.2.811.1. 
We use TFS Build to run unit tests (under MSTest).  I have already set up the code activity (including environmental settings) from the last version based on the JustMock guide and it was working with 100% success rate on the old version. 
I updated the library to latest one from the new JustMock installation. 

Builds completes and most of the JustMock related unit tests are failing with many similar error messages such as:
Telerik.JustMock.MockException: Arranging the return value of a constructor call is not supported.
Telerik.JustMock.MockException: Can not instantiate proxy of class: Could not find a parameterless constructor.

Are there any major changes between the versions that could be causing this?  Something I forgot to update?

Sven
Top achievements
Rank 1
 answered on 18 Sep 2014
3 answers
163 views
Hi, I've been having some trouble passing a list to a class that is the instance of a MockingContainer. 
01.using System.Collections.Generic;
02. 
03.namespace JustMock_AutoContainer
04.{
05.    public interface IWorker
06.    {
07.        void DoSomething();
08.    }
09. 
10.    public interface IService
11.    {
12.        string Moo { get; }
13. 
14.        void DoLotsOfThings();
15.    }
16. 
17.    public class Service : IService
18.    {
19.        private readonly IList<IWorker> workers;
20. 
21.        public Service(IList<IWorker> workers, string moo)
22.        {
23.            this.workers = workers;
24.            this.Moo = moo;
25.        }
26. 
27.        public string Moo { get; private set; }
28. 
29.        public void DoLotsOfThings()
30.        {
31.            foreach (var worker in this.workers)
32.            {
33.                worker.DoSomething();
34.            }
35.        }
36.    }
37.}

And the test class is:
01.using JustMock_AutoContainer;
02.using Microsoft.VisualStudio.TestTools.UnitTesting;
03.using System.Collections.Generic;
04.using Telerik.JustMock;
05.using Telerik.JustMock.AutoMock;
06.using Telerik.JustMock.Helpers;
07. 
08.namespace JustMock_AutoContainer_Tests
09.{
10.    [TestClass]
11.    public class ServiceTest
12.    {
13.        #region Fields
14.        private MockingContainer<Service> container;
15.        #endregion
16. 
17.        #region Test Configuration
18.        [TestInitialize]
19.        public void CreateTargetContainer()
20.        {
21.            this.container = new MockingContainer<Service>();
22.        }
23.        #endregion
24. 
25.        [TestMethod]
26.        public void DoLotsOfWork_TwoWorkers_AllWorkersCalled()
27.        {
28.            // Arrange
29.            var provider1 = StubWorker();
30.            var provider2 = StubWorker();
31.            var target = this.CreateTarget(provider1, provider2);
32. 
33.            // Act
34.            target.DoLotsOfThings();
35. 
36.            // Assert
37.            Assert.AreEqual("moo", target.Moo);
38.            provider1.Assert(p => p.DoSomething()); // Fails here :(
39.            provider2.Assert(p => p.DoSomething());
40.        }
41. 
42.        #region Support Methods
43.        private static IWorker StubWorker()
44.        {
45.            var dataTraceProvider = Mock.Create<IWorker>();
46.            return dataTraceProvider;
47.        }
48. 
49.        private IService CreateTarget(params IWorker[] providers)
50.        {
51.            this.container
52.                    .Bind<IList<IWorker>>()
53.                    .ToConstant((IList<IWorker>)providers);
54. 
55.            //TODO: fix line above; the list is not being picked up in the target.
56.            // JustMock seems keen on giving us a list with one and only one item in it, rather than
57.            // what we've registered above.
58.            this.container
59.                    .Bind<string>()
60.                    .ToConstant("moo");
61. 
62.            return this.container.Instance;
63.        }
64. 
65.        #endregion
66.    }
67.}

The registration on line 51 seems to be ignored.  Is there something else I should be doing?
Stefan
Telerik team
 answered on 10 Sep 2014
1 answer
102 views
Hi,
The following code does not work...
public interface IService2
{
    string MethodWithArgs(string one, string two);
}
 
[TestMethod]
public void SubbingMethodwithArgs_DontCareAboutValues_StubbedMethodCalled()
{
    var service = StubMethodWithArgs("rv");
    var actual = service.MethodWithArgs("a", "b");
    Assert.AreEqual("rv", actual);
}
 
private static IService2 StubMethodWithArgs(string returnValue, string expectedOne = null, string expectedTwo = null)
{
    var service = Mock.Create<IService2>();
    service
       .Arrange(s => s.MethodWithArgs(
            null != expectedOne ? Arg.Is(expectedOne) : Arg.AnyString,  // null coalesance (??) doesn't work either
            null != expectedTwo ? Arg.Is(expectedTwo) : Arg.AnyString))
       .Returns(returnValue);
    return service;
}


Is this a limitation of JustMock?

Regards,

Nick
Stefan
Telerik team
 answered on 26 Aug 2014
1 answer
199 views
Hi, is it possible to use MockingContainer<T> where T is an abstract class, such as the following:

01.public abstract class SimpleBaseClass
02.{
03.    private readonly IService service;
04.    protected SimpleBaseClass(IService service)
05.    {
06.        this.service = service;
07.    }
08.    public void CallServiceMethod()
09.    {
10.        this.service.DoLotsOfThings();
11.    }
12.}

I've tried the following, the latter works as expected. 
01.[TestMethod]
02.public void AutoMock_AbstractClass_CallsMethod()
03.{
04.    var container = new MockingContainer<SimpleBaseClass>();
05.    //container.Bind<SimpleBaseClass>().ToMock(); // Still fails :(
06.    container.Arrange<IService>(s => s.DoLotsOfThings()).MustBeCalled();
07. 
08.    container.Instance.CallServiceMethod();
09. 
10.    container.AssertAll();
11.}
12. 
13.[TestMethod]
14.public void CreateMock_AbstractClass_CallsMethod()
15.{
16.    var service = Mock.Create<IService>();
17.    var target = Mock.Create<SimpleBaseClass>(Behavior.CallOriginal, service);
18. 
19.    target.CallServiceMethod();
20. 
21.    service.Assert(s => s.DoLotsOfThings());
22.}

I've tried configuring with AutoMockSettings using CallOriginal, but it just seems like NInject always jumps in and fails to find a suitable constructor.
Tsvetomir
Telerik team
 answered on 22 Aug 2014
2 answers
466 views
Can I (or does it make sense) call a private method from a unit test? 

The setup code is getting really big to test a little piece of code within a private method. Instead it seems like it might be a good idea to just mock the parameters and then call the private method as follows (incomplete since I don't know if this works). I want to call a piece of the private implementation with defined parameters and then test for results. This would be a replacement for having to walk through the code in the debugger over and over again. 

// Arrange mock data.
var service = new ScheduledTaskService();
var start = new DateTime(2014, 08, 15);
var due = start.Next(DayOfWeek.Thursday);
var assignee = new SimpleEmployeeView {Id = 1, LastNameFirstName = "Test User", IsActive = true};
var taskModel = new ScheduledTaskModel()
{
    DaysBeforeDue = 5,
    Start = start,
    End = due,
    Title = "Test Subject",
    Description = "Test Description",
    Id = 999
};
 
// This is the method I would like to call somehow if possible. 
Mock.NonPublic.Arrange(service, "CreateTaskForAssignee", taskModel, assignee);
 
// Ignore db changes. 
var database = Mock.Create<Database>();
Mock.Arrange(database, d => d.SaveChanges()).DoNothing();

// TODO test for changes in the result.


Todor
Telerik team
 answered on 21 Aug 2014
4 answers
81 views
I figure this out... but I know it won't be very complicated.
I am calling this method and I want to mock the string "alpha" 

public void Request()
{
     if (string.isNullOrEmpty(alpha))
      {
           Do somthing bad
      }
     else
     {
          Do somthing good
      }

Pretty much I want alpha to be mocked so that it passes the if statement and goes on to do something good.
Kaloyan
Telerik team
 answered on 14 Aug 2014
11 answers
170 views
I'm using JustMock to mock out the HttpContext when testing an ASP.Net MVC  controller, below are snapshots of  the stack when I pause the execution:


 Telerik.JustMock.dll!Telerik.JustMock.Core.Context.HierarchicalTestFrameworkContextResolver.CreateAttributeMatcher.AnonymousMethod__26 Normal
  [External Code]  
  XXXXXXXX.Web.Application.dll!XXXXXXXX.Web.Application.Controllers.TransportController.Index() Line 44  
  XXXXXXXX.Tests.dll!XXXXXXTests.Transport.TransportControllerTests.IndexPageTest() Line 36  
  [External Code]  

Telerik.JustMock.dll!Telerik.JustMock.Core.Context.HierarchicalTestFrameworkContextResolver.FindTestMethod Normal
  [External Code]  
XXXXXXXX.Web.Application.dll!XXXXXXXX.Web.Application.Controllers.TransportController.Index() Line 44  
  XXXXXXXX.Tests.dll!XXXXXXXX.Tests.Transport.TransportControllerTests.IndexPageTest() Line 36  
  [External Code]  
Stefan
Telerik team
 answered on 06 Aug 2014
1 answer
111 views
Hi,

Does JustMock support Windows Phone 8.1 WinRT apps? I tried referenced Telerik.JustMock.dll in my project and wrote a sample test, it compiles fine but I get the below runtime error:

UnitTests.SetupTest threw exception. System.IO.FileNotFoundException: System.IO.FileNotFoundException: Could not load file or assembly 'System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified..

Is it a Justmock not supporting WP 8.1 WinRT issue? Or am I missing something?

Thanks,
Tarun
Stefan
Telerik team
 answered on 04 Aug 2014
Narrow your results
Selected tags
Tags
+? more
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?