Telerik Forums
JustMock Forum
3 answers
3.2K+ views
I have the following class, I use this class to assign functionality to another class.  How do I mock the "PrivatelyDoWork" method using JustMock?  I also want to Assert that the "DoPrivateWork" has been call for a certain number of occurances.  Thanks.
internal class MyClass
{
    private MyClass()
    {
    }
 
    private void PrivatelyDoWork(string stringValue)
    {
    }
 
    public static Action<object> HowMyClassWorks()
    {
        return (myString) => new MyClass().PrivatelyDoWork((string)myString);
    }
}
Kaloyan
Telerik team
 answered on 06 Nov 2013
1 answer
111 views
I have some legacy code I am trying to migrate to Just Mock.  There are some static objects that many of our older tests reference.  I am slowly starting to re-write these tests with Static Mocking.

How can I have some of my tests use the mocked static while others continue using the old un-mocked static?  Ideally, I would like some code I can put either at the end of my test, in a using statement, or in my test/fixture teardown that would revert the static object to its original state and cause the next call to it to execute the static constructor/initialization.

Something like this:

class MyClass
{
    public static int SomeStatic { getprivate set;}
    static MyClass()
    {
        SomeStatic = 15;
    }
}
 
[Test]
public void foo()
{
    using (Mock.SetupStatic(typeof(MyClass), Behavior.StrictStaticConstructor.Mocked));
    {
        Mock.Arrange(() => MyClass.SomeStatic).Returns(5);
        Assert.AreEqual(5, MyClass.SomeStatic);
    }
    Assert.AreEqual(15, MyClass.SomeStatic);
}
Kaloyan
Telerik team
 answered on 06 Nov 2013
7 answers
114 views
The temporary solution was to uninstall the version Q3 2013 of JustMock.

I rised a ticket here: http://feedback.telerik.com/Project/105/Feedback/Details/63749-unable-to-debug-asp-net-projects-with-q3-2013

I hope the problem will be fixed soon.


Regards,
Ovidiu
Kaloyan
Telerik team
 answered on 01 Nov 2013
5 answers
309 views
I am testing a private method using JustMock and that works fine. However, to verify the method worked correctly, I need to pull the value of a public property that the private method loads. Basically, the constructor loads a set of configuration XML documents and exposes them through a public property of a configuration class. 

So I am able to mock the private method that is executed from the contrstructor (InitializeFile) and it works fine.  But I want to create a couple of asserts to verify the public property has the values that it should and that it is not empty. But since I have mocked a private method, I don't have a way to get to the public property. At least I do not see how to do that and none of the examples I have come across this show this.

Here's the test I have come up with so far.  The GetProperty() fails becuase the property is a public property and I have mocked up a PrivateAccessor.  So what do you have to do to mock a priviate method, but also have access to get the value of a public property... or can you with JusMock?

 public void LoadConfiguartionSettingsTest()
 {
     // Arrange
     var inst = PrivateAccessor.ForType(typeof(Configuration));
     var xdoc = (XDocument)inst.CallMethod("InitializeFile");

     
// Act
     inst.CallMethod("LoadConfiguartionSettings", new object[] { xdoc });
     var resp = inst.GetProperty("AppSettings");  // This fails... I guess because it is a public property.

     
// Assert
     Assert.IsNotNull(resp);
     Assert.IsInstanceOfType(resp, typeof(List<AppSetting>));
 }
Kaloyan
Telerik team
 answered on 25 Oct 2013
1 answer
508 views
Hi I am trying to mock a Property that is of type DataServiceQuery<EntityLock> like this:

locksViewModel.Query = Mock.Create<DataServiceQuery<EntityLock>>();
 as soon as I try to execute this line I am getting the next exception:

Initialization method Tgw.Wcs.Windows.U.Test.ComponentTests.Modules.LoadCarriers.LocksViewModelTest.TestInitialize threw exception. System.TypeInitializationException: System.TypeInitializationException: The type initializer for 'System.Data.Services.Client.DataServiceQuery`1' threw an exception. ---> System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

I have also tried not to Mock this property and initialize it in the constructor of the class that I am trying to test:

here is part of the constructor:

