Telerik Forums
JustMock Forum
1 answer
46 views
Hello,
  could you show me an example of the following scenario?

class A
{
  public DoSomething() { B b = new B(23, "apple"); }
}

I want to assert A.DoSomething calls B's contructor with 23 and apple parameters.

Thanks,
Zsolt
Ricky
Telerik team
 answered on 26 Nov 2012
3 answers
115 views
I am facing a strange problem when executing unit testes using JustMockRunner from Exec task under CruiseControl.Net

The same command line make the test pass, but from inside the CruiseControl.Net the test failed.

I am using Future Mocking for this unit test.

I reviewed the event viewer and found no errors regarding Profile Loading, the test fails because it didn't use my Future mocking and calls the direct methods.

Below is the code I am using for future Mocking
[TestMethod]
public void Load_Default_Profile_For_New_User()
{
    var userProfileService = Mock.Create<UserProfileServiceBase>(Behavior.Loose);
 
    Mock.Arrange(() => userProfileService.GetByUserId(Arg.AnyInt)).IgnoreInstance().Returns<int>(id => { return null; });
    Mock.Arrange(() => userProfileService.Insert(Arg.IsAny<UserProfile>())).IgnoreInstance().Returns(true);
 
    Assert.IsTrue(Mock.IsProfilerEnabled, "Profiler not enabled");
    var userService = new PaXtreme.Services.UserService();
 
    var userProfile = userService.GetUserProfile(1);
    Assert.IsNotNull(userProfile);
    Assert.IsFalse(string.IsNullOrEmpty(userProfile.ProfileData));
}

This test uses Future mocking when running under VS 2012 and from command prompt

What I am missing!
Kaloyan
Telerik team
 answered on 26 Nov 2012
1 answer
152 views
Hi Guys,

I am new to JustMock. I downloaded Free Trial Version of this product and trying to isolate WCF RIA Webservices (elevated feature) for my silverlight application.

I setup everything and then i get "Could not create mock from sealed class when profiler is not enabled.". I checked for the below items

1. no other profiler products are in use.
2. all DLLs are registered properly, x86/x64.

Am i missing something else?
Kaloyan
Telerik team
 answered on 22 Nov 2012
26 answers
1.1K+ views
I recently upgraded from JustMock Free Q1 2011 to JustMock Free Q3 2011.  Since upgrading I am getting errors on some of my tests.
The errors are as follows.
Test method SPM150.Test.LogBenchmarkValueChangeTest.Test0020LogTransactionCalledWhenValuesDifferentCorrectParmetersVersion1 threw exception:
Telerik.JustMock.MockException: Profiler must be enabled to mock/assert target SPM150ControllerTestBase.get_AssetsServiceMock() method.

My take on this is that somehow JustMock thinks I am trying to use features that are only available in the Paid version....

The way we have our tests architected is that each method in the code that needs to be tested corresponds to a TestClass with all the needed Unit Tests within that test class for testing that method and only that method.  We also have a TestClass which acts as our base class for all the other TestClasses for the methods within a particular class in code.  This base class goes ahead and Mocks most if not all of the external dependencies (just Mock.Create) that the tests might use within it's TestInitialize method.  this way each time a method runs its getting fresh mocks....

So here is an example of the code.
First the Base Class
[TestClass]
    public class SPM150ControllerTestBase
    {
 
        public IAssetsService AssetsServiceMock { get; set; }
        public INavigationService NavigationServiceMock { get; set; }
        public ISPM150Service SPM150ServiceMock { get; set; }
        public IGlobalData GlobalDataMock { get; set; }
        public SPM150Controller Target { get; set; }
 
        [TestInitialize]
        public void TestInit()
        {
            AssetsServiceMock = Mock.Create<IAssetsService>();
            SPM150ServiceMock = Mock.Create<ISPM150Service>();
            NavigationServiceMock = Mock.Create<INavigationService>();
            GlobalDataMock = Mock.Create<IGlobalData>();
            Target = Mock.Create<SPM150Controller>(Behavior.CallOriginal, new object[] { AssetsServiceMock, SPM150ServiceMock, NavigationServiceMock, GlobalDataMock, null });
 
        }
 
    }


Now The class for the method under test.  with a failing method...

[TestClass]
   public class LogBenchmarkValueChangeTest : SPM150ControllerTestBase
   {
       private const string PassedSiteNumber = "12345";
       private const string PassedUserName = "Hi Bob!";
       private const string PassedPrefix = "EQ Item Update";
 
       
       [TestMethod]
       public void Test0020LogTransactionCalledWhenValuesDifferentCorrectParmetersVersion1()
       {
           var beforeValue = 100.0;
           var afterValue = 1002.0;
 
           var expectedActionString = "EQ List Item Benchmark value changed from [100.0] to [1002.0]";
 
           AssetsServiceMock.Arrange(asset => asset.LogTransaction(Arg.AnyString, Arg.AnyString, Arg.AnyString)).OccursOnce();
 
 
           Target.LogBenchmarkValueChange(PassedSiteNumber, afterValue, PassedUserName, PassedPrefix, beforeValue);
 
           AssetsServiceMock.Assert();
           Mock.Assert(() => AssetsServiceMock.LogTransaction(
               Arg.Matches<string>(site => site == PassedSiteNumber),
               Arg.Matches<string>(user => user == PassedUserName),
               Arg.Matches<string>(actionString => actionString == expectedActionString)));
       }

   }


