Telerik Forums
JustMock Forum
19 answers
283 views
Hello, 

I'm trying to make a setup on my TeamCity server with JustMock and dotCover. Unsuccessful, unfortunately.

When all three elements work together I'm getting "Profiler must be enabled" exception during tests phase (tests with static mocking).
I followed all recommendations from Telerik.
When I use TeamCity with JustMock  without  dotCover - tests are passing without a problem.
I'm also able to run tests without TeamCity (in Visual Studio or executing msbuild from console) using JustMock and dotCover together (on the same machine). No problem here.

But when I use all three together - "Profiler must be enabled" exception got raised.

I'm trying to use MSTest Build Step with
.NET Coverage enabled.

Do you have any recommendation on how to run it? May be someone had implemented this kind of configuration?

Thanks,

Alex




Kaloyan
Telerik team
 answered on 10 May 2013
5 answers
115 views
Hi,

I am working on an MVC 4 project againt .net 4.5 on Visual Studio 2012.  JustMock works great until I try to mock an extention method.
Here ist what I did:
- Installed JustMock from the msi file
- In Visual StudioTelerik\JustMock doesn't offer the menu "Enable JustMock"/"Disable JustMock" but "Enable Profiler" and "Disable Profiler".  Enabled is chosen.  (http://www.telerik.com/help/justmock/advanced-usage.html)
- Callling options I can select dot.cover (product from JetBrains)
I mock an extention method as recommended in the documentation (http://www.telerik.com/help/justmock/advanced-usage-extension-methods-mocking.html)

Mock.Arrange(() => projekte.WithPath(Arg.IsAny<IPrefetchPath2>())).Returns(projekte).MustBeCalled();

WithPath is the extention method.

The test fails
- first I get a message box that says "vstest.executionengine.exe has stopped working"
- i have to close the messagebox
- in the test explorer the following message is given: 

System.InvalidOperationException: There is no method 'WithPath' on type 'SupportClasses.QueryableExtensionMethods' that matches the specified arguments

Thank you for your support on this issue!


Kaloyan
Telerik team
 answered on 08 May 2013
1 answer
748 views
Hi, I am testing this piece of code:

public void SaveChanges()
       {
           try
           {
              //some code here
           }
           catch (MyException dbEValEx)
           {
               RaiseValidationError(dbEValEx);
           }
           catch (MySecondException dbUpdateException)
           {
               RaiseUpdateException(dbUpdateException);
           }
       }

What I would like is to force that exception in some way, right now I have tried this:

//Class to be tested
var fooUnitOfWork = Mock.Create<UnitOfWork>(Behavior.CallOriginal);
//Mock private method
Mock.NonPublic.Arrange(fooUnitOfWork, "RaiseValidationError", dbEntityValidationException).DoNothing().MustBeCalled();
//Execute method to test
fooUnitOfWork.SaveChanges();
Mock.Arrange(() => fooUnitOfWork.SaveChanges()).Throws(new DbEntityValidationException());
//Make sure that the RaiseDBValidationError is called
Mock.Assert(fooUnitOfWork);

Any ideas of how to do it?

Kaloyan
Telerik team
 answered on 07 May 2013
1 answer
155 views
Hi, I would like to test this static method:
public static class UnitOfWorkExtensions
{
 
        public static void SetSubCategory(this IOperationTracer tracer, string subCategory)
        {
            UnitOfWork unitOfWork = UnitOfWork.Current;
            if (unitOfWork != null && unitOfWork.CorrelationId != null)
            {
                tracer.SetSubCategory(UnitOfWork.Current.CorrelationId, subCategory);
            }
        }
}
I am implementing the test like this:
[TestMethod]
      public void SetSubCategoryTest()
      {
          Mock.SetupStatic(typeof(UnitOfWorkExtensions));
          IOperationTracer operationTracer = Mock.Create<OperationTracer>();
 
 
          Mock.Arrange(() => operationTracer.SetSubCategory(null, "subCategory")).DoNothing().OccursNever();
 
          UnitOfWorkExtensions.SetSubCategory(operationTracer, "subCategory");
          Mock.Assert(operationTracer);
 
          UnitOfWork.Current = new UnitOfWork();
          UnitOfWork.Current.CorrelationId = "11111";
 
          Mock.Arrange(() => operationTracer.SetSubCategory(null, "subCategory")).DoNothing().OccursOnce();
 
          UnitOfWorkExtensions.SetSubCategory(operationTracer, "subCategory");
          Mock.Assert(operationTracer);
 
      }
The test is failing and I don't have a clue why
Kaloyan
Telerik team
 answered on 07 May 2013
1 answer
82 views
Hi JustMock team,

I'm trying to test that methods are being called in the correct order. I have the following code in one of my tests:

 var busyMonitor = Mock.Create<IBusyMonitor>();
target.BusyMonitor = busyMonitor;
Mock.Arrange(() => busyMonitor.RegisterActivity(Arg.IsAny<BusyActivity>())).InOrder();
Mock.Arrange(() => busyMonitor.UnregisterActivity(Arg.IsAny<BusyActivity>())).InOrder();
target.DoSomethiing();

Mock.Assert(busyMonitor);

Calling target.DoSomething involves calling BusyMonitor.RegisterActivity and BusyMonitot.UnregisterActivity methods. However I'm getting an exception when target objject insance calls BusyMonitor.UnregisterActivity. 

The excepcion thrown is an ArgumentNullException with message:"Value cannot be null. Parameter name: source"
Kaloyan
Telerik team
 answered on 07 May 2013
11 answers
449 views
Hi,

I'm new to mocking and am playing with JustMock to mock Entity Framework 4. Therefore, my understanding of what I want to happen may be a reflection of my lack of understanding of mocking principles/implementation.

I have browsed around and found some resources, but they're not all that clear. Have seen:
What I want to do is establish a mock of my EF entities, and access them without database.

So far, I have:

var entitiesMock = Mock.Create<Entities>();

This still wants the ConnectionString to appear in the app.config file of the Test DLL, which I would hope wouldn't be required? Without it, the default constructor throws an exception. Question 1: So am I right in thinking any unit tests I mock in this way are dependant on the DB - sort of making it a bit pointless?

My next task is to create an object and add it to the mocked entities:

UserAccount userAccount = new UserAccount()
{
    Username = "UserName",
    Password = "Password"
};
 
// Arrange
List<UserAccount> userAccounts = new List<UserAccount>();
Mock.Arrange(() => entitiesMock.AddToUserAccounts(Arg.IsAny<UserAccount>())).DoInstead(()=>userAccounts.Add(userAccount));
             
// Act
entitiesMock.AddToUserAccounts(userAccount);
 
// Assert
Assert.AreEqual(1, userAccounts.Count);
Assert.AreSame(userAccount, userAccounts[0]);

I understand this, and my object does indeed appear in the userAccounts collection. Win.

So in my head, I have an entity framework entities collection that I have mocked and primed with a user account. I would like to pass that into another class:

Authentication authentication = new Authentication(entitiesMock);
UserAccount authenticatedUserAccount=authentication.Authenticate(userAccount.Username, userAccount.Password, Authentication.PasswordFormat.PlainText);
Assert.AreEqual(userAccount.Username, authenticatedUserAccount.Username);

This uses the EF Model to return the user and authenticate their details.

This leaves the Question 2: when this code runs, the UserAccounts collection within the mocked Entities object is (understandably) null. Where am I going wrong? Am I wrong to expect to be able to prime the mocked entities with a single object and be able to use that?

Any help appreciated, I've made time in my project to work on Mocking and I need to get to grips with this fast!

Nathan


Kaloyan
Telerik team
 answered on 07 May 2013
1 answer
100 views
I have a mock and have set up a call to DoInstead on it, something like this: -

Mock.Arrange(() => myService.Foo(Arg.AnyGuid))
   .DoInstead(new System.Action<System.Guid>(Console.WriteLine));

Later on in my test, I call an Assert on that same method: -

Mock.Assert(() => myService.Foo(Arg.AnyGuid), Occurs.Once());

When it hits the Assert line, my DoInstead handler suddenly gets fired. It's as if the Assertion is actually called the mock method like my production code has. Even worse, if I put a Match on the Arrange call e.g.

myService.Foo(Arg.Matches<Guid>(g => g != Guid.Empty))

but this is completely ignored and it still falls into the Console.WriteLine call.

At any rate, calls to Assert should not implicitly call DoInstead handlers that have already been set up.
Kaloyan
Telerik team
 answered on 30 Apr 2013
3 answers
116 views
Hi!

Since I've updated my Visual Studio Premium 2012 to Update 2 (Version: 11.0.60315.01 Update2) following error message is shown when executing Unit-Tests:

Test method XY threw exception: Telerik.JustMock.MockException: Profiler must be enabled to mock/assert target XY method.

With Update 1 everything works fine. Thus, if I uninstall Update 2 the tests are running again. I've tried JustMock 2012.1.608.2 and JustMock Q1 2013 SP1.

Microsoft .NET Framework Version 4.5.50709

Unit-Test code
Line 10: Mock.SetupStatic(typeof(XY));
Line 11: Mock.Arrange(() => XY.XY()).Returns("xy");

Exception when Unit-Test code is executed
at Telerik.JustMock.Handlers.InterceptorHandler.Create(Object target, MethodInfo methodInfo, Boolean privateMethod)
  at Telerik.JustMock.MockContext`1.SetupMock(MockExpression`1 expression)
  at Telerik.JustMock.MockContext`1.SetupMock(Expression`1 expression)
  at Telerik.JustMock.Mock.<>c__DisplayClass1`1.<Arrange>b__0(MockContext`1 x)
  at Telerik.JustMock.MockContext.Setup(Instruction instruction, Func`2 function)
  at Telerik.JustMock.Mock.Arrange(Expression`1 expression)
  at XY() in XY.cs: line 11


