Telerik Forums
JustMock Forum
1 answer
69 views
I am completely new to Just Mock, and for that matter, fairly new to the VS Unit Testing framework. As naive newcomer, I'd welcome any pointers to step-by-step tutorials for setting up unit tests and then using Just Mock properly.
I have set up a test project, and created a test class, so that's mainly done I guess.
But how exactly does one proceed to mock up, say, Windows calls that are made by private methods in the target class?
I'm truly a babe in the woods here. So when I say I'm looking for "step-by-step tutorials", I mean on the order of "Just Mock Just For Idiots". :)
Thanks
Vladi
Telerik team
 answered on 24 Jan 2013
1 answer
122 views
Since the 2012 Q3 release of JustMock, generic methods called on mocks created with CallOriginal fail if they are not arranged.

Here's a test to prove the failure (using xUnit):
public class JustMockFixture
{
    [Fact]
    public void CallOriginal_UnmockedGenericMethod_CallOriginalMock_ThrowsException()
    {
        var obj = Mock.Create<TestClass>(Behavior.CallOriginal);
 
        Should.NotThrow(() => obj.Load<string>(new[] { "1", "2", "3" }));
    }
}
 
internal class TestClass
{
    public T[] Load<T>(string[] ids)
    {
        throw new NotImplementedException();
    }
}

The exception is as follows:

System.NotSupportedException
Cannot create arrays of TypedReference, ArgIterator, ByRef, or RuntimeArgumentHandle Objects.
   at System.Array.InternalCreate(Void* elementType, Int32 rank, Int32* pLengths, Int32* pLowerBounds)
   at System.Array.CreateInstance(Type elementType, Int32 length)
   at Telerik.JustMock.Utility.GetDefaultValue(Type target)
   at Telerik.JustMock.Weaver.WeaverInvocation.SetReturn(Object value)
   at TestClass_Interceptor_cdc31f27c78a442fbc59c6faf3dfdb68.Intercept<T>(String[], TestClass, ref Boolean)
   at JustMockFail.TestClass.Load(String[] ids) in TestClass.cs: line 15
   at JustMockFail.JustMockFixture.CallOriginal_UnmockedMethod_ThrowsException() in JustMockFixture.cs: line 15
Kaloyan
Telerik team
 answered on 10 Jan 2013
6 answers
520 views
Hello,
do you have any simple examples how to use JustMock with Entity Framework and DBContext?

Regards
Dirk

Kaloyan
Telerik team
 answered on 18 Dec 2012
6 answers
118 views
Hi!

I new to doing Test Driven Development.  I have a class factory that I am writing tests for.  The class factory returns a different type of class depending on the underlying properties of the persistence in the data layer.  The data layer is being implemented in an OpenAccess Model.

Here is an example set of code:

public class FooFactory
{
    public static IFoo CreateFoo(int barKey)
    {
        using (FooBarModel foom = new FooBarModel())
        {
            Bar barEntity = foom.Bars.Where(n => n.BarKey == barKey).FirstOrDefault();
            // For this example, I will assume the bar record always exists.
            if (barEntity.IsIron)
            {
                return new IronFoo();
            }
            else if (barEntity.IsGold)
            {
                return new GoldenFoo();
            }
            else
            {
                return new LeadFoo();
            }
        }
    }
}

How do I go about setting up a Mock so that instead of the FooBarModel being directly called, I can have mocked type used that specifies the barEntity.IsIron property returns true?

I do have another way I can go about this, but I don't really like it.  I may also be missing the main idea on how to use the JustMock.

Thanks,
j.
Ricky
Telerik team
 answered on 11 Dec 2012
2 answers
216 views
I'm trying to Mock my Linq To Sql database context, with little luck:

System.InvalidCastException:
'System.Collections.Generic.List`1[My.Models.Person]' to type 'System.Data.Linq.Table`1[My.Models.Person]'

var logic = new PersonLogic();
var context = Mock.Create<DataContext>();
 
var persons= new List<Person>();
persons.Add(new Person());
 
Mock.Arrange(() => (IEnumerable<Person>)context.Persons).Returns(persons);
Mock.NonPublic.Arrange<DataContext>(logic, "context").Returns(context);
 
