Telerik Forums
JustMock Forum
3 answers
221 views
I have a class that takes a mocked object as a parameter.  When the class is invoked on the current thread, calls on the mocked object do nothing by virtue of the mock.  However if the class is run on another thread, the mocked object calls the actual methods instead of doing nothing.  Are mocked objects supported on background threads?

public class BackgroundThread 
{
  private Widget _widget;
  public BackgroundThread(Widget widget)
  {
    _widget = widget;
  }
  
  public void Run()
  {
    Console.WriteLine("widget="+_widget);
    _widget.DoSomething();
  }
}
  
public class Widget
{
  public void DoSomething()
  {
    throw new Exception("Not ready to do something");
  }
}
  
// Test Class
[TestMethod]
public void TestBackgroundThread()
{
  var widget = Mock.Create<Widget>();
  var bt = new BackgroundThread(widget);
  var thread = new Thread(bt.Run);
  thread.Start();
  Console.WriteLine("Thread started");
  thread.Join();  // Exception is thrown but should not because object was mocked
}
Ricky
Telerik team
 answered on 29 Aug 2012
1 answer
94 views
This scenario unexpectedly throws "shouldn't be here" exception which means methods are not mocked out.  As soon as you change method access from protected to public, all works as expected.  It seems that only public methods get mocked out.  Is this by design?  I would expect all methods to be mocked out unless I specify Behavior.CallOriginal.

public class Test1
{
    protected void Testing1()
    {
        string s = "Testing1";
        throw new Exception("shouldn't be here");
    }
}
 
public class Test2 : Test1
{
    protected void Testing2()
    {
        Testing1();
        string s = "Testing2";
        throw new Exception("shouldn't be here");
    }
}
 
public class Test3 : Test2
{
    protected void Testing3()
    {
        Testing1();
        Testing2();
        string s = "Testing3";
    }
}
 
 
    [Test]
    public void MakeSureAllMethodsAreMockedOut()
    {
        Test3 test3 = Mock.Create<Test3>();
 
        Mock.NonPublic.Arrange(test3, "Testing3").CallOriginal().MustBeCalled();
 
        test3.GetType().GetMethod("Testing3", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public).Invoke(test3, new object[] { });
    }
Here's simplified setup that also fails for the test above:
public class Test3
{
    protected void Testing1()
    {
        string s = "Testing1";
        throw new Exception("shouldn't be here");
    }
 
    public void Testing3()
    {
        Testing1();
        string s = "Testing3";
    }
}
Ricky
Telerik team
 answered on 27 Aug 2012
4 answers
127 views
I am mocking interface IRule and set it up as follows

public static IRule MakeMockRule(string description, string rulename, string propname, RuleSeverity severity, bool isbroke)
    {
        IRule mockRule = Mock.Create<IRule>();
        Mock.Arrange(() => mockRule.PropertyName).Returns(propname);
        Mock.Arrange(() => mockRule.RuleName).Returns(rulename);
        Mock.Arrange(() => mockRule.Severity).Returns(severity);
        Mock.Arrange(() => mockRule.IsBroken).Returns(isbroke);
        Mock.Arrange(() => mockRule.HandlesProperty(propname)).Returns(true);
        Mock.Arrange(() => mockRule.Description).Returns(description);
        return mockRule;
    }
And using version  2011.2.713.2 all tests using the above works.

I just upgraded to version 2012.2.813.9 and now when I call a method that uses the mocks .Equals method (for example List.Contains(rule)) it throws the following exception.

Test method Baseclass_Tests.BusinessRules_Test.IsBroken_Test threw exception: 
Telerik.JustMock.MockException: Could not call base for abstract Equals. Either remove the Behavior.CallOriginal specifier or add a setup for the expected call.

What do I need to do?
Ricky
Telerik team
 answered on 24 Aug 2012
7 answers
681 views
I have a simple scenario.  I'm trying to mock a base class that creates a Guid and sets that to a property in the ctor.  I thought I could do that with the following code; however, the mocked object is not calling the ctor.  The result is that my property is Guid.Empty and my unit test fails.

What do I need to do to make this work?  In the meantime, I've just created a concrete class to make my test pass.  However, I'd rather get away from that and use JustMock.

var source = Mock.Create<FooBase>(Constructor.Mocked);

