Telerik Forums
JustMock Forum
3 answers
95 views
As I want install JustMock (JustMock_2010.1.528_Trial.msi) on my system (Visual Studio 2010 (German)) I got the message "This JustMock package requires Visual Studio. And then "The installer has encountered an unexpected error installing this package. This may indicate a problem with this package. The error code is 2869.
What can I do to install JustMock?

Kind regards
Marcel
mlzoll
Top achievements
Rank 1
 answered on 04 Jun 2010
3 answers
91 views
I realize JustMock is beta, but I thought I'd let you know of this issue.

I was testing out JustMock with Visual Studio 2010 RTM.  After installing JustMock, building my application received an error about ResXtoResources.exe has stopped working.  The build output shows resgen.exe errors out with error code -1073740940.

I've attached an image of the error message that pops up.

Bascially any project that has resource built by resgen.exe fail.

After uninstalling JustMock, my build worked once again.
Ricky
Telerik team
 answered on 03 Jun 2010
1 answer
121 views

We are busy developing a Composite Application Library (PRISM) applicationusing Visual Studio 2010, WPF and Silverlight 4.0. We have managed to get asnear as 100% code sharing between our WPF and Silverlight application becauseof the Telerik WPF/SL controls. Currently we are spending our time to write theUnit Tests for our Shell application and our common CAL modules before we startporting the existing application onto the new framework.

We have investigated standard Microsoft Visual Studio Unit Tests in additionto Rhino Mocks and Moq. We have had many troubles in getting both Rhino Mockand Moq to test our CAL application, specifically when it comes to testing theAsynchronous ICommand call-backs and the IEventAggregator subscriptions.

Yesterday we decided to investigate the Telerik JustMock mocking libraries,however we're still failing to completely test our CAL application.

Can you please provide us with a sample of testing an Asynchronous ICommandand a event publication and subscription using the IEventAggregator. I'm hopingthat JustMock is CAL friendly.


Regards

Wessel

 


Ricky
Telerik team
 answered on 28 May 2010
5 answers
116 views


Hi There,

I ran into a few issues when I attempted to fake various SharePoint objects with the first Beta release of JustMock and am experiencing some different errors with the 2010.1.429 build.

I first tried a few simple tests (as seen below) and they worked as expected:
[TestMethod] 
[ExpectedException(typeof(ApplicationException))] 
public void Current_NotAvailable_ThrowsApplicationException() 
    // Arrange 
    Mock.Arrange(() => SPContext.Current).Throws(new ApplicationException("Not allowed to call SPContext.Current")); 
 
    // Act 
    SPContext currentContext = SPContext.Current; 
 
[TestMethod] 
public void Current_CurrentContextIsFake_ReturnsFakeSPContext() 
    // Arrange 
    var fakeContext = Mock.Create<SPContext>(); 
    Mock.Arrange(() => SPContext.Current).Returns(fakeContext); 
 
    // Act 
    SPContext currentContext = SPContext.Current; 
 
    // Assert 
    Assert.IsNotNull(currentContext, "The current SPContext should not be null"); 

I then wanted to try some of the chaining behavior, as this is needed to work with the SPContext object, so I followed your ShouldAssertNestedPropertySetups example

[TestMethod] 
public void ShouldAssertNestedPropertySetups() 
    var foo = Mock.Create<IFoo>(); 
     
    Mock.Arrange(() => foo.Bar.Value).Returns(10); 
 
    Assert.Equal(10, foo.Bar.Value); 

and created the following test

[TestMethod] 
public void SPWeb_AllowAnonymousAccess_ReturnsTrue() 
    // Arrange 
    var fakeContext = Mock.Create<SPContext>(); 
    Mock.Arrange(() => fakeContext.Web.AllowAnonymousAccess).Returns(true); 
 
    // Assert 
    Assert.IsTrue(fakeContext.Web.AllowAnonymousAccess, "Our SPWeb should allow anonymous access"); 

which pegs my CPU, takes 15 seconds to run, and fails with the following information:

Error Message:
Test method JustMockSharePointSamples.ComponentsTests.SPContextTests.SPWeb_AllowAnonymousAccess_ReturnsTrue threw exception:  System.NullReferenceException: Object reference not set to an instance of an object..

