Telerik Forums
JustMock Forum
1 answer
92 views
I confess up front that of all of the hundreds of skills I've had to learn over the years, at this point I'm still not up on unit testing.  I haven't used the tools once, haven't read a book or done my homework on this one, and don't know AAA from the company that tows my car.  In JustMock I think I see a tool that can help with common development.  I just don't want to have to research another paradigm like unit testing (yet) in order to use what seems like a great tool.  But all of the examples seem to be completely based on unit testing.

Here is an example of how I'd like to use JustMock.  I have an ASP.NET app that makes synchronous WebRequests out to other sites to aggregate results.  My code might look something like this:

IList<ClassA> GetGridData(string info) {
  IList<ClassA> list  = LibraryX.DoSomething(info);  // web request done in here
  if (list.Count == 0)
    list = null;
  return list;
}

The problem is that I in testing through Visual Studio I don't have the live web server environment, and I don't want to have to do a live call through LibraryX to get a IList<ClassA> that I need elsewhere in my code.  It would be great if I could generate that list without having to write the manual code to generate N instances of ClassA.  The issue is compounded when ClassA is sealed and instances are constructed internally in LibraryX, and I actually can't manually create those instances anyway without a lot of grief.

So can I do something like this?

IList<ClassA> GetGridData(string info) {
#if Testing
   IList<ClassA> list  = Mock.Create<IList<ClassA>>(info);
// or....
   IList<ClassA> list = Mock.Create<LibraryX.ClassAFactory>().DoSomething(info);
#else
  IList<ClassA> list  = LibraryX.ClassAFactory.DoSomething(info);  // web request done in here
#endif
  if (list.Count == 0)
    list = null;
  return list;
}


As I see it, JustMock doesn't seem to have the tools it needs to create a mock list of ClassA objects ... or maybe that's exactly what JustMock is great at doing!?  I really don't know because I'm not "getting" this from any of the documentation.  Is there something else that does what I want here?  Or is the universal solution still to just lump it and do it all manually?

Thanks!
Ricky
Telerik team
 answered on 03 Nov 2011
1 answer
185 views

I'm running Nunit with this profiler settings in 32bit. In the event log, it clearly shows that the profiler is running.But when I run "Mock.IsProfilerEnabled", it returns false. When I tried to create a sealed class, it said "Telerik.JustMock.MockException : Could not create mock from sealed class when profiler is not enabled.". The strange thing is, it was working at one point yesterday. Today, reboot the machine a couple of times, now it doesn't work.

Environment Variables
set COR_ENABLE_PROFILING=0x1
set COR_PROFILER={D1087F67-BEE8-4f53-B27A-4E01F64F3DA8}
(I tried without COMPLUS_ProfAPI_ProfilerCompatibilitySetting too.)
set COMPLUS_ProfAPI_ProfilerCompatibilitySetting=EnableV2Profiler

EVENT LOG
.NET Runtime version 4.0.30319.239 - The profiler was loaded successfully.  Profiler CLSID: '{D1087F67-BEE8-4f53-B27A-4E01F64F3DA8}'.  Process ID (decimal): 6968.  Message ID: [0x2507].

NUnit 2.5.10.11092
JustMock 2011.2.713.2
Window 7 x64. The application is in 32bit mode, .NET 4.0
Ricky
Telerik team
 answered on 26 Oct 2011
1 answer
199 views
Hi,

Is there a way to mock a private static constructor?

I got an static class with a private static constructor and I don't want to execute it because it configures himself from a configuration within the app.config.

I just want to mock one of is method but the constructor is always call causing the test to throw an exception.

Here an example thats illustrate my problem:

I got a static class like this

public static class StaticClassWithPrivateStaticConstructor
{
    private static string _text = "Text";
    static StaticClassWithPrivateStaticConstructor()
    {
        throw new Exception();
    }
    public static string Text
    {
        get { return _text; }
    }
}

I want to be able to test Text property without executing the static constructor.

[TestMethod]
public void MockStaticConstructor()
{
    Mock.SetupStatic(typeof(StaticClassWithPrivateStaticConstructor));
    Assert.AreEqual("Text", StaticClassWithPrivateStaticConstructor.Text);
}

