Telerik Forums
JustMock Forum
1 answer
84 views
I have a couple of calls like this in my class to be testet, here a snippet:
public void AddKeys(bool resultIsValid)
{
    if (!resultIsValid)
    {
       LogMyException(message);
    }
}

I'm absolutely sure that my code works. I think the problem might be that I call a method on a static member in the LogMyException method. Anyhow, when I run the tests one by one, it works everytime. If I run them all at once they sometimes pass, but sometimes they don't. The LogMyException method is a private method and I test if LogMyException gets called as follows:

public void Test()
{
    var called = false;
 
    // Initialize test class

    Mock.NonPublic.Arrange(confStringManager, "LogMyException"ArgExpr.IsAny<string>()).DoInstead(() => called = true);

    // Do something which makes the class call LogMyException
    Assert.True(called); }




Ricky
Telerik team
 answered on 01 Jun 2012
5 answers
180 views
I have a similar issue to these threads:
http://www.telerik.com/community/forums/justmock/general-discussions/mock-initialize.aspx
http://www.telerik.com/community/forums/justmock/general-discussions/mocks-failing-to-work-correctly-in-large-test-runs.aspx

My issue is with extension methods. I have an extension method for a list called RandomItem. As you could guess, it returns a random item from the list. Now I have a unit test on a function that uses the extension method. So I mock that extension method in the unit test so that I can determine what item comes back so I can verify the expectation. I can run that test by itself all day long and the mock works.

However, I have another set of tests that actually test the logic of the extension method. When these run with it then the mock on the extension method fails. Generally I would use something like Mock.Initialize or Mock.Partial but it wont even let me do something like this:
Mock.Initialize<List<ListExtensions>>()
because it is a static class. So I tried this stuff:

Mock.SetupStatic(typeof(ListExtensions));
Mock.Partial<List<IDataItem>>().For(x => x.RandomItem());
 
But it still fails. Any ideas?
Ricky
Telerik team
 answered on 01 Jun 2012
3 answers
637 views
I'm programming with the Windows Azure SDK and want to Mock the LocalResource object in my unit tests. Problem is that LocalResource is an abstract class that defines property set as internals. The Mock object/proxy does not implement these property set and an exception is thrown at runtime. Looks like a loophole in the language definition. How to write my unit tests?

var resource = Mock.Create<LocalResource>();
Mock.Arrange(() => RoleEnvironment.GetLocalResource("workingfolder")).Returns(resource);
Ricky
Telerik team
 answered on 29 May 2012
3 answers
196 views
I started using JustMock to mock my Linq To SQL (L2S) based repository. Everything works well for my Get operations; however, I am getting a consistent error when I attempt to mock for Insert operations.  The following is my code: 
var context = Mock.Create<MyDataContext>();
          var repository = new CustomerRepository(context);
          var customer = new Customer
              {
                  CustomerId = 0,
                  CompanyId = 1,
                  CustomerNo = "FAKE4",
                  FullName = "Isaac Fake4",
                  LastName = "Fake",
                  FirstName = "Isaac",
                  Sex = "M",
                  Birthdate = new DateTime(2000, 12, 1),
                  IsRecordActive = true,
                  IsRecordDeleted = false,
                  ModifiedOn = DateTime.Now,
                  ModifiedBy = "System.User"
              };
          
          Mock.Arrange(context.SubmitChanges).DoInstead(() =>
          { customer.CustomerId = 5; });
          
          //Act
           
          var actual = repository.Add(customer);
   
          //Assert
          Assert.AreEqual(5, actual.CustomerId);

The call to the Add method in the Customer repository is as follows:
public Customer Add(Customer customer)
       {
            
           this.context.Customer.InsertOnSubmit(customer);
           this.context.SubmitChanges();
           return customer;
       }

The system generates a NullReferenceException error on the InsertOnSubmit call and never gets to the SubmitChanges line.

I moved the same code to a console app for testing and it executed correctly (minus the JustMock embellishments of course).  What is the correct way to utilize JustMock to get the above code to test properly.

Ricky
Telerik team
 answered on 25 May 2012
1 answer
235 views
The reason I got JustMock was so that I could unit test my custom code for a Sitefinity 5 project. I needed it because the methods for interfacing with Sitefinity make prolific use of static classes. I am, however, unable to mock some things in Sitefinity. Here are some examples involving the PageManager:

When I try to do this (so that I can arrange PageManager.GetManager()):
Mock.SetupStatic(typeof(PageManager), StaticConstructor.NonMocked);

I get this: 
GenericArguments[1], 'TItem', on 'Telerik.Sitefinity.Data.GetQuery`2[TProvider,TItem]' violates the constraint of type parameter 'TItem'.

When I try to do this:
var pageManager = Mock.Create<PageManager>(Constructor.Mocked);