Error Stack Trace:
Microsoft.SharePoint.WebControls.SPControl.SPWebEnsureSPControl(HttpContext context)
Microsoft.SharePoint.WebControls.SPControl.GetContextWeb(HttpContext context)
Microsoft.SharePoint.SPContext.get_Web()
lambda_method(ExecutionScope )
Intercept(Expression`1 expression) in c:\B\Basilisk\Basilisk CI Build\Sources\CodeBase\Telerik.JustMock\MockContext.cs: line 72
TReturn](† instruction, Func2`2 function) in c:\B\Basilisk\Basilisk CI Build\Sources\CodeBase\Telerik.JustMock\MockContext.cs: line 173
Telerik.JustMock.Mock.Arrange[TResult](Expression`1 expression) in c:\B\Basilisk\Basilisk CI Build\Sources\CodeBase\Telerik.JustMock\Mock.cs: line 37
JustMockSharePointSamples.ComponentsTests.SPContextTests.SPWeb_AllowAnonymousAccess_ReturnsTrue() in C:\Projects\JustMockSharePointSamples\JustMockSharePointSamples.ComponentsTests\SPContextTests.cs: line 94

My Visual Studio 2008 (SP 1) Test Project is referencing the following libraries:
  • Microsoft.Office.Server
  • Microsoft.SharePoint
  • Microsoft.VisualStudio.QualityTools.UnitTestFramework
  • System
  • System.Core
  • System.Data
  • System.Web
  • System.XML
  • Telerik.JustMock

I then tried the following approach

[TestMethod] 
public void CurrentWeb_AllowAnonymousAccess_ReturnsTrue() 
    // Arrange 
    var fakeContext = Mock.Create<SPContext>(); 
    Mock.Arrange(() => SPContext.Current).Returns(fakeContext); 
 
    var fakeWeb = Mock.Create<SPWeb>(); 
    Mock.Arrange(() => fakeContext.Web).Returns(fakeWeb); 
    Mock.Arrange(() => fakeWeb.AllowAnonymousAccess).Returns(true); 
 
    // Assert 
    Assert.IsTrue(SPContext.Current.Web.AllowAnonymousAccess, "Anonymous access should be allowed on our current SPWeb"); 

and this test passes ... but my CPU pegs once again, and the test takes just over 40 seconds to run.

So, my questions are:
  1. Why is the first approach to chaining/recursive calls failing?
  2. Why is the test pegging my CPU and taking so long? When I run something similar with Typemock, it completes within seconds.

If you require any additional information, please let me know.

Thanks.
Mike
Ricky
Telerik team
 answered on 14 May 2010
1 answer
133 views
Hi,
I'm trying to mock out some functions in my repository. Some work, some don't. This is a combination of NUnit, NHibernate, and indirectly, ASP.NET MVC. I'm in the process of writing tests for a custom ASP.NET Membership provider I'm writing.

The test fixture setup, two tests and the various supporting code:
        [SetUp] 
        public void SetUp() 
        { 
            ServiceLocatorInitializer.Init(); 
            _provider = new NHibernateMembershipProvider(CreateMockUserRepository()); 
            var cs = ConfigurationManager.ConnectionStrings; 
            var config = new NameValueCollection 
                                             { 
                                                 {"applicationName""PerformanceTracker"}, 
                                                 {"name""NHibernateMembershipProvider"}, 
                                                 {"requiresQuestionAndAnswer""false"}, 
                                                 {"connectionStringName""membershipProviderConnectionString"
                                             }; 
 
            _provider.Initialize(config["name"], config); 
        } 
 
        // Doesn't work 
        [Test] 
        public void CanGetUserByEmail() 
        { 
            string email = "marykate2@gmail.com"
            string username = _provider.GetUserNameByEmail(email); // always null so it always fails. Repo mocked below 
            Assert.AreEqual("marykate2", username); 
        } 
 
        // Works fine 
        [Test] 
        public void CanGetUserByUserKey() 
        { 
            string email = "marykate2@gmail.com"
            MembershipUser usr = _provider.GetUser(Guid.Empty, false); 
            Assert.AreEqual(usr.Email, email); 
        } 
 
        private IRepositoryWithTypedId<User, Guid> CreateMockUserRepository() 
        { 
            var called = false
            var mockedDbContext = Mock.Create<IDbContext>(); 
            Mock.Arrange(() => mockedDbContext.BeginTransaction()).DoInstead(() => called = true); 
 
            var mockedRepository = Mock.Create<IRepositoryWithTypedId<User, Guid>>(); 
            Mock.Arrange( 
                () => 
                mockedRepository.Get(Arg.Any<Guid>())).Returns(CreateUser()); 
 
            Mock.Arrange( 
                () => 
                mockedRepository.FindOne(Arg.Any<IDictionary<stringobject>>())).Returns(CreateUser()); 
 
            Mock.Arrange(() => mockedRepository.DbContext).Returns(mockedDbContext); 
 
            return mockedRepository; 
        } 
 
        private User CreateUser() 
        { 
            User user = CreateTransientUser(); 
            EntityIdSetter.SetIdOf<Guid>          (user, new Guid(0x9b84e442, 0x125c, 0x487b, 0x9f, 0x17, 0x18, 0x26, 0xd8, 0xe4, 0x40, 0x72)); 
            return user; 
        } 
 
        /// <summary> 
        /// Creates a valid, transient User; typical of something retrieved back from a form submission 
        /// </summary> 
        private User CreateTransientUser() 
        { 
            User user = new User() 
            { 
                UserName = "marykate2"
                FirstName = "Mary"
                LastName = "Kate"
                LastActivityDate = new DateTime(), 
                Email = "marykate2@gmail.com" 
            }; 
 
            return user; 
        } 

And the method I'm trying to test:
        /// <summary> 
        /// Gets the user name associated with the specified e-mail address. 
        /// </summary> 
        /// <returns> 
        /// The user name associated with the specified e-mail address. If no match is found, return null. 
        /// </returns> 
        /// <param name="email">The e-mail address to search for. </param> 
        public override string GetUserNameByEmail(string email) 
        { 
            User user = null
            _userRepository.DbContext.BeginTransaction(); 
            try 
            { 
               user = _userRepository.FindOne(new Dictionary<stringobject> {{"Email", email}});
            } 
            catch (Exception e) 
            { 
                throw new ProviderException(e.Message); 
            } 
 
            if (user == null
                return String.Empty; 
            return user.UserName; 
        } 

So for whatever reason _userRepository.FindOne(new Dictionary<stringobject> {{"Email", email}}), the results are ALWAYS null. It seem the mock framework isn't intercepting this call, assuming I'm doing things correctly. Is there a better way to do this?

Thanks,
Jack
Ricky
Telerik team
 answered on 11 May 2010
4 answers
163 views
Environment:  VS2010 Premium official release, framework 3.5
Trying to mock a simple static function generates an exception "Ambiguous match found.".  This seems like basic functionality but we have only been able to mock Interfaces.  I tried searching for known issues, but couldn't seem to find bug reporting or anything on JustMock.

Below is the sample code:

    public class Foo
    {
        public static string StaticFunction(int x)
        {
            return x.ToString();
        }
    }

            Mock.CreateStatic<Foo>();

            Mock.Arrange(() => Foo.StaticFunction(10)).Returns("ten");
            //above line generates "Ambiguous match found" exception

            string s = Foo.StaticFunction(1);
            Assert.IsTrue(s == "ten");
Chris
Telerik team
 answered on 29 Apr 2010
3 answers
164 views
Issue 1:
I have VS 2008 running on Server 2008 R2 x64. Every time I start Visual Studio, I get a notification of a VSHOST crash and the faulting module is identified as the CodeWeaver module (which I believe is part of JustMocks).

Issue 2:
To install JustMocks on 2K8 i had to start a command line prompt in admin mode from which I could run the installer otherwise you get a message stating 'This JustMock package requires Visual Studio'

Issue 3:
I have Telerik Reporting, JustCode and JustMocks installed on my dev machine. This takes up a large part of my main menu bar in Visual Studio. Could you please rationalize the usage of the main menu to one item under which all Telerik products are installed.
Chris
Telerik team
 answered on 23 Apr 2010
1 answer
109 views
Anyone got any ideas on how I'd mock a call to a method that contains something similar to below. I realise I could mock the method call itself but I'm really after the method being entered and the linq statment returning values that don't actually exist in the db

using (OptimumWebRollEntities context = new OptimumWebRollEntities()) 
            { 
 
                returnList = (from u in context.OptimumUser 
                              where u.IsOptimumStaff == false 
                              && u.IsActive 
                              && u.Region.RegionId == regionId 
                              orderby u.Surname, u.FirstName 
                              select new data.ReportingEntities.Candidate() 
                              { 
                                  OptimumUserId = u.OptimumUserId, 
                                  FirstName = u.FirstName, 
                                  Surname = u.Surname 
                              }).ToList(); 
 
            } 
 

Chris
Telerik team
 answered on 20 Apr 2010
6 answers
227 views
I am evaluating the framework for mocking the IPluginExecutionContext interface that is critical to mocking Microsoft Crm Plug-ins.  This is a good test of the framework because on the same interface, I need a dictionary property to essentially be stubbed and then some methods to be mocked.  Also the property can use indexers to get to the values and there is only a getter for the interface, so I cannot just set the property to a new dictionary (actually the class is a custom Crm class called PropertyBag, but is similar to a dictionary).

I receive the error:
Test method Ryland.Crm.Plugins.Tests.ContactRequiredFieldsPluginTest.ExecuteRequiredFieldTelerikTest threw exception System.AccessViolationException, but exception Microsoft.Crm.Sdk.InvalidPluginExecutionException was expected. Exception message:  System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

Telerik.DynamicProxy.ProxyFactory.Create()
Telerik.DynamicProxy.Fluent.FluentProxy.NewInstance()
Telerik.DynamicProxy.Proxy.Create(Type target, Action`1 action)
ctor(Type target, BehaviorMode mode, Object[] args)
Telerik.JustMock.Mock.Create(Type target, BehaviorMode mode, Object[] args)
Telerik.JustMock.Mock.Create(Type target, Object[] args)
Telerik.JustMock.Mock.Create[T]()
Ryland.Crm.Plugins.Tests.ContactRequiredFieldsPluginTest.ExecuteRequiredFieldTelerikTest() in C:\projects\RylandStandards\RylandStandards\tests\Ryland.Crm.Plugins.Tests\ContactRequiredFieldsPluginTest.cs: line 58