Is there a way to do this?

Thanks
Ricky
Telerik team
 answered on 20 Oct 2011
3 answers
317 views
Hello!
I have troubles with getting my test case to work, possibly due to a lack of understanding of the principles to set this up correctly.

Environment: Entity Framework and .NET 4, Visual Studio 2010, MS SQL Server 2008

What I would like to do, is to test a short method "TryToGetObject", which is defined in BaseClass<T>.
The method takes an object named "importObject" of type "SomeEntityType".

The method passes this object to the compiled query and uses the property "ItemId" of it to find the matching data in the Entity Framework ObjectContext (if it exists).

For this test I wanted to mock the ObjectContext, so that I can avoid a real database access.

Here is my setup (Code is provided below):
  • SomeObjectContext: The Entity Framework context that provides access to the database
  • SomeEntityType: The type that represents the data of a table in the database
  • Class Baseclass<T>: Provides the pasic functionality for all derived classes.
  • DerivedClass<SomeEntityType>: Derives from BaseClass<T> and overrides property "CompiledQueryGetObject" to provide the specific implementation of the compiled query.
  • UnitTest1.TestMethod1() shows various attempty to mock the acces to the query, all of which do not work. The comments above them show the particular error message.

Can anyone please provide me some guidance what I am doing wrong?


Thank you in advance and best wishes,
Jens

BaseClass<T>

namespace MyNamespace
{
  /// <summary>
  /// Provides methods to access a database table.
  /// </summary>
  public abstract class BaseClass<T> where T : EntityObject
  {
    #region Properties
 
    /// <summary>
    /// Is overriden in derived classes.
    /// </summary>
    protected abstract Func<SomeObjectContext, T, T> CompiledQueryGetObject { get; }
 
    /// <summary>
    /// Context for database operations (EntityFramework)
    /// </summary>
    protected SomeObjectContext Context { get; set; }
 
    #endregion Properties
 
    #region Constructors
 
    /// <summary>
    /// Creates a new instance of type BaseClass.
    /// </summary>
    /// <param name="context">The current database context.</param>
    public BaseClass(SomeObjectContext context)
    {
      this.Context = context;
    }
 
    #endregion Constructors
 
    #region Public methods
 
    /// <summary>
    /// Tries to retrieve the given object from the database by its unique database constraints.
    /// </summary>
    /// <param name="importObject">Given entity object.</param>
    /// <returns>Object if found, otherwise null</returns>
    public T TryToGetObject(T importObject)
    {
      T existingObject = this.CompiledQueryGetObject(this.Context, importObject);
      return existingObject;
    }
 
    #endregion Public methods
  }
}

DerivedClass<SomeEntityType>
namespace MyNamespace
{
  /// <summary>
  /// Provides methods to access the SomeEntityType database table.
  /// </summary>
  public class DerivedClass : BaseClass<SomeEntityType>
  {
    #region Compiled queries
 
    /// <summary>
    /// A compiled query to look for an entity by its unique identifier(s) column(s).
    /// </summary>
    private static readonly Func<SomeObjectContext, SomeEntityType, SomeEntityType> m_LocalCompiledQueryGetObject = CompiledQuery.Compile<SomeObjectContext, SomeEntityType, SomeEntityType>(
        (context, importSomeEntityType) => context.SomeEntityTypes.SingleOrDefault(someEntityInstance => someEntityInstance.ItemId == importSomeEntityType.ItemId));
 
    #endregion Compiled queries
 
    #region Constants
 
    /// <summary>
    /// The EntitySetName of the processor that is accessed by this class.
    /// </summary>
    private const string LocalEntitySetName = "SomeEntityType";
 
    #endregion Constants
 
 
    #region Constructor
 
    /// <summary>
    /// Creates a new instance of type DerivedClass.
    /// </summary>
    /// <param name="context">The current database context.</param>
    public DerivedClass(SomeObjectContext context)
      : base(context)
    {
    }
 
    #endregion Constructor
 
    #region Properties
 
    /// <summary>
    /// Compiled query to get an object by the unique database constraint; Is overriden in derived classes.
    /// </summary>
    protected override Func<SomeObjectContext, SomeEntityType, SomeEntityType> CompiledQueryGetObject
    {
      get
      {
        return DerivedClass.m_LocalCompiledQueryGetObject;
      }
    }
 
