Telerik Forums
JustMock Forum
3 answers
123 views
Hi!

Since I've updated my Visual Studio Premium 2012 to Update 2 (Version: 11.0.60315.01 Update2) following error message is shown when executing Unit-Tests:

Test method XY threw exception: Telerik.JustMock.MockException: Profiler must be enabled to mock/assert target XY method.

With Update 1 everything works fine. Thus, if I uninstall Update 2 the tests are running again. I've tried JustMock 2012.1.608.2 and JustMock Q1 2013 SP1.

Microsoft .NET Framework Version 4.5.50709

Unit-Test code
Line 10: Mock.SetupStatic(typeof(XY));
Line 11: Mock.Arrange(() => XY.XY()).Returns("xy");

Exception when Unit-Test code is executed
at Telerik.JustMock.Handlers.InterceptorHandler.Create(Object target, MethodInfo methodInfo, Boolean privateMethod)
  at Telerik.JustMock.MockContext`1.SetupMock(MockExpression`1 expression)
  at Telerik.JustMock.MockContext`1.SetupMock(Expression`1 expression)
  at Telerik.JustMock.Mock.<>c__DisplayClass1`1.<Arrange>b__0(MockContext`1 x)
  at Telerik.JustMock.MockContext.Setup(Instruction instruction, Func`2 function)
  at Telerik.JustMock.Mock.Arrange(Expression`1 expression)
  at XY() in XY.cs: line 11


This is a very important issue for me, because I want to migrate from Moles to JustMock.

Can anyone help? 

Thank you!
Kaloyan
Telerik team
 answered on 29 Apr 2013
1 answer
95 views
Hello,

I need to mock the DateTime.Now static method in mscorlib.  I've got it to work if it is in a non-static class.

(EXAMPLE CLASS)
class Program
{
    static void Main()
    {
        var results = new Program().CheckForY2K();
 
        Console.WriteLine(results);
        Console.Read();
    }
 
    internal bool CheckForY2K()
    {
        return DateTime.Now == new DateTime(2000, 1, 1);
    }
}

(EXAMPLE WORKING TEST)
[TestFixture]
public class NuintTest
{
   static NuintTest()
    {
        Mock.Replace(() => DateTime.Now).In<Program>(x => x.CheckForY2K());
    }
 
    [Test]
    public void TestY2K()
    {
        Mock.Arrange(() => DateTime.Now).Returns(new DateTime(2000, 1, 1));
        var results = new Program().CheckForY2K();
        Assert.IsTrue(results);
    }
}

But, I need it to work on static class

(ANOTHER EXAMPLE)
class Program
{
    static void Main()
    {
        var results = CheckForY2K();
 
        Console.WriteLine(results);
        Console.Read();
    }
 
    internal static bool CheckForY2K()
    {
        return DateTime.Now == new DateTime(2000, 1, 1);
    }
}

But this time, JustMock complains:
Mock.Replace(() => DateTime.Now).In<Program>(x => x.CheckForY2K());

That it cannot access static method "CheckForY2K" in non-static context.

What would the correct syntax be?  I cannot find an example.

Lee




Kaloyan
Telerik team
 answered on 26 Apr 2013
3 answers
1.3K+ views
Hi there,
I am testing method that inserts data into a table in the database and returns the ID.
My class(not the test class business logic class) is no way related to any wcf service but after inserting data my method calling context.savechanges() method then its validating my credentials. For the validation I have validation.cs. There its checking the headers
in the operation context. Is there anyway to get around the OperationContext. I am using JustMock 30 day Trial version. I tried the following code

 IContextChannel channel = null;

            var context = Mock.Create<OperationContext>(()=>new OperationContext(channel));
            OperationContext.Current = context;
            MessageHeader header = MessageHeader.CreateHeader(CustomHeader.Header, CustomHeader.HeaderNamespace, customHeader);
            Mock.Arrange(() => context.OutgoingMessageHeaders.Add(header));
I have been trying to solve this for the last 2 days.
Thank so much for ur help in advance
Kaloyan
Telerik team
 answered on 19 Apr 2013
10 answers
251 views
I have a simple test that is using MustBeCalled() to insure certain methods are called, but it also needs to know if they are called in the correct order. I thought InSequence() might do this, but it apparently does not, unless I'm not using it correctly. Is there a way to insure order?

Here is my test:

            ILGenerator gen = Mock.Create<ILGenerator>();
            ISnippetMgr mgr = Mock.Create<ISnippetMgr>();

            MethodInfo get_Item = typeof(Variables).GetProperty("Item", new Type[] { typeof(string) }).GetGetMethod();
            MethodInfo get_AsNumber = typeof(Variable).GetProperty("AsNumber").GetGetMethod();

            Mock.Arrange(() => gen.Emit(OpCodes.Ldarg_1)).MustBeCalled();
            Mock.Arrange(() => gen.Emit(OpCodes.Ldstr, "x")).MustBeCalled();
            Mock.Arrange(() => gen.Emit(OpCodes.Callvirt, get_Item)).MustBeCalled();
            Mock.Arrange(() => gen.Emit(OpCodes.Callvirt, get_AsNumber)).MustBeCalled();

            VarArray v = new VarArray("x", '+');
            v.GenItemCode(mgr, gen);

            Mock.Assert(gen);

