Telerik Forums
JustMock Forum
2 answers
95 views
Hello, I grabbed this example from docs and added virtual modifier to ReturnFive function because free version can't mock not virtual members.
As far as I understand this modification shouldn't influence test results, though this test fails with  "Expected: 7  But was:  5"
I can't find any explicit statement in docs about future mock feature support in free version, so I'm not sure if it's my fault or this feature is just not available.
Any help would be appreciated.
       
public class UserData
        {
            public virtual int ReturnFive()
            {
                return 5;
            }
        }
        [Test]
        public void ShouldArrangeReturnForFutureUserDataInstances()
        {
            // Arrange
            var fakeUsed = Mock.Create<UserData>();
            Mock.Arrange(() => fakeUsed.ReturnFive()).IgnoreInstance().Returns(7);

            // Assert
            Assert.AreEqual(7, fakeUsed.ReturnFive());
            Assert.AreEqual(7, new UserData().ReturnFive());
        }
vsevolod
Top achievements
Rank 1
 answered on 04 Mar 2015
13 answers
6.5K+ views

It's quite common that we will try to customise a Framework class but still reuse most of the logic from the base class. For example, we want to provide our own Navigation Provider inheriting from Microsoft.SharePoint.Navigation.SPNavigationProvider. And we want to override GetChildNodes class to add some addition site map node on top of the collection that base class return. So we will be calling base.GetChildNodes() from our GetChildNodes method.

Here is a simple example. The problem is I dont know how to reference the base class method in the Mock.Arrange method?

public class ParentClass
{
    public virtual int Sum()
    {
        return 0;
    }
}
public class ChildClass : ParentClass
{
    public override int Sum()
    {
        return 1 + base.Sum();
    }
}
[TestMethod]
public void RunChildClass()
{
    var childClass = new ChildClass();
    Mock.Arrange(() => childClass.Sum()).Returns(2); // want to override ParentClass.Sum(), not ChildClass.Sum().
    var result = childClass.Sum();
    Assert.IsTrue(result == 3); // instead I will get 2 here.
}
Stefan
Telerik team
 answered on 04 Mar 2015
7 answers
317 views
My general pattern for testing has been to use TestInitialize to set up mocks that are used by all tests, and then in TestCleanup to call AssertAll on each mocked object. However I have just discovered that this doesn't (always?) work. In one of my tests I put an Arrange on one of the mocked objects that I knew would never happen, but the call to AssertAll did not fail the test. However, if I move the AssertAll into the body of the test itself it does indeed fail as it should.
Is this a known bug, or am I doing something wrong? I have used this pattern for a lot of tests which it now seems may not be testing as rigorously as they should.
Kaloyan
Telerik team
 answered on 26 Feb 2015
12 answers
1.2K+ views
Dear sir,
Now I am in a new problem. I am unable to Mock Asynchronous Methods.

Here is my code which I try for :

 My Class :

 public class BaseRepository<T> : IRepositoryBase<T> where T : class, IEntity, new()
    {
        protected readonly DbContext InnerDbContext;
        protected DbSet<T> InnerDbSet;

        public BaseRepository(DbContext innerDbContext)
        {
            InnerDbContext = innerDbContext;
            InnerDbSet = InnerDbContext.Set<T>();
        }

        public virtual void Add(T entity)
        {
            InnerDbSet.Add(entity);
        }

        public virtual async Task UpdateAsync(T entity)
        {
            var newEntry = InnerDbContext.Entry(entity);
            if (newEntry.State != EntityState.Detached)
            {
                var oldEntity = await FindAsync(entity.Id);
                if (oldEntity == null)
                    throw new EntityNotFound();
                var attachEntity = InnerDbContext.Entry(oldEntity);
                attachEntity.CurrentValues.SetValues(newEntry);
            }
            else
            {
                newEntry.State = EntityState.Modified;
            }
        }

        public virtual async Task RemoveAsync(T entity)
        {
            entity.IsDelete = true;
            await UpdateAsync(entity);
        }

        public virtual IQueryable<T> All()
        {
            return InnerDbSet.Where(x => !x.IsDelete);
        }

        public virtual Task<T> FindAsync(long id)
        {
            return InnerDbSet.FirstOrDefaultAsync(x => x.Id == id && !x.IsDelete);
        }

        public virtual IQueryable<T> Search(Expression<Func<T, bool>> expression)
        {
            return InnerDbSet.Where(x => x.IsDelete)
                .Where(expression);
        }
    }

