Telerik Forums
JustMock Forum
2 answers
960 views
I need to mock any DbCommand calls to the specific sproc. I tried mocking
var cmd = Mock.CreateLike<System.Data.IDbCommand>(c => c.CommandText == "dbo.GetStartTime");
Mock.Arrange(() => cmd.ExecuteScalar())
    .Returns("10:00");

for the code below but I doesn't work. How can I achieve it?
private static string LoadFromDatabase(DateTime date)
{
    // create EntLib database object
 
    using (DbCommand cmd = db.GetStoredProcCommand("dbo.GetStartTime"))
    {
        db.AddInParameter(cmd, "DateToCheck", DbType.Date, date.Date);
        var startTime = db.ExecuteScalar(cmd);
 
        if (startTime == null || startTime == DBNull.Value)
            return null;
        else
            return startTime;
    }
}
miksh
Top achievements
Rank 1
Iron
 answered on 11 Sep 2013
11 answers
238 views
I'm attempting to test an app that creates an instance of the struct System.Windows.Media.Color.

The color is loaded fine in the actual app, but when testing, I get the error: System.InvalidProgramException: Common Language Runtime detected an invalid program.

This happens on the line where the color is created using Color.FromArgb()..

So I thought perhaps I need to mock the struct and static method. This is what I tried:

var color = Mock.Create<Color>(Constructor.Mocked, Behavior.Loose);
Mock.Arrange(() => Color.FromArgb(Arg.IsAny<byte>(), Arg.IsAny<byte>(), Arg.IsAny<byte>(), Arg.IsAny<byte>())).IgnoreArguments().IgnoreInstance().Returns(color);

but when I run this, I get this error: Telerik.JustMock.MockException: Implementation of method Equals in value types must not throw for mocked instances.

Is there something additional I need to do to mock this struct?
Deyan
Telerik team
 answered on 11 Sep 2013
1 answer
821 views
Here is my attempt to mock the interface (I actually want to return a value, but throw just to make it easier to identify):

var cache = Mock.Create<ICache>();
_cacheFactoryMock.Arrange(m => m.Application).Returns(cache);
cache.Arrange(m => m.GetOrAdd(Arg.AnyString, Arg.IsAny<Func<Dictionary<string, string>>>, Arg.IsAny<DateTime>(), Arg.IsAny<TimeSpan>(), null)).Throws(new DivideByZeroException());

Here is the invocation:
return _caches.Application.GetOrAdd(
    string.Format(CacheKeyFormat, groupName),
    () => _ldapService.FindLdapUserEmailsInGroup(groupName),
    DateTime.Now.AddDays(1),
    Cache.NoSlidingExpiration
    );
 
Here is the method signature of FindLdapUserEmailsInGroup:
Dictionary<string, string> FindLdapUserEmailsInGroup(string groupName);

The pertinent part of the cachefactory interface:
public interface ICacheFactory
{
        ICache Application { get; }       
}

The pertinent part of ICache:
public interface ICache
{
         TItem GetOrAdd<TItem, TState>(string key, Func<TState, TItem> getValue, TState state, DateTime absoluteExpiration, TimeSpan slidingExpiration, object dependencies = default(object));
 
        TItem GetOrAdd<TItem>(string key, Func<TItem> getValue, DateTime absoluteExpiration, TimeSpan slidingExpiration, object dependencies = default(object));
}


I'm not sure where I am going wrong.  I have tried several permutations of the dependencies object (using null, default etc), and I'm not sure what could be wrong with the Func<Dictionary<string,string>> arg but nothing I have done so far is getting the arrange to take effect.  Any guidance is appreciated.
Stefan
Telerik team
 answered on 10 Sep 2013
2 answers
112 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
123 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
92 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
115 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.5K+ 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
87 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
475 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
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?