    #endregion Properties
  }
}

The test class:
namespace TestProject1
{
  [TestClass]
  public class UnitTest1
  {
    [TestMethod]
    public void TestMethod1()
    {
      // Arrange
      // -------
      using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew, TimeSpan.FromSeconds(300)))
      {
        SomeObjectContext mockedContext = Mock.Create<SomeObjectContext>(Constructor.Mocked, Behavior.CallOriginal);
 
        SomeEntityType emptyQueryObject = new SomeEntityType();
        emptyQueryObject.ItemId = 1;
        emptyQueryObject.CountryId = 1;
        emptyQueryObject.StyleColorSetId = 1;
 
        SomeEntityType returnThisObject = new SomeEntityType();
        returnThisObject.ItemId = 2;
        returnThisObject.CountryId = 2;
        returnThisObject.StyleColorSetId = 2;
 
        DerivedClass classUnderTest = new DerivedClass(mockedContext);
 
        // System.ArgumentException: Direct null valued argument for non-public member is not supported. Use ArgExpr.IsNull<T>() or other members from ArgExpr wrapper class to provide your specification.
        Mock.NonPublic.Arrange<DerivedClass>(classUnderTest, "m_LocalCompiledQueryGetObject", Arg.IsAny<SomeObjectContext>(), Arg.IsAny<SomeEntityType>())
                      .IgnoreArguments()
                      .Returns(CompiledQuery.Compile<SomeObjectContext, SomeEntityType, SomeEntityType>(
                        (paramContext, importSomeEntityType) => mockedContext.SomeEntityTypes.SingleOrDefault(someEntityInstance => someEntityInstance.ItemId == importSomeEntityType.ItemId)));
         
        //Test method TestProject1.UnitTest1.TestMethod1 threw exception:
        //System.ArgumentException: Expression of type 'System.Func`3[MyNamespace.SomeObjectContext,MyNamespace.SomeEntityType,MyNamespace.SomeEntityType]' cannot be used for return type 'MyNamespace.SomeEntityType'
        Mock.NonPublic.Arrange<SomeEntityType>(classUnderTest, "CompiledQueryGetObject")
                      .IgnoreArguments()
                      .Returns(returnThisObject);
 
        // This one is only possible if I set "InternalsVisibleTo" attribute and use the DerivedClass_Accessor instead
        //// Test method TestProject1.UnitTest1.TestMethod1 threw exception:
        //// System.ArgumentException: Direct null valued argument for non-public member is not supported. Use ArgExpr.IsNull<T>() or other members from ArgExpr wrapper class to provide your specification.
        Mock.Arrange(() => classUnderTest.CompiledQueryGetObject(Arg.IsAny<SomeObjectContext>(), Arg.IsAny<SomeEntityType>()))
                                           .IgnoreArguments()
                                           .Returns(returnThisObject);
 
        // Act
        // -------
        SomeEntityType receivedObject = classUnderTest.TryToGetObject(emptyQueryObject);
 
        // Assert
        // ------
        Assert.IsNotNull(receivedObject);
 
        // Some more Asserts...
      }
    }
 
    private SomeEntityType returnEntity()
    {
      SomeEntityType returnObject = new SomeEntityType();
      return returnObject;
    }
  }
}
Ricky
Telerik team
 answered on 11 Oct 2011
3 answers
173 views
I am trying to write a unit test for a class that internally calls the static function Assembly.ReflectionOnlyLoadFrom(string). I would like to Arrange that call to return a Mock Assembly. 

Is this even possible?

Below are my two approaches thus far, both ended with my arrangement being bypassed and the internal function being executed:

Mock.SetupStatic<Assembly>();
Mock.Arrange(() => Assembly.ReflectionOnlyLoadFrom(Arg.AnyString)).Returns(Mock.Create<Assembly>());
 
var test = Assembly.ReflectionOnlyLoadFrom("Some Assembly"); //this will throw an exception instead of returning the mock Assembly

