Telerik Forums
JustMock Forum
1 answer
94 views
Dear Telerik team,

my problem is the following: I have a static class called Context. Its data is needed in the system under test. I have two Test classes (let's say Foo and Bar). In Foo I use some methods to manually load all the stuff from the database into my Context. So I actually use it like it works in the real application. In Bar, though, I use static mocking to mock Context. Now it should look like follows:

  • If I load all the stuff from the database there is a CodeDictionary with a big amount of entries (Foo)
  • The mock is like Mock.Arrange(() => CodeDictionary[specificId]).Returns(specificValue) (Bar)

If I run them by theirselves everything works fine. But if a run both test classes at the same time they seem to interfere each other. If I debug the Bar class while running all the tests at the same time I just saw the this CodeDictionary is filled with the codes from the database. That's not the behaviour I expected. How could I get around with this? This post could not help me.
Ricky
Telerik team
 answered on 21 Jun 2012
1 answer
206 views
Normally you test, if an exception gets thrown in a certain method, as follows. 
I use FluentAssertions:

        [Fact]
        public void Exception_gets_thrown()
        {
            var foo = new Foo("validArgument");
 
            foo.Invoking(f => f.Bar(null))		// null is an invalid argument
               .ShouldThrow<ArgumentNullException>();
        }
But how to test if an exception gets thrown in the constructor. I just did it like this, but is there maybe a more appropriate way via FluentAssertions?


        [Fact]
        public void Constructor_throws_Exception()
        {
            Action a = () => new Foo(null);		// null is an invalid argument
            a.ShouldThrow<ArgumentNullException>();
        }
Ricky
Telerik team
 answered on 08 Jun 2012
1 answer
87 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
190 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
663 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
214 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
244 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
64 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
138 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
Narrow your results
Selected tags
Tags
+? more
Top users last month
Jay
Top achievements
Rank 3
Bronze
Iron
Iron
yw
Top achievements
Rank 2
Iron
Iron
Stefan
Top achievements
Rank 2
Iron
Iron
Iron
Kao Hung
Top achievements
Rank 1
Iron
Bohdan
Top achievements
Rank 2
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Jay
Top achievements
Rank 3
Bronze
Iron
Iron
yw
Top achievements
Rank 2
Iron
Iron
Stefan
Top achievements
Rank 2
Iron
Iron
Iron
Kao Hung
Top achievements
Rank 1
Iron
Bohdan
Top achievements
Rank 2
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?