Telerik Forums
JustMock Forum
10 answers
237 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
395 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
113 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
119 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
188 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
43 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
92 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
3 answers
101 views
Hi,
We are currently evaluating JustMock against Moq.

For a silverlight project I want to test the view generation. For this I have a viewmodel interface
public interface IViewModel
{
        string DisplayName { get; }
        Brush BackgroundBrush { get; }
}

And a UserControl as xamlx:
<UserControl x:Class="View" [...]>
    <Grid x:Name="LayoutRoot" Background="{Binding Path=BackgroundBrush}">
        <Border BorderBrush="Black" BorderThickness="1">
            <TextBlock Text="{Binding Path=DisplayName}" />
        </Border>
    </Grid>
</UserControl>
 
The test looks like this:
[TestMethod]
[Asynchronous]
public void BindingTest_BackgroundBrushIsSet()
{
    var target = new View();
    var datacontextMock = Mock.Create<IViewModel>();
    var expectedBackground = new SolidColorBrush(Colors.Purple);
    target.DataContext = datacontextMock;
    Mock.Arrange(() => datacontextMock.BackgroundBrush).Returns(expectedBackground);
    Mock.Arrange(() => datacontextMock.DisplayName).Returns(string.Empty);
 
    AsyncWaitForFrameworkElementLoaded(target);
    AssertCallback
        (() =>
        {
            var layoutRoot = target.FindName<Grid>("LayoutRoot");
            Assert.AreEqual(expectedBackground, layoutRoot.Background);
        });
}

The test creates a View and waits for it to be loaded. Then the backgroundcolor is checked. It fails using JustMock (layoutRoot.Background is null), while it passes using Moq.
Looking at the Debug Output it tells that the Property BackgroundBrush could not be found on IViewModelProxy\+a45306a40f1f4947a9984002599ac998. Checking by hand the watch window gives me the proper type which only contains the mock framework properties. The same is true for a test checking DisplayName.

Is there anything I'm missing using JustMock?

Kaloyan
Telerik team
 answered on 18 Mar 2013
1 answer
27 views
Greetings,

I know that JustMock doesn't work directly with WP7 from reading this post, yet the proposed solution doesn't apply to WP8, as a Silverlight project won't allow me to add a WP8 assembly to it...

Is there any workaround to use JustMock with WP8 assemblies?

Thanks,

Pedro Lamas
Kaloyan
Telerik team
 answered on 18 Mar 2013
1 answer
81 views
I'm trying to get JustMock setup on our TFS server and I'm having an issue. I installed JustMock on our build server and then followed these steps http://www.telerik.com/help/justmock/integration-code-activity-workflow.html. Once that was finished I checked everything in and ran the build. I came back as failed with the following message,

TF215097: An error occurred while initializing a build for build definition \TOCO\BuildDefinitionTest: Cannot create unknown type '{http://schemas.microsoft.com/netfx/2009/xaml/activities}Variable({clr-namespace:Telerik.JustMock.Build.Workflow;assembly=Telerik.JustMock.Build.Workflow}ReturnCodes)'.

I made sure the Workflow library is in the directory that is referenced in the Version Control path to custom assemblies. 

Any ideas on why this is happening? 
Kaloyan
Telerik team
 answered on 12 Mar 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?