Ricky
Telerik team
 answered on 23 Aug 2012
8 answers
399 views
When mocking a property of _commandLineArgument struct, I get 'Argument types do not match' exception.
When I make this struct a class(private class _commandLineArgument), everything works as expected.  Anybody can explain this behavior?  Anyway to make it work without making it a class.  Thank you.

public abstract class ConsoleBase
{
        private struct _commandLineArgument
        {
            public string Name { get; set; }
            public string Description { get; set; }
            public bool IsRequired { get; set; }
            public string Value { get; set; }
            public bool Found { get; set; }
        }
}
 
Type argType = Type.GetType( "Utilities.ConsoleBase+_commandLineArgument" );
Mock.NonPublic.Arrange<bool>( argType, "Found" ).Returns(true);
Ricky
Telerik team
 answered on 23 Aug 2012
3 answers
157 views
In my code I create a SharePoint site collection object (SPSite) using a url.
using (var siteCollection = new SPSite(spWebAppUri + siteUrl))
{
// more code...
}

So I want to mock that site collection object, but I dont know how to swap out a thing like that which is not referenced to anything that I can call statically like SPContext.Current.Web. In TypeMock it would be something like this...

// the next time a new instance of SPSite is created, use our fake one instead  
Isolate.Swap.NextInstance<SPSite>().With(fakeSite);

Thank you
Ricky
Telerik team
 answered on 23 Aug 2012
5 answers
148 views
Hello,

I am currently running into an issue where the arrange method returns the wrong value for the mock.  This does not occur all the time, but randomly, which seems to suggest a threading issue.  The "arrange" code that I have is as follow:

      IRTObjectModel model = Mock.Create<IRTObjectModel>();
 
      Mock.Arrange<TimeSpan>(() => model.ShiftDateStartTime)
        .Returns(shiftDateStartTime);
      Mock.Arrange<IDictionary<stringFuelBay>>(() => model.FuelBays)
        .Returns(initialTestData.ActiveFuelBays);
      Mock.Arrange<IDictionary<stringFuelTruck>>(() => model.FuelTrucks)
        .Returns(initialTestData.ActiveFuelTrucks);

However, sometimes I get the following error message:
System.InvalidCastException: Unable to cast object of type 'System.TimeSpan' to type 'FMFuelDispatch.Util.ObservableDictionary`2[System.String,FMFuelDispatch.Model.FuelBay]'.

