Telerik Forums
JustMock Forum
1 answer
38 views
It looks like it doesn't work. 

Is there a way to get JustMock running on the Windows Phone 7 framework? 

I tried it and got an error: 
Could not load type 'System.Reflection.Emit.ModuleBuilder' from assembly 'mscorlib, Version=3.7.0.0, Culture=neutral, PublicKeyToken=969DB8053D3322AC'.
I'm assuming it wants the full Silverlight version of that. 

cheers,
Stephen
Ricky
Telerik team
 answered on 24 Jun 2011
1 answer
99 views
Evening,

I was trying to step into some code and got the following error:

Call stack location:

Telerik.CodeWeaver.Hook.dll!Telerik.CodeWeaver.Hook.Bindings.TryGetDelegate(string bindingKey) Line 32

Source file location:

Locating source for 'c:\B\Minotaur\JustMock CI Build\Sources\Telerik.CodeWeaver.Hook\Bindings.cs'. Checksum: MD5 {c2 99 df 65 6a 15 68 37 cd e6 77 54 d3 bd fa c5}
The file 'c:\B\Minotaur\JustMock CI Build\Sources\Telerik.CodeWeaver.Hook\Bindings.cs' does not exist.
Looking in script documents for 'c:\B\Minotaur\JustMock CI Build\Sources\Telerik.CodeWeaver.Hook\Bindings.cs'...
Looking in the projects for 'c:\B\Minotaur\JustMock CI Build\Sources\Telerik.CodeWeaver.Hook\Bindings.cs'.
The file was not found in a project.
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\crt\src\'...
The debug source files settings for the active solution indicate that the debugger will not ask the user to find the file: c:\B\Minotaur\JustMock CI Build\Sources\Telerik.CodeWeaver.Hook\Bindings.cs.
The debugger could not locate the source file 'c:\B\Minotaur\JustMock CI Build\Sources\Telerik.CodeWeaver.Hook\Bindings.cs'.

I know that I do not have a path label "'c:\B\Minotaur\JustMock CI Build"

Thanks

James

p.s.

I was attempting to duplicate the application Graham was showing (great example of where to use mock object)

http://www.telerik.com/community/forums/justmock/general-discussions/am-i-setting-up-these-tests-correctly.aspx
Ricky
Telerik team
 answered on 15 Jun 2011
1 answer
92 views
I am experiencing difficulty mocking an interface that has write only properties.  When I try to set the property's value a NullReferenceExcpetion is thrown.

Here is some sample code (which throws the exception):
public interface IFoo
{
    int Foo { set; }
}
 
 
[TestMethod]
public void TestSetOnlyProperty()
{
    IFoo fooMock = Mock.Create<IFoo>();
 
    fooMock.Foo = 30;
 
    Mock.AssertSet(() => fooMock.Foo = 30);
}

By simply adding a getter to the interface, the test passes as expected:
public interface IFooGetAndSet
{
    int Foo { get; set; }
}
 
[TestMethod]
public void TestSetProperty()
{
    IFooGetAndSet fooMock = Mock.Create<IFooGetAndSet>();
 
    fooMock.Foo = 30;
 
    Mock.AssertSet(() => fooMock.Foo = 30);
}

I would like to be able to mock interfaces that might have write only properties.

Thanks
Ricky
Telerik team
 answered on 15 Jun 2011
8 answers
355 views

I have a simple 'Service' system set up with an interface as shown below. I am trying to mock it for use in my unit testing, but am having a bit of an obstacle. The way it works is that I design classes that implement IRequestFor<T,R> and I would call the service bus like this...

var member = new Member { Name = "valid@email.com", Password = "validPassword" };ServiceBus.Query<ValidateUser>().With(member);

This works fine in my code. I have no issues with it. But when I try to mock it, like this ..

var service = Mock.Create<IServiceBus>();

           
// Model
           
var model = new Web.Models.Membership.Login
           
{
               
Email = "acceptible@email.com",
               
Password = "acceptiblePassword",
               
RememberMe = true
           
};

           
// Arrange
           
Mock.Arrange(() => service.Query<Membership.Messages.ValidateMember>().With(model))
               
.Returns(true);

I am given the following error.

NullReferenceException

I don't even know what the exception is on. It 'points' to the ServiceBus in my Controller code, and if I use the debugger, the object is like .. {IServiceBus_Proxy_2718486e043f432da4b143c257cef8ce}, but other than that, everything else looks the exact same as if I step through it in a normal run.

I am using Telerik JustMock for the mocking, but I don't know how I would do this in a different mocking framework either. I am using Ninject for my Dependency Injection, as well. Can anyone help me?

