Telerik Forums
JustMock Forum
2 answers
96 views
I'm trying to test the following, and the class under test's internals are visible to the test class:

public class PriceSeries
{
    private double _avPrice = 650;
    private double _relativePriceVol = 0.025;
    private double _priceRegress = 0.2;
    private double _currPrice = 650;
 
    private readonly Random _oracle = new Random();
 
    public double AvPrice
    {
        get { return _avPrice; }
        private set { if(value > 0) {_avPrice = value;} }
    }
 
    public double CurrPrice
    {
        get { return _currPrice; }
        private set { if (value > 0) { _currPrice = value; } }
    }
 
    public double RelativePriceVol
    {
        get { return _relativePriceVol; }
        private set { if(value > 0 && value < 1) { _relativePriceVol = value; } }
    }
 
    public double PriceRegress
    {
        get { return _priceRegress; }
        private set { if (value > 0 && value < 1) { _priceRegress = value; } }
    }
 
    /// <summary>
    /// Return NdX
    /// </summary>
    /// <param name="numdice">Number of dice being rolled</param>
    /// <param name="numfaces">Highest numbered face on die</param>
    /// <returns></returns>
    internal int[] RollDice(int numdice, int numfaces)
    {
        numdice = Math.Max(1, numdice);
        numfaces = Math.Max(1, numfaces);
        int[] dice = new int[numdice];
        for(int i=0;i<numdice;i++)
        { dice[i] = RollOneDie(numfaces); }
        return dice;
    }
 
    public double GetNextPrice()
    {
        int[] dice = RollDice(4, 6);
        int sum = -14;
        foreach(int t in dice)
        { sum += t; }
        double result = this.CurrPrice + this.PriceRegress*(this.AvPrice - this.CurrPrice)
 +
this.AvPrice*this.RelativePriceVol*sum;
        return result;
    }
 
    internal int RollOneDie(int numfaces)
    {
        return _oracle.Next(numfaces) + 1;
    }
}


With these unit tests

[TestMethod]
public void TestFirstPriceGen()
{
    PriceSeries target = new PriceSeries();
    // mock out dice roll
    int[] mockroll = new int[] {3,5,4,5};
    Mock.Arrange(() => target.RollDice(4, 6)).Returns(mockroll);
     
    double expectedPrice = 698.75;  // dice roll of +3 from initialisation
 
    double actualPrice = target.GetNextPrice();
    Assert.AreEqual(expectedPrice,actualPrice);
    Mock.Assert(() => RollDice(4,6),Occurs.Once());

}
 
[TestMethod]
public void TestRollDice()
{
    PriceSeries target = new PriceSeries();
    Mock.Arrange(() => RollOneDie(6)).Returns(3);
 
    int[] expectedd6 = {3};
    int[] actuald6 = target.RollDice(1, 6);
    Mock.Assert(() => RollOneDie(6), Occurs.Once());
    Assert.AreEqual(expectedd6.Length,actuald6.Length);
    Assert.AreEqual(expectedd6[0],actuald6[0]);         
}


 I'm using VS2010, JetBrains ReSharper 7.0.1, and JetBrains dotCover2.2.  

TestFirstPriceGen() always picks up the mocking and works correctly, whether running it alone, or as part of the UT harness (via Run All Tests or Cover All Tests) - all assertions pass.

However, that doesn't apply for TestRollOneDie() - no matter how I call it (via running the UT directly, or Run/Cover All Tests), it fails the Mock.Assert call, saying:
"Expected PriceSeries.RollOneDie(Int32) call on the mock should be once, but it was called 0 time(s)."

Without that Mock.Assert call, it ignores the mock and calls the original implementation of RollOneDie(), and thus fails 5 out of 6 times.

What am I doing wrong?
Peter
Top achievements
Rank 1
 answered on 09 Sep 2013
7 answers
116 views
I've found an issue between Just Mock Lite when running unit tests that consistently fail, but only under Release build (presumably because of optimized code) and X64 builds with the XUnit test framework. I can't comment on whether this issue occurs under other test frameworks or not, but it definitely goes away under x86 and Debug builds. I have no idea why this happens. Cheers. Here's a sample: -

public class MyClass
{
    private readonly MockClass generator;
    public MyClass(MockClass generator)
    {
        this.generator = generator;
    }
 