Thanks
Kaloyan
Telerik team
 answered on 09 Apr 2013
5 answers
405 views
Hi,

I am getting Profiler must be enabled error on Mock.Arrange. I have the following code snippet.

[TestMethod]
        public void TestMethod2()
        {
            bool called = false;


            var bll = new FieldBLL();


            List<Field> fields = new List<Field>();
            fields.Add(new Field("custom100", "Bio", "Select"));


            Mock.Arrange(() => new FieldDAL().GetAllFields()).DoInstead(() => { called = true; })
                      .Returns(Fields);


            string name = bll.GetFirstFieldName();
            Assert.AreEqual(name, "custom100");
        }

Please let me know how I can fix this error.
thanks..
Kaloyan
Telerik team
 answered on 04 Apr 2013
1 answer
121 views
My sample code:

Assert.IsTrue(Mock.IsProfilerEnabled);
Mock.SetupStatic<RoleEnvironment>();            
Mock.Arrange(() => RoleEnvironment.CurrentRoleInstance.Id).Returns("TEST");

Error Msg: 

Method 'set_Id' in type 'RoleInstanceProxy+79c0aa98ec994a37a2e00052dd3aa3bd' from assembly 'Telerik.JustMock.DynamicStrong, Version=1.0.0.0, Culture=neutral, PublicKeyToken=8b221631f7271365' does not have an implementation.

StackTrace:

