Telerik Forums
JustMock Forum
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.2K+ 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
249 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
402 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
118 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
129 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
203 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
97 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
104 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
Narrow your results
Selected tags
Tags
+? more
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?