    public void Foo(Object someData)
    {
        generator.Bar();
    }
}
 
public interface MockClass
{
    void Bar();
}  
 
 
public class TestClass
{
    private readonly MockClass generator;
    private readonly MyClass myClass;
         
    public TestClass()
    {
        generator = Mock.Create<MockClass>();
        myClass = new MyClass(generator);
    }
 
    [Fact]
    public void X64Failure()
    {
        myClass.Foo(null);
 
        Mock.Assert(() => generator.Bar());
    }
}

Here's the test failure message: -

X64Failure has failed
 
Occurrence expectation failed. Expected calls in range [1, (any)]. Actual calls: 0
  
\x8Ž\x2.\x19\x3.\x7
    \x12\x1A\x3(String —)
  
  
\x2.—\x2
    Assert(Nullable`1 •\x2, Nullable`1 –\x2, Int32 \x18\x3)
  
  
Telerik.JustMock.Core.MocksRepository
    \x13˜\x2(œ\x2 œ\x2, Boolean \x11˜\x2, Occurs š\x7\x2)
    Assert(Object ›–\x2, Expression ›•\x2, Occurs š\x7\x2, Boolean \x11˜\x2)
  
  
Telerik.JustMock.Mock.\x3‚
    šž\x2()
  
  
“•\x2.’•\x2
    Š•\x2(Action ‹•\x2)
Stefan
Telerik team
 answered on 02 Sep 2013
3 answers
87 views
Can't figure out a strategy to test the pattern following:

The problem is to avoid AnotherCall from being called from within VoidCall to isolate VoidCall's implemenation. You can't use IFoo because neither implementation can be called, but the DoNothing doesn't seem to have any effect on avoiding AnotherCall even if you do a foo.AnotherCall(). Also the CallOriginal seems valueless, since without it the method gets called anyway. I don't see the value of it without parameters to VoidCall (but I couldn't even get that to work). As a matter of fact nothing seems any different than not mocking Foo at all. What am I missing in the definition of these Arrange functions.
[TestClass]
    public class FooTest
    {
        [TestMethod]
        public void SimpleExampleWithDoNothing()
        {
            // Arrange
            var foo = Mock.Create<Foo>();
 
            Mock.Arrange(() => foo.VoidCall()).CallOriginal();
            Mock.Arrange(() => foo.AnotherCall()).DoNothing();
 
            // Act
            foo.VoidCall();
 
            // Assert
            Mock.Assert(foo);
        }
    }
 
    public interface IFoo
    {
        void VoidCall();
 
        void AnotherCall();
    }
 
    public class Foo : IFoo
    {
        public void VoidCall()
        {
            AnotherCall();
        }
 
        public void AnotherCall()
        {
            throw new InvalidOperationException();
        }
    }
Kaloyan
Telerik team
 answered on 02 Sep 2013
3 answers
103 views
Hi. 
Is there any option to use MockingContainer to mock properties (not just the ctor)? 
Thanks

Tsvetomir
Telerik team
 answered on 28 Aug 2013
5 answers
4.4K+ views
Hi..
I use the JustMock first time. I have no idea to test the method below.
Anybody could tell me how to do it.
Thanks.

public static class CacheHelper
{
   public static void AddCacheValue(string key, object obj, DateTime dt)
   {
       var policy = new CacheItemPolicy();
       policy.AbsoluteExpiration = dt;
       MemoryCache.Default.Set(key, obj, policy);
   }
}
Martin
Telerik team
 answered on 28 Aug 2013
1 answer
81 views

Hi. I've been looking for any examples (if it's possible) of using JustMock to Unit Test legacy ASP.Net applications. So basically, loading a page and then perhaps some interaction with the page to test the code behind.

Something along the lines of this using TypeMock and Ivonna 

So far I haven't really been able to find anything. Anyone know if it is possible, and any examples?

Many Thanks
Kaloyan
Telerik team
 answered on 23 Aug 2013
2 answers
441 views
Hi Telerik,
In JustMock documents (Entity Framework Mocking) you use :
IList<Dinner> FakeDinners()
And then :
Mock.Arrange(() => nerdDinners.Dinners).ReturnsCollection(FakeDinners());
to mock a DbSet. The problem is where I use " DbContext.DbSet<Dinner>.Find(2) " which gets from context or database the entity with primary key equal to 2. But in my test where I pass the FakeDinners() ,it doesn't work and return null. Looks like it doesn't know primary key in 
FakeDinners() as it is list. So what is solution?
Iman
Top achievements
Rank 2
 answered on 23 Aug 2013