at System.Reflection.Emit.TypeBuilder.TermCreateClass(RuntimeModule module, Int32 tk, ObjectHandleOnStack type)
   at System.Reflection.Emit.TypeBuilder.CreateTypeNoLock()
   at System.Reflection.Emit.TypeBuilder.CreateType()
   at Telerik.JustMock.DynamicProxy.TypeEmitter.CreateType()
   at Telerik.JustMock.DynamicProxy.Proxy.CreateType()
   at Telerik.JustMock.DynamicProxy.ProxyFactory.Create()
   at Telerik.JustMock.DynamicProxy.Fluent.FluentProxy.NewInstance()
   at Telerik.JustMock.DynamicProxy.Proxy.Create(Type type, Action`1 action)
   at Telerik.JustMock.MockManager.CreateProxy(Type targetType, Container container)
   at Telerik.JustMock.MockManager.CreateProxy()
   at Telerik.JustMock.Utility.CreateMockWithEmptyArgs(Type target, Behavior behavior)
   at Telerik.JustMock.Interceptors.MethodInterceptor.OnMethodExecuting(MethodInvocation invocation)
   at Telerik.JustMock.Interceptors.MockInterceptor.OnExecution(MethodInvocation invocation)
   at Telerik.JustMock.Interceptors.MockInterceptor.Execute(MethodInvocation invocation)
   at Telerik.JustMock.Interceptors.MockInterceptor.Intercept(MockInvocation invocation)
   at Telerik.JustMock.Weaver.Interceptors.WeaverInterceptor.Telerik.JustMock.Weaver.Interceptors.Abstraction.IWeaverInterceptor.Intercept(IInvocation invocation)
   at Telerik.JustMock.Handlers.WeaverInterceptorHandler.Invoke(Object[] args)
   at Telerik.JustMock.MockContext`1.SetupMock(MockExpression`1 expression)
   at Telerik.JustMock.MockContext`1.SetupMock(Expression`1 expression)
   at Telerik.JustMock.Mock.<>c__DisplayClass1`1.<Arrange>b__0(MockContext`1 x)
   at Telerik.JustMock.MockContext.Setup[TDelgate,TReturn](Instruction instruction, Func`2 function)
   at Telerik.JustMock.Mock.Arrange[TResult](Expression`1 expression)





Kaloyan
Telerik team
 answered on 29 Mar 2013
7 answers
134 views
If I install JustMock I can't use Edit & Continue in a web application project.  Uninstalling it allows the use of Edit & Continue again.  When it's installed, Edit & Continue just pops up either the standard error message about changes not being allowed for various reasons which is the same message you get if you leave the project set for AnyCPU instead of x86.  This is even if everything is set correctly to allow for Edit & Continue.
Kaloyan
Telerik team
 answered on 29 Mar 2013
4 answers
216 views
Hi folks, I am trying to mock the SendMail windows workflow activity.

In this default workflow, the SmtpClient calls SendAsync(), and without a callback, the workflow just hangs forever.  So obviously, i need to fake out SendAsync() so that no email is sent, but I also want to 'DoInstead' and trigger the SendComplete event.  Am I missing anything obvious in my code snippet below?


        public UnitTestProject()
        {
        Mock.Replace<SmtpClient>(x => x.SendAsync(Arg.IsAny<MailMessage>(), null)).In<SendMail>();    
        }


        [TestMethod]
        public void TestSendMail()
        {   
            var smtpClient = new SmtpClient(Arg.AnyString);            
            var args = new System.ComponentModel.AsyncCompletedEventArgs(null, false, null);
                        
            Mock.Arrange(() => smtpClient.SendAsync(Arg.IsAny<MailMessage>(), null))
                        .IgnoreArguments()
                        .IgnoreInstance()
                        .DoInstead(
                        () => Mock.Raise(
                                () => smtpClient.SendCompleted += null, args)
                        );   // not raising the event ...
       
                                                  
            var wit = new WorkflowInvokerTest(new SendMail
            {
                Body = "BodyString",
                IsBodyHtml = true,
                CC = "email@example.com",
                To = "email@example.com",
                From = "email@example.com",
                Sender = "email@example.com",
                Subject = "Unit testing"
            });            
                        
            wit.TestActivity();
            Mock.Assert(smtpClient);
        }       


        
Kaloyan
Telerik team
 answered on 26 Mar 2013
2 answers
46 views
Sorry for the meaningless title, but I do have a general question on using JustMock.

Imagine the following SUT

public interface IDao
{
  // throws an exception on duplicate key
  void Insert(string key, string value);
  // throws an exception if key not available
  void Update(string key, string value);
  // throws an exception of key not found
  string FindByKey(string key);
}
 
public interface IService
{
  string Get(string key);
  void Set(string key, string value);
  // should insert or update the value for the given key
  void Save(string key, string value);
}
 
public class ServiceImpl : IService
{
  private readonly IDao _dao;
 
  public ServiceImpl(IDao dao)
  {
    _dao = dao;
  }
   
  public string Get(string key)
  {
    return _dao.FindById(key);
  }
 
  public void Set(string key, string value)
  {
    _dao.Insert(key, value);
  }
   
  public void Save(string key, string value)
  {
    var value = Get(key);
    if (null == value)
    {
      Set(key, value);
    }
    else
    {
      _dao.Update(key, value);
    }
  }
}

Now have a look at my test case for the save method:
[Test]
public void SaveShouldCallInsertOnNonExistingKey()
{
  var key = "key";
  var value = "value";
  var dao = Mock.Create<IDao>();
  dao.Arrange(x => x.Insert(Arg.AnyString,Arg.AnyString)).MustBeCalled();
  var service = Mock.Create<ServiceImpl>(Behaviour.CallOriginal, dao);
  service.Arrange(x => x.Get(Arg.AnyString)).Returns((string)null).MustBeCalled();
   
  service.Save(key, value);
   
  Mock.AssertAll(dao);
  Mock.AssertAll(service);
}

Running this test I get the error that Mock.AssertAll(dao) failed because the IDao.Insert method has never been called ?

Debugging through the test I could step into

service.Save()
-> service.Get() => returning NULL as expected
-> service.Set()
  -> dao.Insert (which is proxied)


What am I doing wrong here ?

Kind regards
Sebastian



Kaloyan
Telerik team
 answered on 25 Mar 2013
1 answer
100 views
We have many test projects that use Microsoft Moles extensively to detour/intercept calls to dependencies. Can JustMock perform detours in the same way Moles does, or does it require target classes to support some kind of dependency injection as I have seen in the examples so far? (I haven't studied JustMock extensively yet, just saw a few examples.) To be clear, for the time being, unfortunately, we need to test classes that do not support any sort of dependency injection (i.e., we can't modify the dependent classes yet), so we're not talking about just creating mocks here. Here's an example. It intercepts all calls to the GetError method on any instance of the SomeClass class. Can JustMock do stuff like this?
MSomeClass.AllInstances.GetError = (instance) =>
    {
        return string.Empty;
    };
Kaloyan
Telerik team
 answered on 18 Mar 2013
Narrow your results
Selected tags
Tags
+? more
Top users last month
Jay
Top achievements
Rank 3
Bronze
Iron
Iron
yw
Top achievements
Rank 2
Iron
Iron
Stefan
Top achievements
Rank 2
Iron
Iron
Iron
Kao Hung
Top achievements
Rank 1
Iron
Bohdan
Top achievements
Rank 2
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Jay
Top achievements
Rank 3
Bronze
Iron
Iron
yw
Top achievements
Rank 2
Iron
Iron
Stefan
Top achievements
Rank 2
Iron
Iron
Iron
Kao Hung
Top achievements
Rank 1
Iron
Bohdan
Top achievements
Rank 2
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?