Mock.Partial<Assembly>().For<string>((s) => Assembly.ReflectionOnlyLoadFrom(s));
Mock.Arrange(() => Assembly.ReflectionOnlyLoadFrom(Arg.AnyString)).Returns(Mock.Create<Assembly>());
 
var test = Assembly.ReflectionOnlyLoadFrom("Some Assembly"); //this will throw an exception instead of returning the mock Assembly

Ricky
Telerik team
 answered on 10 Oct 2011
2 answers
602 views
I'm using the Trial Edition and am just getting started with JustMock.  Previously I was using Moq, and am looking at your features for mocking sealed classes, etc.

I have a question about mocking FileInfo properties like LastWriteTimeUtc.  I saw how you mocked FileInfo methods in the example.

Initially, I tried mocking FileSystemInfo, an abstract class, using an approach like this:

[TestMethod]
public void Can_Determine_Todays_File_By_LastWrite()
{
    var mockFile = Mock.Create<FileSystemInfo>();
    Mock.Arrange(() => mockFile.FullName).Returns("c:\\MSGTRK20111001-1.log");
    Mock.Arrange(() => mockFile.Name).Returns("MSGTRK20111001-1.log");
    Mock.Arrange(() => mockFile.LastWriteTimeUtc).Returns(DateTime.UtcNow);             
       
    var result = FileRoutines.IsTodaysFile(mockFile);
    Assert.IsTrue(result);
}

My issue is that although the Name and FullName properties are set, LastWriteTimeUtc is not set, and retains its default value.

I also tried mocking FileInfo by changing the constructor to look like this, but it was not effective either.  Do you have some advice?

var mockFile = Mock.Create<FileInfo>("c:\\MSGTRK20111001-1.log");
Chris Williams
Top achievements
Rank 1
 answered on 07 Oct 2011
1 answer
93 views
Are the JustMock docs available in PDF format?  Would really like to see it.

Thanks


Ricky
Telerik team
 answered on 30 Sep 2011
1 answer
60 views
Hi as the subject explains I've updated to JustMock Q2 2011 and now have exceptions thrown.

System.Reflection.Emit.ILGenerator.Emit(OpCode opcode, MethodInfo meth)
š..(ILGenerator il, Type target, MethodBase methodInfo)
š..Š(MethodBase methodBase, Boolean isFrameworkMethod, Type target)
š..Š(Type target, MethodBase methodBase, Boolean isFrameworkMethod, Boolean force)
š..Š(MethodBase methodBase, Boolean isMsCorlib, Boolean force)
.€.(Behavior behavior, Boolean static)
.€.‡()
Telerik.JustMock.Mock.Create(Type target, Behavior behavior, Object[] args)
Telerik.JustMock.Mock.Create(Type target, Object[] args)
Telerik.JustMock.Mock.Create[T]()
TPN.MessageProcessor.Tests.DeliveryMessageProcessorTemplateTest.Setup() in C:\Source\TPN\DEV\TPN.TestSuite\MessageProcessor\DeliveryMessageProcessorTemplateTest.cs: line 45

I haven't installed the MSI, just added the dll from (JustMock_2011.2.713_Dev.msi) which I expect wouldn't cause any problems, I'm using VS 2010. I couldn't find anything in the release notes related to Q2 2011, any help would be greatly appreciated.
Ricky
Telerik team
 answered on 28 Sep 2011
1 answer
123 views
I am trying to get a very basic test working that looks like this and keep getting a failure.

Test:
[TestMethod()]
public void FooSubmitTest()
{
    Mock.SetupStatic<Foo>();
    Foo.Submit();
    Mock.Assert(() => Foo.Submit());
}

Submit method:
public class Foo
{
    public static void Submit()
    {
        throw new NotImplementedException();
    }

The test fails on this line:
throw new NotImplementedException();

Can you tell me why this does not pass?










Ricky
Telerik team
 answered on 27 Sep 2011
6 answers
180 views
Hello,

I receive this excpetion when this code Mock.Create<IRepositoryStore>(); executes.

All other mocks on interfaces are working except this one.  I cant find a duplicate definition of the interface anywhere.

It's only started happening recently.  Any clues?

Regards,

Nick


Ricky
Telerik team
 answered on 23 Sep 2011
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?