My code is below.  Also note I am running on a Hyper-V Guest and do have references to other Mocking frameworks in the project since I am comparing and contrasting Rhino Mocks, Moq and JustMock.  I have JustMock enabled.  The Microsoft Crm sdk contains the IPluginExecutionContext and only the sdk is needed to test this scenario, not Crm.

If the syntax below works for this test, I will definitely recommend this framework.  The simplicity is great compared to RhinMocks and slightly better than Moq.  Understanding the API is important to adoption and the ability to avoid needing different calls for stubbing or mocking is very nice.  I also am assuming the typical Create will essentially cause properties to behave like simple get/set properties without any setup.

///

 

<summary>

 

 

///

 

 

///</summary>

 

[

TestMethod()]

 

[

ExpectedException(typeof(InvalidPluginExecutionException))]

 

 

public void ExecuteRequiredFieldTelerikTest()

 

{

 

 

 

ContactRequiredFieldsPlugin target = new ContactRequiredFieldsPlugin(string.Empty, string.Empty);

 

 

var context = TelerikMock.Mock.Create<IPluginExecutionContext>(); //!!!!!!!!! Fails here

 

 

var service = TelerikMock.Mock.Create<ICrmService>();

 

 

TelerikMock.Mock.Arrange(() => context.CreateCrmService(true)).Returns(service);

 

 

DynamicEntity

 

entity = new DynamicEntity(EntityName.contact.ToString());

 

entity.Properties.Add(

new StringProperty("telephone1", ""));

 

entity.Properties.Add(

new StringProperty("emailaddress1", ""));

 

 

 

context.InputParameters[

ParameterName.Target] = entity;

 

target.Execute(context);

 

 

}

Chris
Telerik team
 answered on 19 Apr 2010
3 answers
241 views
Hello.

I'm currently trying out JustMock to make a SharePoint Unit test.
However I have difficulties mocking SPSite and SPWeb objects.
Any advice?

The method that I'm trying to mock is roughly as follows:
SPSite site = SPContext.Current.Site; 
SPSecurity.RunWithElevatedPrivileges(delegate() { 
    using (SPSite mysite = new SPSite(site.ID)) { 
        using (SPWeb myweb = mysite.OpenWeb()) { 
            SPList = myweb.Lists["List_Name"]; 
            // do something else 
        } 
    } 
}); 
Ricky
Telerik team
 answered on 18 Apr 2010
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?