For convenience, I have included as much of my code as possible below.

Code Reference

Service Bus

public interface IServiceBus
{
    T
Query<T>() where T : IRequest;
    T
Dispatch<T>() where T : IDispatch;
}

public interface IRequest
{
}

public interface IDispatch
{

}

public interface IRequestFor<TResult> : IRequest
{
   
TResult Reply();
}

public interface IRequestFor<TParameters, TResult> : IRequest
{
   
TResult With(TParameters parameters);
}

public interface IDispatchFor<TParameters> : IDispatch
{
   
void Using(TParameters parameters);
}

Service Bus Implementation

public class ServiceBus : IServiceBus
{
   
private readonly IKernel kernel;

   
public ServiceBus(IKernel kernel) {
       
this.kernel = kernel;
   
}

   
/// <summary>
   
/// Request a query behavior that may be given parameters to yield a result.
   
/// </summary>
   
/// <typeparam name="T">The type of query to request.</typeparam>
   
/// <returns></returns>
   
public T Query<T>() where T : IRequest
   
{
       
// return a simple injected instance of the query.
       
return kernel.Get<T>();
   
}

   
/// <summary>
   
/// Request a dispatch handler for a given query that may be given parameters to send.
   
/// </summary>
   
/// <typeparam name="T">The type of handler to dispatch.</typeparam>
   
/// <returns></returns>
   
public T Dispatch<T>() where T : IDispatch
   
{
       
// return a simple injected instance of the dispatcher.
       
return kernel.Get<T>();
   
}
}

Service Bus Dependency Injection Wiring (Ninject)

Bind<IServiceBus>()
               
.To<ServiceBus>()
               
.InSingletonScope();

Complete Unit Test

    [TestMethod]
   
public void Login_Post_ReturnsRedirectOnSuccess()
   
{
       
// Inject
       
var service = Mock.Create<IServiceBus>();
       
var authenticationService = Mock.Create<System.Web.Security.IFormsAuthenticationService>();

       
// Arrange
       
var controller = new Web.Controllers.MembershipController(
            service
, authenticationService
       
);

       
var httpContext = Mock.Create<HttpContextBase>();

       
// Arrange
       
var requestContext = new RequestContext(
           
new MockHttpContext(),
           
new RouteData());

        controller
.Url = new UrlHelper(
            requestContext
       
);

       
// Model
       
var model = new Web.Models.Membership.Login
       
{
           
Email = "acceptible@email.com",
           
Password = "acceptiblePassword",
           
RememberMe = true
       
};

       
// Arrange
       
Mock.Arrange(() => service.Query<Membership.Messages.ValidateMember>().With(model))
           
.Returns(true);

       
// Act
       
var result = controller.Login(model, "/Home/");

       
// Assert
       
Assert.IsInstanceOfType(result, typeof(RedirectResult));
   
}

Actual Query Method

public class ValidateMember : IRequestFor<IValidateMemberParameters, bool>
{
   
private readonly ISession session;

   
public ValidateMember(ISession session) {
       
this.session = session;
   
}

   
public bool With(IValidateMemberParameters model)
   
{
       
if (String.IsNullOrEmpty(model.Email)) throw new ArgumentException("Value cannot be null or empty.", "email");
       
if (String.IsNullOrEmpty(model.Password)) throw new ArgumentException("Value cannot be null or empty.", "password");

       
// determine if the credentials entered can be matched in the database.
       
var member = session.Query<Member>()
           
.Where(context => context.Email == model.Email)
           
.Take(1).SingleOrDefault();

       
// if a member was discovered, verify their password credentials
       
if( member != null )
           
return System.Security.Cryptography.Hashing.VerifyHash(model.Password, "SHA512", member.Password);

       
// if we reached this point, the password could not be properly matched and there was an error.
       
return false;
   
}
}

Ricky
Telerik team
 answered on 15 Jun 2011
7 answers
273 views
This is giving me a compile error:


var urlHelper = Mock.Create<UrlHelper>( Constructor.Mocked );
Mock.Arrange( () => urlHelper.Action( Arg.IsAny<string>(), Arg.IsAny<string>() ) )
    .DoInstead( ( string actionName, string controllerName ) => {} )
    .Returns( ( string actionName, string controllerName ) => String.Format( "/{0}/{1}", controllerName, actionName ) );

The error is:

Error 4 The type arguments for method 'Telerik.JustMock.Helpers.MultipleReturnValueChainHelper.Returns<TReturn>(Telerik.JustMock.Expectations.Abstraction.IAssertable, TReturn)' cannot be inferred from the usage. Try specifying the type arguments explicitly. D:\DevL\Overview\Alpha\Source\Test\Client\Client.Test\Core\Menus\MenuBuilderTest.cs 29 11 Client.Test