Person returned = logic.GetPerson(1);
Assert.Equals(returned.ID, 1);

How do I mock System.Data.Linq.Table? Where am I going wrong.
Kaloyan
Telerik team
 answered on 10 Dec 2012
5 answers
161 views
Hi guys,

I'm pleased to say that JustMock is the only mocking framework I've actually got to work with Win8 Store/"Metro" projects

However, whenever there is a problem, instead of a detailed error I get:
Test method Win8Proto.Tests.WhenUserIsNotAuthenticated.ThenTryParseOAuthCallbackUrlIsCalled threw exception: <br>System.Resources.MissingManifestResourceException:
Unable to load resources for resource file "Telerik.JustMock.Messages" in package "97A458C7-A0AA-4BC7-B8FA-D9F82394A7BE".<
br>   
at System.Resources.ResourceManager.GetString(String name, CultureInfo culture)<
br>   at Telerik.JustMock.Messages.get_ExpectedCallIsNeverInvoked()<br>   
at Telerik.JustMock.MockAssertion.AssertValidator.ValidateExpectations(MethodInstance methodInstance, Int32 numberofTimeExecuted)<
br>   
at Telerik.JustMock.MockAssertion.AssertValidator.ToExceptionString(MethodInstance methodInstance)<
br>   
at Telerik.JustMock.MockAssertion.AssertValidator.Validate()<
br>   at Telerik.JustMock.MockAssertion.Assert(MethodInstance instance, Filter filter)<br>   
at Telerik.JustMock.Mock.AssertInternal(Occurs occurs)<
br>   at Telerik.JustMock.Helpers.FluentHelper.<>c__DisplayClass7`2.<Assert>b__6(MockContext`1 x)<br>   
at Telerik.JustMock.MockContext.Setup(Instruction instruction, Action`1 action)<
br>   at Telerik.JustMock.Helpers.FluentHelper.Assert(T obj, Expression`1 expression, Occurs occurs)<br>   
at Telerik.JustMock.Helpers.FluentHelper.Assert(T obj, Expression`1 action)<
br>   at Win8Proto.Tests.WhenUserIsNotAuthenticated.ThenTryParseOAuthCallbackUrlIsCalled() in WithMockFacebookClient.cs: line 104<br>
<
div></div>


and so on. It doesn't matter what the error actually is

I've got the sample Just Mock projects working fine, and I can generally debug to work out what the actual problem/test failure is

what do you reckon?

Toby
Top achievements
Rank 1
 answered on 05 Dec 2012
1 answer
204 views
I tried to use JustMock Replace technique to replace the Print method of  System.Drawing.Printing.PrintDocument.

In class Initialize
Mock.Replace<System.Drawing.Printing.PrintDocument>(p => p.Print()).In<PrintJobTest>(t => t.Ensure_Print_Job_Folder_Name());

and in my unit test method arranged the PrintDocument.Print as follows:

var printDocument = new System.Drawing.Printing.PrintDocument();
Mock.Arrange(() => printDocument.Print()).IgnoreInstance().DoNothing();

When PrintDocument object instatiated under the class to be tested, it throws the following exception when calling the PrintDocument.Print method

Could not load file or assembly 'Telerik.CodeWeaver.Api, Version=1.0.0.0, Culture=neutral, PublicKeyToken=87210992829a189d' or one of its dependencies. The system cannot find the file specified.

This error occurs when running the test using MSTest runner, but if I used JustCode test runner everything run ok and no exception thrown

And no errors in the event viewer regarding the profiler:
.NET Runtime version 4.0.30319.17929 - The profiler was loaded successfully.  Profiler CLSID: '{b7abe522-a68f-44f2-925b-81e7488e9ec0}'.  Process ID (decimal): 6368.  Message ID: [0x2507].

Is this a problem whenmocking the System.Drawing.Printing.PrintDocument?

Please help I am facing many troubles with JustMock and my unit tests using MSTest runner.

If this a test runner problem, do you suggest a replacement?
Kaloyan
Telerik team
 answered on 05 Dec 2012
5 answers
156 views
I am getting the following exception thrown when I attempt to instantiate a class that is a windows form control: 
Method 'OnFrameWindowActivate' on type 'PortalControlProxy+1d48ab8d01e14d88b1961be6f78a21fb' from assembly 'Telerik.JustMock, Version=1.0.0.0, Culture=neutral, PublicKeyToken=8b221631f7271365' is overriding a method that is not visible from that assembly.

The line of code that is causing the exception is: 
PortalControl mockedPortalControl = Mock.Create<PortalControl>(Constructor.Mocked);

The PortalControl is a Winform control. It appears that during instantiation the exception is being thrown.  Any ideas?

Thank you in advance,
Ken
Kaloyan
Telerik team
 answered on 05 Dec 2012
1 answer
114 views
Here is a snippet of my test code:

private PendingListViewModel _vm;
 
        [TestInitialize]
        public void Setup()
        {
            var view = Mock.Create<IPendingListView>();
            var repository = Mock.Create<ISubmissionRepository>();
            repository.Arrange(x => x.GetPendingSubmissions()).Returns(GetSubmissionSet());
 
            var subscribedEvent = Mock.Create<RefreshPendingSubmissions>();
            subscribedEvent.Arrange(x => x.Subscribe(Arg.IsAny<Action<string>>())).DoNothing();
            var events = Mock.Create<IEventAggregator>();
            events.Arrange(x => x.GetEvent<RefreshPendingSubmissions>()).Returns(subscribedEvent);
            _vm = new PendingListViewModel(view, repository, events);
        }
        [TestMethod]
        public void ExecuteSortByCountyCommand_CollectionShouldContainOneSortDescriptor()
        {
            _vm.SortCountyCommand.Execute("ASC");
            Assert.IsTrue(_vm.SubmissionsCollection.SortDescriptions.Count == 1);
        }

When I do this I get an exception:

System.IO.FileLoadException: System.IO.FileLoadException: Could not load file or assembly 'Telerik.JustMock_fe91bf8a4e2f4132a3849f92ab689d67, Version=2012.3.1025.4, Culture=neutral, PublicKeyToken=null' or one of its dependencies. A strongly-named assembly is required. (Exception from HRESULT: 0x80131044).
    at Microsoft.Practices.Prism.Events.CompositePresentationEvent`1.Subscribe(Action`1 action)
   at Complaints.Modules.Web.ViewModels.PendingListViewModel..ctor(IPendingListView view, ISubmissionRepository subRepository, IEventAggregator events) in PendingListViewModel.cs: line 73

If I remove the code that creates and arranges subscribedEvent and leave the mocked event aggregator alone (just create, no arranging), then the same line of code returns a NullReferenceException.

The problem line of code is :
_events.GetEvent<RefreshPendingSubmissions>().Subscribe(a => OnRefresh());

in the constructor of my Class under test.

I had the same issues when I used a Mocking Container, so I switched to creating all the mocks individually, but it's still not working.

What am I doing wrong?
Ricky
Telerik team
 answered on 30 Nov 2012
1 answer
125 views
I have an enum declared as

public enum SubdivisionTypeCode : byte
    {
        None = 255,
        State = 0,
        County = 1,
        City = 2,
        Village = 3,
        Township = 4,
        CitySchoolDistrict = 5,
        SchoolDistrict = 6,
        JtVocSchoolDistrict = 7,
        Miscellaneous = 8,
        University = 9,
        PooledFinancing = 10
    }

when I try to use that in a parameter in a Mocking Arrange, it doesn't match and the mock doesn't get called correctly.
public interface ISubdivisionTypeRepository
{
    ISubdivisionType Get(SubdivisionTypeCode subdivisionTypeCode);
}
 
...
[Test]
var subdivisionTypeCode = SubdivisionTypeCode.City;
var subdivisionType = new SubdivisionType(subdivisionTypeCode: SubdivisionTypeCode.City);
var subdivisionTypeRepository = Mock.Create<ISubdivisionTypeRepository>();
Mock.Arrange(() => subdivisionTypeRepository.Get(subdivisionTypeCode)).Returns(subdivisionType);
 
var s = subdivisionTypeRepository.Get(subdivisionTypeCode);
In this case s returns null.  

If I remove the type from the enum (or change it to int) the above code returns the correct instance as expected.

Thanks,
Eric
Ricky
Telerik team
 answered on 30 Nov 2012
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?