Telerik Forums
JustMock Forum
6 answers
503 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
2 answers
230 views
I'm attempting to mock a private method that has an argument passed by ref.  The Mock.NonPublic.Arrange() is throing an ArgumentException with the message "Could not resolve the target method; make sure that you have provided arguments correctly."

Regardless of how I set up the arguments in the test, it can't seem to match the function.  Is there a workaround?  Here's a sample method signature:
private void PrivateMethodWith1ArgByRef(ref object arg)

The test calls Mock.NonPublic.Arrange() as follows:
Mock.NonPublic.Arrange(class1, "PrivateMethodWith1ArgByRef", ArgExpr.IsNull<object>()).DoNothing();

Instead of IsNull<object>(), I tried IsAny<object>(), I tried passing in a variable of type object, and I tried passing in typeof(object).

In the interim, is there some kind of a workaround?
Aaron
Top achievements
Rank 1
 answered on 14 Dec 2012
6 answers
112 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
205 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
153 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
197 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
149 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
107 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
119 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
8 answers
154 views
I am attempting to run dotCover with JustMock.  I attempted to follow the directions from a previous thread and I always get no results in the output file.  If I take out the JustMockRunner (commenting out the JustMock calls), I get the expected results.

Here is the stuff from the coverage.xml
<TargetExecutable>C:\Program Files\Telerik\JustMock\Libraries\JustMockRunner.exe</TargetExecutable>
<TargetArguments>"C:\Program Files\NUnit 2.5.10\bin\net-2.0\nunit-console.exe" TestLibrary.UnitTests.dll</TargetArguments>
<TargetWorkingDir>F:\users\eric\documents\visual studio 2010\Projects\TestLibrary\TestLibrary.UnitTests\bin\Debug</TargetWorkingDir>
<ReportType>HTML</ReportType>
<Output>output.html</Output>
What am I doing wrong here?

Thanks,
Eric
Software
Top achievements
Rank 1
 answered on 30 Nov 2012
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?