First, am I mocking this correctly?  I just want to return a formatted route instead of actually calling Action.

Second...what do I have to do to get it to compile?  I've tried specifying the template parameters for Returns and casting the lambda to Func2<string,string,string>.  I'm not sure why it's complaining.

Thanks,
Chris
Ricky
Telerik team
 answered on 15 Jun 2011
2 answers
114 views
I am trying to arrange the following:

TEntity GetByKey(params object[] keyValues);

using:

const long id = 1;
Mock.Arrange(() => _appSettingRepository.GetByKey(id)).Returns(() => null);

This is failing with the following:

Get_app_setting_by_invalid_key_should_return_null' failed: System.NullReferenceException : Object reference not set to an instance of an object.
at ....Ž(UnaryExpression expression)
at ..ˆ(Expression expression)
at ....(Expression argExpression)
at ....(Int32 i, Expression chidExp)
at ..[T](IEnumerable`1 enumeration, Action`2 action)
at ..Œ(MethodCallExpression expression)
at ..ˆ(Expression expression)
at ..(Object obj, Type mockTarget, MethodInfo method, Expression expression)
at ..(Expression`1 expression)
at Telerik.JustMock.Mock...€( x)
at ..[TDelgate,TReturn](† instruction, Func2`2 function)
at Telerik.JustMock.Mock.Arrange[TResult](Expression`1 expression)
Ricky
Telerik team
 answered on 13 Jun 2011
1 answer
125 views
In regards to http://www.telerik.com/community/forums/reply-thread.aspx?messageId=1680620&threadId=303674 I'm hoping that someone might be able to provide further help on this?

This example was great. I'm wondering if someone there could point me in a direction on how to do "NorthwindDataContextDataContext"? I did some research and see that I might be creating this with sqlMetal.exe. If so, would you mine letting me know

1) what command line you used to generate it?
2) how do you add it to the project? I was able to generate a "cs" file containing many LINQ objects but could not seem to be able to reference the class once I created it?
3) when I was doing my research, I believe that I might have come across a refernce to be able to generate store procedure (could be wrong as it was late last night when I was running it @ home and now it is early in the office here) :). If this is the case, can I add records to JustMock and run the store procedure against it?

Thanks for a great product. Everytime I go back to do further research on mocking objects, the more that I seem such a hugh benefit in using it :)

Thanks again,

James
Ricky
Telerik team
 answered on 13 Jun 2011
3 answers
297 views
How do I call a private method without using the MS accessor?  I find when using the accessor the mocking does not work,
Ricky
Telerik team
 answered on 10 Jun 2011
5 answers
293 views
I have a Utility class that contains several static methods.  Originally I was setting up my static mock within an individual unit test but that was causing it to fail when run as a group of tests (I found the reason for that).  So to fix that issue I have moved the static setup to the ClassInitialize method. 

Here is the code....
Mock.SetupStatic<EagleUtility>();
           Mock.Arrange(() => EagleUtility.ValidateMessage(Arg.IsAny<byte[]>(), Arg.AnyInt, TowerTypes.Unified)).
             DoNothing().Returns(true).MustBeCalled();



This does not seem to be working.  When I call the test method that uses the mock and asserts that this and other methods are called it fails. I try debugging and see that the method in question is not being skipped as I expect it to.

Any suggestions?
Ricky
Telerik team
 answered on 08 Jun 2011
2 answers
122 views
Hi im try to grant access to a private method with class generic type return but allway throw the same error. i put here and example only the structure as my code.

Alway send the error:
Argument Exception
Could not resolve the target method; make sure that you have provided arguments correctly.
Code:

    public interface IBase
    {
    }
 
    public abstract class BaseClass
    {
    }
 
    public class AssignedClass : BaseClass
    {
    }
 
    public class WrapperClass<T> : IBase where T : BaseClassnew()
    {
    }
 
    public class Control
    {
        private WrapperClass<AssignedClass> getWrapper()
        { return null; }
    }
 
    [TestClass]
    public class TestFlow
    {
        [TestMethod]
        public void ShouldWork()
        {
            var control = Mock.Create<Control>();
            var wrapper = Mock.Create<WrapperClass<AssignedClass>>();
 
            //Dosent Work
            Mock.NonPublic.Arrange<WrapperClass<AssignedClass>>(control, "getWrapper").Returns(wrapper);
 
            //Dosent Work
            Mock.NonPublic.Arrange<IBase>(control, "getWrapper").Returns(wrapper);
        }
 
    }
Ricky
Telerik team
 answered on 03 Jun 2011
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?