Telerik Forums
JustMock Forum
4 answers
176 views
Hi,
I am trying to mock db access using JustMock. I do have an interface defined and created a mock object from the interface. I then arranged a method to return false for any argument. After arranging the mock object on the second call with unique arguments a null reference exception is thrown. The code snippet below shows what I am trying to do:

IDBAccess fakeDBAccess = Mock.Create<IDBAccess>();
List<ModelType1> fakeModelType1 = GetFakeModelModelType1();
Mock.Arrange(()=> fakeDBAccess.GetModelType1ForPrimaryKey(Arg.Is<long>(1))).Returns(fakeModelType1[0]);
Mock.Arrange(() => fakeDBAccess.GetModelType1ForPrimaryKey(Arg.Is<long>(2))).Returns(fakeModelType1[1]);
List<fakeModelType2> fakeModelType2 = new List<fakeModelType2>();
Mock.Arrange(() => fakeDBAccess.GetModelType2ForPrimaryKey(Arg.IsAny<long>())).Returns(fakeModelType2);
Mock.Arrange(() => fakeDBAccess.GetModelType1Status(Arg.IsAny<ModelType1>())).Returns(false);
ClassUnderTest OUT = new ClassUnderTest(fakeDBAccess );

On debugging the above code try to call fakeDBAccess.GetModelType1Status() with two different values say fakeModelType[0] and fakeModelType[1] (in the watch window) the first call succeeds and returns false but the second call fails with a null reference exception. The order of calls do not matter. It is always  the second call that throws the null reference exception. Can you please confirm whether this is a bug or not. If this is a bug can you please suggest a work around?
Freddy
Top achievements
Rank 1
 answered on 24 Dec 2014
1 answer
172 views
How to Test Protected Static method in Abstract Class using JustMock 
Stefan
Telerik team
 answered on 24 Dec 2014
1 answer
105 views
Trying to write tests for some legacy code and I have a question about mocking fields or other references inside a mock. In the code below, "Assert.IsNotNull(member.Rsa)" will fail because the mocked constructor of member hasn't created anything. Currently I've solved the problem by creating a separate mock and assigning to it, but is this really the best way to do this?
var testChallengeData = new ChallengeData();
testChallengeData.responseList = new Response[] {new Response(), new Response(), new Response()};
 
var member = Mock.Create<Member>(Constructor.Mocked);
var rsa = Mock.Create<Vendors.RSA>(Constructor.Mocked);
 
Mock.SetupStatic(typeof (Settings), StaticConstructor.Mocked);
Mock.Arrange(() => Settings.getBool(Arg.AnyString)).IgnoreInstance().Returns(false);
Mock.Arrange(() => Settings.getInt(Arg.AnyString)).IgnoreInstance().Returns(3);
 
Mock.Arrange(() => rsa.CurrUserStatus).IgnoreInstance().Returns(Vendors.AdaptiveAuthRef.UserStatus.UNVERIFIED).OccursOnce();
Mock.Arrange(() => rsa.HasChallengeQuestions).IgnoreInstance().Returns(true).OccursNever();
 
Mock.Arrange(() => member.challengeQuestions).IgnoreInstance().Returns(testChallengeData);
Mock.Arrange(() => member.hasChallengeQuestions).CallOriginal();
member.Rsa = rsa;
 
Assert.IsNotNull(member.Rsa);
Assert.IsTrue(member.hasChallengeQuestions);
rsa.Assert();
Mock.Assert(() => Settings.getBool(Arg.AnyString), Occurs.Once());

Stefan
Telerik team
 answered on 24 Dec 2014
1 answer
147 views
Hi All, We have a requirement where we have to use NUnit to write test methods and JustMock for mocking the application.
Our application is exposing WCF services and the unit tests will be written to test the WCF Operations. We are using VS 2013.In our application we are using Dependency injection while calling the Constructor i.e. the parameters to the Constuctor are created using Dependency injection. Please refer below sample
 
 public NetworkService(IDbContextFactory<NetworkDbContext> contextFactory, IEventBus eventBus, HostService hostService, UserManagementService userManagementService)
         {
             _contextFactory = contextFactory.ThrowIfNull("contextFactory");
             _eventBus = eventBus.ThrowIfNull("eventBus");
             _hostService = hostService.ThrowIfNull("hostService");
             _userManagementService = userManagementService.ThrowIfNull("userManagementService");
       } 