This is a very important issue for me, because I want to migrate from Moles to JustMock.

Can anyone help? 

Thank you!
Kaloyan
Telerik team
 answered on 29 Apr 2013
1 answer
95 views
Hello,

I need to mock the DateTime.Now static method in mscorlib.  I've got it to work if it is in a non-static class.

(EXAMPLE CLASS)
class Program
{
    static void Main()
    {
        var results = new Program().CheckForY2K();
 
        Console.WriteLine(results);
        Console.Read();
    }
 
    internal bool CheckForY2K()
    {
        return DateTime.Now == new DateTime(2000, 1, 1);
    }
}

(EXAMPLE WORKING TEST)
[TestFixture]
public class NuintTest
{
   static NuintTest()
    {
        Mock.Replace(() => DateTime.Now).In<Program>(x => x.CheckForY2K());
    }
 
    [Test]
    public void TestY2K()
    {
        Mock.Arrange(() => DateTime.Now).Returns(new DateTime(2000, 1, 1));
        var results = new Program().CheckForY2K();
        Assert.IsTrue(results);
    }
}

But, I need it to work on static class

(ANOTHER EXAMPLE)
class Program
{
    static void Main()
    {
        var results = CheckForY2K();
 
        Console.WriteLine(results);
        Console.Read();
    }
 