I get this: 
GenericArguments[0], 'Telerik.Sitefinity.GenericContent.Model.ILocatable', on 'Void Intercept[TItem](TItem, Boolean, Telerik.Sitefinity.Modules.GenericContent.ContentManagerBase`1[Telerik.Sitefinity.Modules.Pages.PageDataProvider], Boolean ByRef)' violates the constraint of type 'TItem'.

The eventual goal is for me to mock the call "GetPageNode" on the PageManager. Unfortunately, an interface containing that call is not provided on the PageManager.

Any ideas?
Ricky
Telerik team
 answered on 23 May 2012
8 answers
115 views
I have a class with multiple public methods in it. Some of these public methods call eachother. In an effort to issolate my tests I mock the calls to other methods in the same concrete class. I mock things up like this:

Mock.Initialize<PageService>();
var service = Mock.Create<PageService>();
Mock.Arrange(() => service.FirstCall()).CallOriginal();
Mock.Arrange(() => service.SecondCall()).returns(null);
service.FirstCall();

Now this works all fine and dandy but it kills my NCover code coverage. Before I changed to mocking the concrete calls I had perfect code coverage. Now the code coverage will show that only the first line of each method is covered. I would like to use JustMock concrete mocking to isolate my tests, but if it kills my metrics then it isn't worth it and I will have to resort to mocking up every object for every call. Is there some setting I am missing?

On a side note, mocking a concrete call messes up the debugger so that F10 jumps around the method, skipping lines and going to lines it isn't actually hitting. It pretty-much renders debugging it useless.

Erik
Top achievements
Rank 1
 answered on 22 May 2012
1 answer
59 views
Another question on MustBeCalled. Is there a way to assert a partial match of an argument?

For example, the first argument of the call to be asserted is an object which has 10 properties but I only care about 2 of them in the particular test case.

Thanks!

A failed attempt/example:

var accounts = ...
var target = Mock.Create<TargetClass>(Behavior.CallOriginal, accounts);

Mock.Arrange(() => target.TestCall(Arg.IsAny<Account>()).DoNothing();

target.Run(); // Will call internal TestCall for each account

foreach(var account in accounts)
Mock.Assert(() => target.TestCall(Arg.Matches<Account>(x => x.FirstName == account.FirstName && x.LastName == account.LastName), Occurs.Once());

Error is: Expected TargetClass.TestCall(Accoutn) call on the mock should be once, but it was called 0 times(s).

Any suggestion, please?
Ricky
Telerik team
 answered on 21 May 2012
1 answer
125 views
I have to verify multiple calls with different arguments to a method and MustBeCalled does the job.
Some pieces are missing, though.

For example, let's say I want to verify that the "Prompt(string text)" method is called just twice with the following two texts only: "hello", "world".

Mock.Arrange(() => foo.Prompt("hello")).DoNothing().MustBeCalled();
Mock.Arrange(() => foo.Prompt("world")).DoNothing().MustBeCalled(); 

How do I know that it wasn't called a third time with any other argument?

Thanks!

Also, I wanted to add that it's very annoying and especially time consuming not having any information about which MustBeCalled expectation failed.
Ricky
Telerik team
 answered on 21 May 2012
9 answers
128 views
I think I have discovered a bug.
    internal class InternalClass
    {
        public int GetInt() { return 5; }
    }
 
    internal class InternalOwner
    {
        public int GetInt() { return 5; }
        public InternalClass InternalClassField = new InternalClass();
 
        public InternalClass InternalClassProp
        {
            get { return InternalClassField; }
        }
    }
 
...
 
    [Test]
    public void Test5()
    {
        InternalOwner io = Mock.Create<InternalOwner>();
//      Mock.Arrange(() => io.GetInt()).Returns(6);     // Test1, works.
//      Mock.Arrange(() => io.InternalClassField.GetInt()).Returns(6);      // Test2, works.
        Mock.Arrange(() => io.InternalClassProp.GetInt()).Returns(6);       // Test3, FAILS.
    }
If you uncomment each of the lines Test1, Test2 and Test3 in turn you'll see that recursively mocking the GetInt() method via InternalClassProp fails.

Adding the InternalsVisibleto assembly attribute has no effect.

Ricky
Telerik team
 answered on 16 May 2012
1 answer
84 views
Hi,

I'm using JustMock Q1 2012 SP1 (2012.1.508.6) and when I try to create a mock of the same type as the one under test most of the test for the type are failing.
 

A simplified example of what I'm doing follows.
var mock = Mock.Create<MyTypeUnderTest>(Constructor.Mocked);
var target = new MyTypeUnderTest ();
target.TestMethod();

The only temporary solution I've found is to create the Mock with Behavior.CallOriginal.

Any solution for this?

Kind Regards,
Edoardo
Ricky
Telerik team
 answered on 15 May 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?