I tried mocking using Telerik Justmock to create the objects of ContextFactory, EventBus etc. but the object created using mocking was of type Proxy of actual object rather than the object itself i.e. Proxy of IEventBus rather than IEventBus.The _contextFactory object is used to create a context like below

 using (var ctx = _contextFactory.Create()) 

But as the object is of type Proxy(Object) I am unable to create the context ctx in above scenario. Hence the controls goes to the Service but
when it tries to use context object ctx, it throws an "Null Reference exception" and hence the testing fails. 

Can anyone please suggest if there is any issue with the above and suggest on alternate solution using NUnit and JustMock. 

Any help will be highly appreciated. Thanks in advance.
Stefan
Telerik team
 answered on 17 Dec 2014
1 answer
167 views
Hi All,We have a requirement where we have to use NUnit to write test methods and JustMock for mocking the application. Dep injOur application is exposing WCF services and the unit tests will be written to test the WCF Operations.We are using VS 2013.In our application we are using Dependency injection while calling the Constructor i.e. the parameters to the Constuctor are created

using Dependency injection.Pls refer below
public NetworkService(IDbContextFactory<NetworkDbContext> contextFactory, IEventBus eventBus, HostService hostService, UserManagementService userManagementService)
        {
            _contextFactory = contextFactory.ThrowIfNull("contextFactory");
            _eventBus = eventBus.ThrowIfNull("eventBus");
            _hostService = hostService.ThrowIfNull("hostService");
            _userManagementService = userManagementService.ThrowIfNull("userManagementService");
      }

I tried mocking using Telerik Justmock to create the objects of ContextFactory/EventBus etc but the object create using mocking was of type Proxy of actual object rather than the object itself i.e. Proxy of IEventBus rather than IEventBus.The issue with this is, the _contextFactory object is used to create a context like below
using (var ctx = _contextFactory.Create())

But as the object is of type Proxy(Object) I am unable to create the context ctx in above scenario and hence the testing fails.

Can anyone please help me with the mocking.

Any help will be highly appreciated.

Thanks in advance.
Stefan
Telerik team
 answered on 17 Dec 2014
1 answer
282 views
I am using CallMethod to call a private method and it works great, but I need to call a method that has some ref parameters, Is it possible to do that
Also i would like to compare the values in the ref after the method execution finishes, basically instead of returning one value method is manipulating multiple values and i need to Assert all of them

Thanks
vikas
Stefan
Telerik team
 answered on 27 Nov 2014
8 answers
203 views
I have enabled the code activity workflow in a TFS build that runs unit tests.  My understanding is that JustMockTestRunner uses MSTest.exe to execute them.  Is it possible to use VSTest.Console.exe instead?
Kaloyan
Telerik team
 answered on 29 Oct 2014
1 answer
85 views
I have a mocked class which has a bool property BoolProperty.
I have a class under test with a method under test which first sets BoolProperty to true, and then to false.
I wish to set up an arrangement which tests that these two calls are made in the correct order, which I have done as follows:

    mockedClass.ArrangeSet(x => x.BoolProperty = true).InSequence();
    mockedClass.ArrangeSet(x => x.BoolProperty = false).InSequence();

This passes the test fine. However, if I reverse the order:

    mockedClass.ArrangeSet(x => x.BoolProperty = false).InSequence();
    mockedClass.ArrangeSet(x => x.BoolProperty = true).InSequence();

this *also* passes.
Shouldn't this second arrangement cause the test to fail?

I am using JustMock 2014.1.1424.1
Dave
Top achievements
Rank 1
 answered on 02 Oct 2014
1 answer
117 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
242 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
Narrow your results
Selected tags
Tags
+? more
Top users last month
Anislav
Top achievements
Rank 6
Silver
Bronze
Bronze
Jianxian
Top achievements
Rank 1
Iron
Marco
Top achievements
Rank 3
Iron
Iron
Iron
Jim
Top achievements
Rank 2
Iron
Iron
Nurik
Top achievements
Rank 2
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Anislav
Top achievements
Rank 6
Silver
Bronze
Bronze
Jianxian
Top achievements
Rank 1
Iron
Marco
Top achievements
Rank 3
Iron
Iron
Iron
Jim
Top achievements
Rank 2
Iron
Iron
Nurik
Top achievements
Rank 2
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?