My Test :

       readonly TimeSketchContext _mockDataContext = Mock.Create<TimeSketchContext>();
        private readonly BaseRepository<EmployeeSkill> _repository;
        public BaseRepositoryTest()
        {
            _repository = new BaseRepository<EmployeeSkill>(_mockDataContext);
        }

        [Fact]
        public async void Find_Should_Call_Once()
        {
            await _repository.FindAsync(Arg.AnyInt);
            Mock.Assert(() => _mockDataContext.Set<EmployeeSkill>().FirstOrDefaultAsync(x => x.Id == Arg.AnyInt && !x.IsDelete), Occurs.Once());
            // Mock.Assert(() => _mockDataContext.Set<EmployeeSkill>().LastOrDefault(x => x.Id == Arg.AnyInt && !x.IsDelete), Occurs.Once());  test is pass !!!

        }
       above test is also  pass if  change this FirstOrDefaultAsync to LastOrDefault

        [Fact]
        public async void Update_Should_Call_Once()
        {
            var employeeSkill = GetEmployeeSkill();
            employeeSkill.SkillName = "Skill Update";
            await _repository.UpdateAsync(employeeSkill);
            Mock.Assert(() => _repository.FindAsync(Arg.AnyInt), Occurs.Once());
        }
   
       Same Problem.
        
       [Fact]
        public async void Remove_Should_Call_Update()
        {
            await _repository.RemoveAsync(Arg.IsAny<EmployeeSkill>());
            Mock.Assert(() => _repository.UpdateAsync(Arg.IsAny<EmployeeSkill>()), Occurs.Once());
        }