1 answer
439 views
Is there a NuGet package for JustMock non-lite?  Since the features of non-lite require a profiler it seems that you wouldn't be losing anything by making the .NET assemblies for the non-lite version available on NuGet since users would still have to purchase a license to actually use the features provided in the assembly.

Myself and one of my peers (we'll call him Bob) are working together on a project.  I install JustMock to the default install path (C:\Program Files (x86)\Telerik\JustMock) while he installs to D:\Programs\JustMock.  I keep my source code in C:\Users\Micah\Source\GitHub\awesome and he stores it in C:\source\awesome.  I add JustMock to our UnitTest project (in the awesome repo) by adding a reference to C:\Users\Micah\Documents\Source\dotnet_agent\Agent\packages\JustMock.2013.3.819\lib\Net35\Telerik.JustMock.dll.  I commit and push this change to GitHub and then Bob pulls the change down.  He then attempts to build and receives an error saying the assembly couldn't be found.

There appear to be a few solutions, though none of them seem particularly clean:
1. Copy Telerik.JustMock.dll to our repo and reference it there.
2. Have all developers copy Telerik.JustMock.dll to the GAC.
3. Have all developers use the same install path for JustMock.
4. Have all developers use the same install path for JustMock and the source code.

Problems with each:
1. Telerik.JustMock.dll has to match the version of the profiler that is installed.  The same problem would occur with a NuGet package.
1. I have to know which of the JustMock\Libraries assemblies I need.  Right now I am just using JustMock.dll but I have only scratched the surface of JustMock, will I need others like JustMock.Container or Practices.Unity?
2. It is easy to forget to do this when building out a new machine or onboarding a new developer.
2. Every time a user upgrades JustMock they have to re-copy the assemblies or risk versioning related failures.
3,4. Everyone sets up their workspace differently, some developers may not even be able to match the folder structure of others (perhaps their whole OS and applications are on D drive or they are running x86 version of the OS).

A NuGet package still has the versioning issue but at least it is one that can be reported as an intelligible error at runtime and it eliminates all of the other problems.

Assuming a NuGet package isn't available, what solution is recommended in the meantime?  I am most fond of #1 but I don't know which assemblies to copy.  Insight wanted.
Kaloyan
Telerik team
 answered on 22 Aug 2013
1 answer
95 views
We have some mission critical code that catches all exceptions and recovers from them in various ways.  I would like to be able to use Mock.Create<MyClass>(Behavior.Strict) so that I can know that none of the methods on MyClass are being called besides the ones I explicitly Mock.Arrange.  However, this results in the methods throwing exceptions which are then caught by my application and recovered from so I never see them.

I would like something like this, but where I didn't have to manually arrange every method on the class and instead have some Behavior that I could give to Mock.Create that would result in all of the arranges being auto-generated.  I could then manually arrange anything I didn't want to have OccursNever on, just like you can override the exceptions thrown by Behavior.Strict.
class MyClass
{
    public void Method1() { }
    public void Method2() { }
    public void Method3() { }
}
 
class ClassUnderTest
{
    public void DoSomething(MyClass myClass)
    {
        myClass.Method3();
    }
}
 
[Test]
void MyClass_methods_are_never_called()
{
    // ARRANGE
    var myClass = Mock.Create<MyClass>();
    Mock.Arrange(() => myClass.Method1()).OccursNever();
    Mock.Arrange(() => myClass.Method2()).OccursNever();
    Mock.Arrange(() => myClass.Method3()).OccursNever();
 
    // ACT
    var classUnderTest = new ClassUnderTest();
    classUnderTest.DoSomething(myClass);
 
    // ASSERT
    Mock.Assert(myClass); // this will fail
}
Kaloyan
Telerik team
 answered on 21 Aug 2013
0 answers
43 views
Nevermind.  It was a problem with having a static that was being re-used, not a problem with JustMock.  (please delete this post if possible)
Micah
Top achievements
Rank 1
 asked on 21 Aug 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?