Thank you


Edit 1:  I was able to determine the issue is related to whether or not the "Paid" version is installed and enabled or not.  When I install the trial for the paid version and enable it the exception goes away and things run. I also understand now that you can't mix Fluent Mocking/Assertion with the non fluent its either one or the other for each test.

Apparently something changed between Q1 2011 and Q3 2011 releases that make things we were doing completely fine in Q1 now require the paid version of Q3?  Any thoughts?

I would really like to upgrade to the Q3 release as it provides better support for the Fluent Arranging/Asserting (in particular the Fluent Assert method actually lets you pass in parameters and expectations....)  But if our tests are breaking because we don't currently have the paid version I can't use it.


Any ideas are greatly appreciated.
Kaloyan
Telerik team
 answered on 16 Nov 2012
3 answers
101 views
Hi,
I am using OAConnection and OACommand to return multiple result sets.
This is working fine. However, I am trying to unit test my code and am having problems mocking them.
I would rather not have to actually connect to the database, I just want to mock the connections and dbDataReader to return pre defined values set by mocking. If the only way to do this is to connect to the database I will do that, but I would still want to mock call for the stored proc.
I think I can use IngnoreInstance to mock the calls, but I am having two issues.
The first issue, is that I am not able to mock the OAConnection.
I might be able to get around this my setting the the connection info in the App.Config file and create an actual instance of the Entity model.
Of course this wil create an actual connection to the database, but I will do it if there is no other way.
Then I hope to be able to mock the OACommand and dbDataReader .

The second issue is that I am not sure how to mock the OACommand and dbDataReader .
Heres is a sample of the code I am trying to mock. Any help would be greatly appreciated.

EntitiesModel dbContext = new EntitiesModel();
if (dbContext != null)
{
    EntityName myEntity = EntityName();
         
    using (OAConnection connection = dbContext.Connection)
    {
        using (OACommand command = connection.CreateCommand())
        {
             command.CommandType = System.Data.CommandType.StoredProcedure;
             command.CommandText = "SpName";
 
             using (DbDataReader dataReader = command.ExecuteReader())
             {
                  if (dataReader.HasRows)
                  {
                       IEnumerable<EntityName> entityname = dbContext.Translate<EntityName>(dataReader);
                       foreach EntityName c in entityname
                       {
                           myEntity = dbContext.AttachCopy<EntityName>(c);
                       }
 
                  }
 
                 dataReader.NextResult();
                 if (dataReader.HasRows)
                 {
                      while (dataReader.Read())
                      {
                           this._myField = dataReader.GetString(1);
                       }
                  }
                  if (!dataReader.IsClosed)
                      dataReader.Close();
             }
        }
    }
 }
Ricky
Telerik team
 answered on 15 Nov 2012
3 answers
57 views
Hi,

is there a way for me to make sure my event in my class being tested is added to? For example, if the class I am tests has a method like:

public void Work(int count)
{
    if(count == 1)
    {
        MyEvent += new MyHandler(handleEvent);
    }
}

I want to test when 1 is passed in to this method the handler (any handler) is attched to Myevent. Is this possible?
Thanks

Graham
Kaloyan
Telerik team
 answered on 15 Nov 2012
1 answer
89 views
I am trying to use automocking to test a class that looks something like this:

class X
{
public X(int code, IFoo a, IBar b, IBaz c, ...) { ... } 
}

Using automocking how do I go about getting the int into the class under test?
Kaloyan
Telerik team
 answered on 15 Nov 2012
1 answer
116 views
Hi.

I have the following code snippet:
public class Class1
{
    public Class1()
    {
        Parameter = new VMParameter() { Token = 21 };
    }
 
    internal VMParameter Parameter { get; set; }
}
 
internal class VMParameter
{
    public int Token { get; set; }
}
 
// Unit Test
[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        var c = Mock.Create<Class1>(Behavior.CallOriginal);
        var p = Mock.Create<VMParameter>();
        p.Token = 1;
        Mock.Arrange(() => c.Parameter).Returns(p);
        Assert.AreEqual(c.Parameter.Token, 1);
    }
}

The error message is:
Test method TestProject1.UnitTest1.TestMethod1 threw exception: 
System.TypeAccessException: Attempt by method 'Class1_Interceptor_c1e1c12fbbc845f8a8921237e642d7ff.Intercept(TryJM.Class1, Boolean ByRef)' to access type 'TryJM.VMParameter' failed.

I've followed the instruction at http://www.telerik.com/help/justmock/basic-usage-mock-internal-types-via-proxy.html to add the InternalsVisibleTo to the Telerik.JustMock assembly.

My guess is that the interceptor class is generated dynamically and the 'assembly' of that dynamically generated type doesn't have the InternalsVisibleTo attribute applied to it.  Any suggestions for a workaround for this?