public LocksViewModel(IEnumerable<LoadCarrier> selectedLoadCarriers, ILoadCarrierRepository loadCarrierRepository)
      {
          if (selectedLoadCarriers != null && loadCarrierRepository != null)
          {
              DataContext = loadCarrierRepository.DataModelServiceContext;
              Query = (DataServiceQuery<EntityLock>)loadCarrierRepository.GetEntityLocks(selectedLoadCarriers.Select(x=>x.Id));


And here is part of my InitializeTest:
IQueryable<EntityLock> entityLocks = Mock.Create<IQueryable<EntityLock>>();
 
           LoadCarrierRepository loadCarrierRepository = Mock.Create<LoadCarrierRepository>();
           loadCarrierRepository.DataContext = Mock.Create<ClientDataModelServiceContext>();
            
 
           Mock.Arrange(() => loadCarrierRepository.GetEntityLocks(Arg.IsAny<IEnumerable<Guid>>())).ReturnsCollection(entityLocks);
           Mock.Arrange(() => loadCarrierRepository.GetLockReasons()).ReturnsCollection(new List<string> { "fooLockReason1", "fooLockReason2" });
           locksViewModel = new LocksViewModel(new ObservableCollectionEx<LoadCarrier>() { loadCarrier }, loadCarrierRepository);
And I am getting this exception: Initialization method Tgw.Wcs.Windows.U.Test.ComponentTests.Modules.LoadCarriers.LocksViewModelTest .TestInitialize threw exception. System.InvalidCastException: System.InvalidCastException: Unable to cast object of type 'Castle.Proxies.IQueryable`1Proxy' to type 'System.Data.Services.Client.DataServiceQuery`1[Tgw.Wcs.Windows.Data.UIModel.EntityLock]'..
Kaloyan
Telerik team
 answered on 25 Oct 2013
1 answer
248 views
Hi,

I have a test that have a Parallel.For in it. If I remove the Parallel.For, works fine, but if I try to do it in a parallel way I get an exception like if the Mocks where not applied.

Exception:

Test method Tgw.Wcs.StorageAndInventory.U.Test.Core.LoadCarrierManagerTest.UpdateLoadCarrierLocksLoadCarrier threw exception: 
System.AggregateException: One or more errors occurred. ---> System.InvalidOperationException: No connection string named 'StorageAndInventoryContext' could be found in the application config file.

Is like after the first thread is launched the rest of them cannot get the Mocked object...

[TestInitialize]
       public void Initialize()
       {
           loadCarrierManager = new LoadCarrierManager();
           loadCarrier = new LoadCarrier { Name = "LC1" };
           //Creates a number of elements
           loadCarriers = CreateLoadCarriers(numberOfLoadcarriers);
            
           //First Mock the SIS Context
           storageAndInventoryContext = Mock.Create<StorageAndInventoryContext>(() => new StorageAndInventoryContext("Non"),
                                                       Behavior.CallOriginal);
           //Mock the GetContext so it will return out Mocked element
           Mock.Arrange(() => StorageAndInventoryContextProvider.GetContext())
               .Returns(storageAndInventoryContext);
 
           Mock.Arrange(() => storageAndInventoryContext.InventoryAccountSet.OfType<LoadCarrier>())
              .ReturnsCollection(loadCarriers);
       }
 
 
 
       [TestMethod]
       [TestCategory(TgwTestingCategories.ServiceTest)]
       [WorkItem(11126)]
       public void UpdateLoadCarrierLocksLoadCarrier()
       {
 
          Parallel.For((long)0, 3, i =>
               {
                   using (var scope = new UnitOfWorkScope())
                   {
                       for (int lcCount = numberOfLoadcarriers-1; lcCount > 0; lcCount--)
                       {
                           string lcName = string.Format("LC{0}", lcCount);
 
                           LoadCarrierChangeSet loadCarrierChangeSet = new LoadCarrierChangeSet();
 
                           var lcToUpdate = loadCarrierManager.GetLoadCarrierData(lcName);
 
                           loadCarrierChangeSet.Locks = new LockChangeSet("fooReason", "fooDescription");
 
                           loadCarrierManager.UpdateLoadCarrier(lcToUpdate.Name, loadCarrierChangeSet);
                       }
 
                       scope.Complete();
                   }
             });
 
           using (new UnitOfWorkScope())
           {
 
               var badEntityLocksDescriptions =
                   storageAndInventoryContext.InventoryAccountSet.OfType<LoadCarrier>()
                                             .Select(x => x.EntityLocks.Where(y=>y.Description == "fooReason"));
 
 
               Assert.AreEqual(100, badEntityLocksDescriptions.Count());
           }
       }



Kaloyan
Telerik team
 answered on 25 Oct 2013
2 answers
67 views
We upgraded to Visual Studio 2013 and along with it, the latest version of JustMock (2013.3.1015.0)

After the upgrade, 3 of our tests started failing.

The code that kills it:

var sp = new ClaimsPrincipal();
        Mock.Arrange(() => sp.FindFirst("CONTROLLER/CONTROLLER")).Returns(new Claim("CONTROLLER/CONTROLLER", "0"));
        Mock.Arrange(() => System.Threading.Thread.CurrentPrincipal)
                .IgnoreInstance()
                .Returns(sp);

The exception it throws:

Telerik.JustMock.MockException: Type System.Threading.Thread does not support mocking of static members due to limitations in CLR.




It blows on the bolded line, which worked previously...

We have attached JustMock to 2013 CodeCoverage/Intellitrace profiler options, but there is no Visual Studio 2013 Profiler selectable as there was with VS2012.  (I believe the elevated permissions are working as expected, because all of our other .Net mscorelib tests are passing fine)

Any thoughts?


Kaloyan
Telerik team
 answered on 25 Oct 2013
4 answers
174 views
For 11/140 tests we are using JusMock. I just installed the latest version. When I enable the profiler and run all test though, they all break.  I have VS2010 ultimate and VS2013 ultimate. This is the error I am getting.

Test Name:  BackButtonTest
Test FullName:  BBA.POS.Test.NewTransactionViewModelTest.BackButtonTest
Test Source:    c:\TFS\POS\POSApp\v3-Phase2\Source\BBA.POS.Test\NewTransactionViewModelTest.cs : line 995
Test Outcome:   Failed
Test Duration:  0:00:00.7688022
 
Result Message:
Test method BBA.POS.Test.NewTransactionViewModelTest.BackButtonTest threw exception:
System.TypeInitializationException: The type initializer for '“•.’•' threw an exception. ---> System.ArgumentNullException: Value cannot be null.
Parameter name: field
TestCleanup method BBA.POS.Test.NewTransactionViewModelTest.MyTestCleanup threw exception. System.TypeInitializationException: System.TypeInitializationException: The type initializer for '“•.’•' threw an exception. ---> System.ArgumentNullException: Value cannot be null.
Parameter name: field.
Result StackTrace: 
at System.Dynamic.Utils.ContractUtils.RequiresNotNull(Object value, String paramName)
   at System.Linq.Expressions.Expression.Field(Expression expression, FieldInfo field)
   at “•.’•.[](String •, Func`1& , Action`1& ™)
   at “•.’•..cctor()
 --- End of inner exception stack trace ---
    at “•.’•.Š•(Action ‹•)
   at Telerik.JustMock.Mock.Reset()
   at BBA.POS.Test.NewTransactionViewModelTest.BackButtonTest() in c:\TFS\POS\POSApp\v3-Phase2\Source\BBA.POS.Test\NewTransactionViewModelTest.cs:line 241
 
TestCleanup Stack Trace
    at System.Dynamic.Utils.ContractUtils.RequiresNotNull(Object value, String paramName)
   at System.Linq.Expressions.Expression.Field(Expression expression, FieldInfo field)
   at “•.’•.[](String •, Func`1& , Action`1& ™)
   at “•.’•..cctor()
 --- End of inner exception stack trace ---
    at “•.’•.Š•(Action ‹•)
   at Telerik.JustMock.Mock.Reset()
   at BBA.POS.Test.NewTransactionViewModelTest.MyTestCleanup() in c:\TFS\POS\POSApp\v3-Phase2\Source\BBA.POS.Test\NewTransactionViewModelTest.cs:line 99

When i disable the profiler, all of the non-justmock tests pass but the 11 fail. When I check in my code the build server says all tests pass, so I know it's just something on my machine causing the problem. Does anyone know how to fix this?



Kaloyan
Telerik team
 answered on 21 Oct 2013
2 answers
176 views
Please refer to the next posting, as I have removed this one.
Stefan
Telerik team
 answered on 16 Oct 2013
7 answers
440 views
I can't figure out how to Assert the number of occurrences on a static Mock.  The below doesn't work.
Mock.SetupStatic(typeof(DataAccess), StaticConstructor.Mocked);
Mock.Arrange(() => DataAccess.IsRequestAuthenticate(null))
    .IgnoreArguments().IgnoreInstance()
    .Returns(true)
    .OccursOnce();
 
Mock.Assert(() => DataAccess.IsRequestAuthenticate(null));
Kaloyan
Telerik team
 answered on 11 Oct 2013
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?