    internal static bool CheckForY2K()
    {
        return DateTime.Now == new DateTime(2000, 1, 1);
    }
}

But this time, JustMock complains:
Mock.Replace(() => DateTime.Now).In<Program>(x => x.CheckForY2K());

That it cannot access static method "CheckForY2K" in non-static context.

What would the correct syntax be?  I cannot find an example.

Lee




Kaloyan
Telerik team
 answered on 26 Apr 2013
3 answers
1.2K+ views
Hi there,
I am testing method that inserts data into a table in the database and returns the ID.
My class(not the test class business logic class) is no way related to any wcf service but after inserting data my method calling context.savechanges() method then its validating my credentials. For the validation I have validation.cs. There its checking the headers
in the operation context. Is there anyway to get around the OperationContext. I am using JustMock 30 day Trial version. I tried the following code

 IContextChannel channel = null;

            var context = Mock.Create<OperationContext>(()=>new OperationContext(channel));
            OperationContext.Current = context;
            MessageHeader header = MessageHeader.CreateHeader(CustomHeader.Header, CustomHeader.HeaderNamespace, customHeader);
            Mock.Arrange(() => context.OutgoingMessageHeaders.Add(header));
I have been trying to solve this for the last 2 days.
Thank so much for ur help in advance
Kaloyan
Telerik team
 answered on 19 Apr 2013
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?