Ciao.
Muljadi Budiman.
Kaloyan
Telerik team
 answered on 13 Nov 2012
5 answers
341 views
Hi,
I'm having trouble when mocking methods from VirtualPathUtility class, i.e.VirtualPathUtility.ToAbsolute(...)

Here is a test sample :

    public class XTest
    {
        static XTest()
        {
            Mock.Replace(() => System.Web.VirtualPathUtility.ToAbsolute(Arg.AnyString)).In<XTest>(x => x.Test());
        }

        [Fact]
        public void Test()
        {
            Mock.SetupStatic(typeof(System.Web.VirtualPathUtility));
            Mock.Arrange(() => System.Web.VirtualPathUtility.ToAbsolute(Arg.AnyString)).Returns("absolute");

            string r = System.Web.VirtualPathUtility.ToAbsolute("test");

            Assert.Equal("absolute", r);
        }
    }

I've also tried using Mock.Initialize, Mock.Replace is static constructor but didn't help.
I'm always getting exception:

System.IO.FileNotFoundException : Could not load file or assembly 'Telerik.CodeWeaver.Api, Version=1.0.0.0, Culture=neutral, PublicKeyToken=87210992829a189d' or one of its dependencies. The system cannot find the file specified.

Any idea what am I doing wrong?

Thanks

Heiko
Ricky
Telerik team
 answered on 12 Nov 2012
1 answer
135 views
Hi.

I recently downloaded a sample project from this thread and it worked fine.

So, I started to make some modifications, adding this simple test method to the JustMockTest1 class:
[TestMethod]
public void ShouldAssertMockedGetAllCategories()
{
    NorthwindEntities entities = Mock.Create<NorthwindEntities>();
     
    Category category = new Category()
    {
        CategoryName = "Beer"
    };
    List<Category> allCategories = new List<Category>
    {
        category
    };       
     
    // Arrange           
    Mock.Arrange(() => entities.Categories).ReturnsCollection(allCategories);
 
    // Act
    List<Category> categoriesList= entities.Categories.ToList();
     
    // Assert
    Assert.AreEqual(1, categoriesList.Count);
    Assert.AreSame(category, categoriesList[0]);
}

Again, everything worked like a charm.

Since I don't access a ObjectContext directly I tried to make things a little bit real world like.

[TestMethod]
public void ShouldAssertMockedGetAllCategories()
{
    NorthwindEntities entities = Mock.Create<NorthwindEntities>();
     
    Category category = new Category()
    {
        CategoryName = "Beer"
    };
    List<Category> allCategories = new List<Category>
    {
        category
    };       
     
    // Arrange           
    Mock.Arrange(() => entities.Categories).IgnoreInstance().ReturnsCollection(allCategories);
 
    // Act
    //Some instance of some class calls the following lines of code somewhere, somehow. =)
    NorthwindEntities ne = new NorthwindEntities();
    List<Category> categoriesList = ne.Categories.ToList();
     
    // Assert
    Assert.AreEqual(1, categoriesList.Count);
    Assert.AreSame(category, categoriesList[0]);
}

 

Test passed. \o/

Oops! I forget to call Dispose(). Let's first try the default way to do that.

[TestMethod]
public void ShouldAssertMockedGetAllCategories()
{
    NorthwindEntities entities = Mock.Create<NorthwindEntities>();
 
    Category category = new Category()
    {
        CategoryName = "Beer"
    };
    List<Category> allCategories = new List<Category>
    {
        category
    };
 
    // Arrange           
    Mock.Arrange(() => entities.Categories).IgnoreInstance().ReturnsCollection(allCategories);
 
    // Act
    //Some instance of some class calls the following lines of code somewhere, somehow. =)
    List<Category> categoriesList;
    using (NorthwindEntities ne = new NorthwindEntities())
    {        
        categoriesList = ne.Categories.ToList();
    }
 
    // Assert
    Assert.AreEqual(1, categoriesList.Count);
    Assert.AreSame(category, categoriesList[0]);
}

Uh-oh. An Exception was thrown at the end of using block.

Even if I call Dispose() directly (instead of using the using statement), test fails for the same reason.

[TestMethod]
public void ShouldAssertMockedGetAllCategories()
{
    NorthwindEntities entities = Mock.Create<NorthwindEntities>();
 
    Category category = new Category()
    {
        CategoryName = "Beer"
    };
    List<Category> allCategories = new List<Category>
    {
        category
    };
 
    // Arrange           
    Mock.Arrange(() => entities.Categories).IgnoreInstance().ReturnsCollection(allCategories);
 
    // Act
    //Some instance of some class calls the following lines of code somewhere, somehow. =)
    NorthwindEntities ne = new NorthwindEntities();
    List<Category> categoriesList = ne.Categories.ToList();
    ne.Dispose();
 
    // Assert
    Assert.AreEqual(1, categoriesList.Count);
    Assert.AreSame(category, categoriesList[0]);
}

Am I missing something here?

Thanks in advance.

Ricky
Telerik team
 answered on 09 Nov 2012
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?