According to the stack trace, it looks like there is something wrong with the proxy:
IRTObjectModel_Proxy_26c2fd2954ac4f68ba71390f3a22fa84._get_FuelBays(MethodInvocation , Int32 , Boolean )
IRTObjectModel_Proxy_26c2fd2954ac4f68ba71390f3a22fa84.get_FuelBays()
FMFuelDispatch.ViewModel.FuelScheduleViewModel.DataBindFuelSources(IRTObjectModel objModel, IDictionary`2 keyedResources, ResourceCollection resourceCollection) 

Based on the above, it looks like that calling the FuelBays property of my mock, returns the first arrange.  I am currently using the free edition of JustMock (v2011.3.1116.2).  Is there anything I can do to work around this problem?

Thanks.


-Carlos.
Ricky
Telerik team
 answered on 22 Aug 2012
1 answer
379 views
I want to put a Debug Assert into a function that I am giving to programmers so they make sure to pass the correct information into the routine when they code against it.  The problem is I want my test to be able to see that the assert happens.  The code in the routine will handle the invalid parameter correctly if it is compiled as is and sent to a user and the user will not get the assert because they get the released version.

What I want to do is have my tests run without the assert screen getting show while when the programmer runs it in the actual code, it gives them the assertion.

What I have done so far is:

using System.Diagnostics;
 
        [ClassInitialize()]
        public static void MyClassInitialize(
            TestContext testContext)
        {
            Mock.Initialize(typeof(Debug));
            Mock.Partial(typeof(Debug)).For<bool, string>((i, j) => Debug.Assert(i, j));
        }
 
        public void Test()
        {
            Mock.Arrange(() => Debug.Assert(Arg.AnyBool, Arg.AnyString)).DoNothing();
 
            DoSomeFunctionThatAsserts();
        }

The Assert screen still comes up.  I am not sure what I am missing in this process.  Can you guys help me out here?  Is this something that is possible or do I just have to remove the assert and throw an exception instead?

David Parvin
Mihail
Telerik team
 answered on 20 Aug 2012
3 answers
211 views
Hi,

I'm experiencing the following problem.
I'm trying to mock this class:

public class UnmockableClass<T>
    {
        private bool _dummyvariable;
  
        public UnmockableClass()
        {
            _dummyvariable = true;
        }
  
        public static UnmockableClass<T> GetInstance<TDescriptor>() where TDescriptor : IDescriptor<T>
        {
           throw new NotImplementedException();
        }
    }

inside this test

[TestClass]
    public class UnmockableClassTest
    {
        [TestMethod]
        public void SimpleTest()
        {
            Mock.SetupStatic<UnmockableClass<AvailableID>>();
            //nothing else. The test will fail with just this line of code above
  
        }
    }

But the test fails and I obtain this exception:
Test 'JustMockIssueTestMock.UnmockableClassTest.SimpleTest' failed: Test method JustMockIssueTestMock.UnmockableClassTest.SimpleTest threw exception: 
System.ArgumentException: GenericArguments[0], 'JustMockIssue.IDescriptor`1[T]', on 'JustMockIssue.UnmockableClass`1[JustMockIssue.AvailableID] GetInstance[TDescriptor]()' violates the constraint of type 'TDescriptor'. ---> System.Security.VerificationException: Method JustMockIssue.UnmockableClass`1[JustMockIssue.AvailableID].GetInstance: type argument 'JustMockIssue.IDescriptor`1[T]' violates the constraint of type parameter 'TDescriptor'.
    at System.RuntimeMethodHandle.GetStubIfNeeded(RuntimeMethodHandleInternal method, RuntimeType declaringType, RuntimeType[] methodInstantiation)
    at System.Reflection.RuntimeMethodInfo.MakeGenericMethod(Type[] methodInstantiation)
     --- End of inner exception stack trace ---
    at System.RuntimeType.ValidateGenericArguments(MemberInfo definition, RuntimeType[] genericArguments, Exception e)
    at System.Reflection.RuntimeMethodInfo.MakeGenericMethod(Type[] methodInstantiation)
    at Telerik.JustMock.Weaver.WeaverInterceptorBuilder.DefineInterceptor(MethodBase methodBase, FieldBuilder fldInterceptor, Type[] parameters)
    at Telerik.JustMock.Weaver.DynamicInjector.EmitInterceptor(ILGenerator il, MethodBase methodInfo)
    at Telerik.JustMock.Weaver.DynamicInjector.Inject(Type targetType, MethodBase methodBase, MethodInfo containerMethodInfo)
    at Telerik.JustMock.Weaver.DynamicInjector.Inject(Type targetType, MethodBase methodBase, MethodInfo injectingMethod, Boolean force)
    at Telerik.JustMock.Weaver.DynamicInjector.Inject(Type targetType, MethodBase methodBase)
    at Telerik.JustMock.MockManager.SetupMock(Behavior behavior, Boolean static)
    at Telerik.JustMock.MockManager.SetupStatic()
    at Telerik.JustMock.Mock.SetupStatic(Type targetType, Behavior behavior, StaticConstructor staticConstructor)
    at Telerik.JustMock.Mock.SetupStatic[T]()
    UnmockableClassTest.cs(17,0): at JustMockIssueTestMock.UnmockableClassTest.SimpleTest()

Do you have any idea why this happens? I wasn't able to find any help about this problem in the forum, except this one.

I'm working with JustMock Q2 2012 (trial version), VS2010 and Win7x64.
Thanks in advance
Livio
Ricky
Telerik team
 answered on 16 Aug 2012
16 answers
682 views
Hey Everyone,

I am trying to mock DateTime.Now and having some issues.  Below is my code
[Test]
public void datetime_test_justmock()
{
    var YEAR_2K = new DateTime(2000, 1, 1);
    Mock.Arrange(() => DateTime.Now).Returns(YEAR_2K);
    var actual = DateTime.Now;
    Assert.AreEqual(YEAR_2K, actual);
}

Actual gets sets to the current DateTime not the one I arranged.

Am I missing something.

Thanks,

-zd
Ricky
Telerik team
 answered on 10 Aug 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?