Thank`s in Advance.
Brandon Hunt
Top achievements
Rank 2
 answered on 17 Feb 2015
2 answers
589 views
I have been testing JustMock Lite as a replacement to RhinoMocks and converting some of our existing unit tests to learn the tool and asses if this is better.

I am using VB.NET, VS 2013 and .NET 4.

I came across this error after converting one particular unit test:

Result Message: System.Collections.Generic.KeyNotFoundException : The given key was not present in the dictionary.
Result StackTrace:
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at Telerik.JustMock.Core.Castle.DynamicProxy.Generators.Emitters.AbstractTypeEmitter.GetGenericArgumentsFor(MethodInfo genericMethod)
at Telerik.JustMock.Core.Castle.DynamicProxy.Generators.InvocationTypeGenerator.GetCallbackMethod(AbstractTypeEmitter invocation)
at Telerik.JustMock.Core.Castle.DynamicProxy.Generators.InvocationTypeGenerator.ImplementInvokeMethodOnTarget(AbstractTypeEmitter invocation, ParameterInfo[] parameters, MethodEmitter invokeMethodOnTarget, Reference targetField)
at Telerik.JustMock.Core.Castle.DynamicProxy.Generators.InvocationTypeGenerator.ImplemementInvokeMethodOnTarget(AbstractTypeEmitter invocation, ParameterInfo[] parameters, FieldReference targetField, MethodInfo callbackMethod)
at Telerik.JustMock.Core.Castle.DynamicProxy.Generators.InvocationTypeGenerator.Generate(ClassEmitter class, ProxyGenerationOptions options, INamingScope namingScope)
at Telerik.JustMock.Core.Castle.DynamicProxy.Contributors.ClassProxyTargetContributor.BuildInvocationType(MetaMethod method, ClassEmitter class, ProxyGenerationOptions options)
at Telerik.JustMock.Core.Castle.DynamicProxy.Contributors.ClassProxyTargetContributor.GetMethodGenerator(MetaMethod method, ClassEmitter class, ProxyGenerationOptions options, OverrideMethodDelegate overrideMethod)
at Telerik.JustMock.Core.Castle.DynamicProxy.Contributors.CompositeTypeContributor.ImplementMethod(MetaMethod method, ClassEmitter class, ProxyGenerationOptions options, OverrideMethodDelegate overrideMethod)
at Telerik.JustMock.Core.Castle.DynamicProxy.Contributors.CompositeTypeContributor.Generate(ClassEmitter class, ProxyGenerationOptions options)
at Telerik.JustMock.Core.Castle.DynamicProxy.Generators.ClassProxyGenerator.GenerateType(String name, Type[] interfaces, INamingScope namingScope)
at Telerik.JustMock.Core.Castle.DynamicProxy.Generators.ClassProxyGenerator.<>c__DisplayClass1.<GenerateCode>b__0(String n, INamingScope s)
at Telerik.JustMock.Core.Castle.DynamicProxy.Generators.BaseProxyGenerator.ObtainProxyType(CacheKey cacheKey, Func`3 factory)
at Telerik.JustMock.Core.Castle.DynamicProxy.Generators.ClassProxyGenerator.GenerateCode(Type[] interfaces, ProxyGenerationOptions options)
at Telerik.JustMock.Core.Castle.DynamicProxy.DefaultProxyBuilder.CreateClassProxyType(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options)
at Telerik.JustMock.Core.Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, Object[] constructorArguments, IInterceptor[] interceptors)
at Telerik.JustMock.Core.MocksRepository.Create(Type type, MockCreationSettings settings)
at Telerik.JustMock.MockBuilder.Create(MocksRepository repository, Type type, Object[] constructorArgs, Nullable`1 behavior, Type[] additionalMockedInterfaces, Nullable`1 mockConstructorCall, IEnumerable`1 additionalProxyTypeAttributes, List`1 supplementaryBehaviors, List`1 fallbackBehaviors, List`1 mixins, Expression`1 interceptorFilter)
at Telerik.JustMock.Mock.<>c__DisplayClass78`1.<Create>b__77()
at Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal[T](Func`1 guardedAction)
at Telerik.JustMock.Mock.Create[T](Behavior behavior)
at ConsoleApplication1.TestClass1.Test() in Temporary Projects\ConsoleApplication1\Class1.vb:line 27


After some trial and error I found out what the issue is and the following code will reproduce the error. The issue is that the implementation of an interface function that has generics uses a different variable name for the types. In the example below the interface method has TParent and TChild but when implemented the generic types are called ParentT and ChildT.

Imports NUnit.Framework
Imports Telerik.JustMock

Public Class Class1
    Implements myInterface

    Public Function myMethod(Of ParentT, ChildT)(a As ParentT) As ChildT Implements myInterface.myMethod
        Return Nothing
    End Function
End Class

Public Interface myInterface
    Function myMethod(Of TParent, TChild)(a As TParent) As TChild
End Interface

<TestFixture> _
Public Class TestClass1
    <Test> Public Sub Test()
        Dim c As Class1
        c = Mock.Create(Of Class1)(Behavior.RecursiveLoose)
    End Sub
End Class


I assume this is a bug or do we need to be more careful in our coding? RhinoMocks is able to handle this okay.

Thanks,
Sameer
Stefan
Telerik team
 answered on 17 Feb 2015
1 answer
271 views
I am not sure why my arrange call for a static method is trying to execute the original.

[Test]
public void RunCompleteDivxJob_Negative_Exception()
{
    DebugView.IsTraceEnabled = true;
    var mediaId = 2000999;
    var mediaTypeId = (int)CmtMediaType.Video;
    var queueCmtId = 9999;
    var cmtFileType = CmtFileType.SourceMediaFile;
    var statusError = CmtQueueStatus.Error;
    var exception = new Exception("test");
 
    // ARRANGE
    var encodeJobStateMachineManager = Mock.Create<EncodeJobStateMachineManager>(Behavior.CallOriginal);
    var logger = Mock.Create<Logger>(Behavior.CallOriginal, typeof(EncodeJobStateMachineManager));
    var inst = new PrivateAccessor(encodeJobStateMachineManager);
    inst.SetProperty("_log", logger);
    var createCompleteJobCalled = false;
    Mock.Arrange(() => DivxEncodeJob.CreateCompleteJob(mediaId, mediaTypeId, queueCmtId, cmtFileType))
        .DoInstead(() => createCompleteJobCalled = true);
    Mock.Arrange(() => encodeJobStateMachineManager.EncodeJob.Submit()).Throws(exception).MustBeCalled();
    logger.Arrange(x => x.Error(Arg.AnyString, exception)).MustBeCalled();
    //Mock.SetupStatic(typeof(QueueDAO));
    var updateQueueStatusCalled = false;
    Mock.Arrange(() => QueueDAO.UpdateQueueStatus(queueCmtId, statusError)).DoInstead(() =>  updateQueueStatusCalled = true);
 
    // ACT
    encodeJobStateMachineManager.RunCompleteDivxJob(mediaId, mediaTypeId, queueCmtId, cmtFileType);
 
    // ASSERT
    Mock.Assert(encodeJobStateMachineManager);
    Assert.IsTrue(createCompleteJobCalled);
    Assert.IsTrue(updateQueueStatusCalled);
}

The first static call is mocking the method call correctly:
Mock.Arrange(() => DivxEncodeJob.CreateCompleteJob(mediaId, mediaTypeId, queueCmtId, cmtFileType))
        .DoInstead(() => createCompleteJobCalled = true);

But the second static call is executing the original code:
Mock.Arrange(() => QueueDAO.UpdateQueueStatus(queueCmtId, statusError)).DoInstead(() => updateQueueStatusCalled = true);

These are essentially called exactly the same.  So why is the first one working as expected and the second not?

Stefan
Telerik team
 answered on 10 Feb 2015
3 answers
392 views
I have code that I want to test that looks similar to this:
01.public class Manager
02.{
03.    public Job Job {get;set;}
04. 
05.    public void RunCompleteJob(int arg1, int arg2, int arg3, string arg4)
06.    {
07.         Job = MyStaticClass.CreateCompleteJob(arg1, arg2, arg3, arg4);
08.         Job.Submit();
09.         ExecuteJobStates();
10.     }
11.}

I want to test this method, but I am getting stuck when I try to return an object when the static method is called.  Here is the test method:
01.[Test]
02.public void RunCompleteJob_Success()
03.{
04.    var arg1 = 2000999;
05.    var arg2 = 12345;
06.    var arg3 = 9999;
07.    var arg4 = "filepath;
08. 
09.    var manager = Mock.Create<Manager>(Behavior.CallOriginal);
10.    Mock.SetupStatic(typeof(MyStaticClass), Behavior.Strict, StaticConstructor.Mocked);
11.    Mock.Arrange(() => MyStaticClass.CreateCompleteJob(arg1, arg2, arg3, arg4))
12.        .Returns(new Job
13.            {
14.                JobProcessTypeParameters = new JobParameters(),
15.                JobType = JobType.Complete,
16.                MediaId = arg1
17.            });
18.    Mock.Arrange(() => manager.Job.Submit()).MustBeCalled();
19.    Mock.NonPublic.Arrange(manager, "ExecuteJobStates").MustBeCalled();
20. 
21.    manager.RunCompleteJob(arg1, arg2, arg3, arg4);
22. 
23.    Mock.Assert(manager);
24.    Assert.AreEqual(arg1, manager.Job.MediaId);
25.}

The last assert statement always returns an error saying that 2000999 does not equal 0.  Which implies that the Job property is not getting set the the new instance I am trying to return in the Arrange section.  

What am I doing wrong?  Is this something that can't be done as it is written?  Please help, I am new to the JustMock framework.
Stefan
Telerik team
 answered on 10 Feb 2015
3 answers
111 views
I have this code in my SUT:

            FarmLoggingService tempService = FarmLoggingService.Local;
            if (null != tempService)
            {
                tempService.Update();
            }
            else
            {
                tempService = new FarmLoggingService();
                tempService.Update();

                if (tempService.Status != SPObjectStatus.Online)
                    tempService.Provision();
            }

I'm trying to figure out how to mock the call to the FarmLoggingService constructor: tempService = new FarmLoggingService.

I've tried variations all similar to 
     Mock.Arrange( () => new FarmLoggingService() ).Returns(mockSvc);  

where mockSvc was created  like this: 
     var mockSvc = Mock.Create<FarmLoggingService>(Constructor.Mocked);

But nothing seems to be working.  Ultimately, I need to be able to check that Update and Provision were each called once.  I have it working to return null from FarmLoggingService.Local to force me into the else block, mock the return value from the Status property so it always calls Provision, but I can't get the constructor bit working right.

Any ideas?

Thanks,

Dave







Stefan
Telerik team
 answered on 02 Feb 2015
3 answers
76 views
Hello,

I am trying to use JustMock on a view-model in a silverlight application.  The structure of the solution is basically as follows:

Solution
    SilverlightApp.proj
        - ViewModels
            ViewModelX.cs
        -Views
            ViewX.xaml
            
     SIlverligthApp.Tests.proj
         ViewModelXFixture.cs

         
Both projects are Silverlight Class projects with Silverlight 5.  The test project is using NUnitLite 1.0  libraries (also tried it with NUnit3.0) and has a reference to Telerik.JustMock.Silverlight.dll.  I have a license for the commercial version but have not enabled the profiler.  A sample unit test is below:

[TestFixture]
public class Class1Fixture
{
  [Test]
  public void Len_Returns_Length()
  {
    //Arrange
    var mockDummy = Mock.Create<IDummy>();
    var x = new Class1(mockDummy);
 
    //Act
    var result = x.Len("test");
 
    //Assert
    Assert.AreEqual(4, result);
  }
}

And this is what I tried testing:

public interface IDummy
{ }
 
public class Class1
{
  public Class1(IDummy dummy)
  { }
  public int Len(string input)
  {
    if (string.IsNullOrWhiteSpace(input))
      return 0;
    return input.Length;
  }
}

But this is the error I get:

Tests1.Class1Fixture.Len_Returns_Length:
System.TypeInitializationException : The type initializer for 'Telerik.JustMock.Mock' threw an exception.
  ----> System.InvalidOperationException : Telerik.JustMock.Silverlight should only be used inside the Silverlight runtime. For all other runtimes reference Telerik.JustMock instead.

But since the test project is a SilverLight class library, I cannot add a reference to Telerik.JustMock.dll.

I'm sure I'm missing something but just can recognize it at the moment.  Any advice would be much appreciated.

Thanks,

Mike





Stefan
Telerik team
 answered on 30 Jan 2015
1 answer
229 views
using System;
using System.Threading.Tasks;
using Telerik.JustMock;
using Xunit;
 
namespace Test
{
    public class ClassTests
    {
        public interface IAsync
        {
            Task<String> MyTask();
        }
 
        [Fact]
        public async Task fails_due_to_timeout()
        {
            var mocked = Mock.Create<IAsync>();
 
            var result = await mocked.MyTask();
        }
 
        [Fact]
        public async Task passes()
        {
            var mocked = Mock.Create<IAsync>();
            Mock.Arrange(() => mocked.MyTask()).Returns(Task.FromResult<String>(null));
 
            var result = await mocked.MyTask();
        }
 
    }
}

I believe that the more useful auto-mocking behavior here would be for the returned task to be in a completed state containing an auto-mocked T.  For example, if the function to be mocked returns a Task<IMyInterface>, I believe the automocker should return the equivalent of Task.FromResult(Mock.Create<IMyInterface>()).

When writing async friendly code, the auto-mocker isn't very useful because none of my async methods never complete.  I have to manually Mock.Arrange every method so it will return a mocked Task.FromResult.  In most cases, I would prefer the happy path be default (tasks complete with results) rather than the unhappy path be the default.
Stefan
Telerik team
 answered on 19 Jan 2015
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?