Telerik Forums
JustMock Forum
16 answers
705 views
Hey Everyone,

I am trying to mock DateTime.Now and having some issues.  Below is my code
[Test]
public void datetime_test_justmock()
{
    var YEAR_2K = new DateTime(2000, 1, 1);
    Mock.Arrange(() => DateTime.Now).Returns(YEAR_2K);
    var actual = DateTime.Now;
    Assert.AreEqual(YEAR_2K, actual);
}

Actual gets sets to the current DateTime not the one I arranged.

Am I missing something.

Thanks,

-zd
Ricky
Telerik team
 answered on 10 Aug 2012
2 answers
100 views
Dear Support
I am currently evaluating JustMock and when trying to create mock for SPField:
var field = Mock.Create<SPField>();
I get NullReferenceException. 
StackTrace:
at Telerik.JustMock.DynamicProxy.ProxyFactory.CreateInstance(Type proxyType, Object[] extArgs)
at Telerik.JustMock.DynamicProxy.ProxyFactory.Create()
at Telerik.JustMock.DynamicProxy.Fluent.FluentProxy.NewInstance()
at Telerik.JustMock.DynamicProxy.Proxy.Create(Type target, Action`1 action)
at Telerik.JustMock.MockManager.CreateProxy(Type targetType, Container container)
at Telerik.JustMock.MockManager.CreateInstance(Container container)
at Telerik.JustMock.MockManager.SetupMock(Behavior behavior, Boolean static)
at Telerik.JustMock.MockManager.CreateInstance()
at Telerik.JustMock.Mock.Create(Type target, Behavior behavior, Object[] args)
at Telerik.JustMock.Mock.Create(Type target, Object[] args)
at Telerik.JustMock.Mock.Create[T]()

Can SPField be mocked using JustMock?
Ricky
Telerik team
 answered on 01 Aug 2012
2 answers
125 views
I am new to the framework so I guess it is just something I did not do before invoke the test case using MSTEST.

Created the test as following

        public class Foo
        {
            public static int Execute(int arg) { throw new NotImplementedException(); }
        }

        [TestMethod]
        public void TestMethod1()
        {
            Mock.SetupStatic<Foo>(Behavior.Strict);
            Mock.Arrange(() => Foo.Execute(0)).Returns(10);
            Foo.Execute(0);
        }

Got a passed test case within VS2012 environment. 

When I do commandline "mstest /testcontainer:test.dll", the case failed. Anything I need to do before running MSTEST?

Thanks.
Ricky
Telerik team
 answered on 20 Jul 2012
5 answers
388 views
Hi,

Having played around with JustMock, I couldn't figure out how to test a controller action properly. I can't seem to figure out how to properly instantiate the controller (with request, session etc).

Here's a controller with a simple action (which renders a custom login form):

public class LoginController : Controller
{
        public ActionResult LogOn(string company)
        {
            ViewData["showCompany"] = company == null;
            ViewData["company"] = company;
            return View();
        }
}

I'd like to write a test on this method, but have no idea how to correctly instantiate the controller object. Having created the following test attempt, it doesn't work. When debugging it the action is not fully executed and the actionResult is null:

            // arrange
            var outputString = new StringWriter();
            var context = new HttpContextWrapper(new HttpContext(new HttpRequest("/", "http://localhost/mft/Login/LogOn", ""), new HttpResponse(outputString)));
            var loginController = new LoginController();

            Mock.Arrange(() => loginController.HttpContext).Returns(context);
            Mock.Arrange(() => loginController.LogOn("mft")).MustBeCalled();

            // act
            var actionResult = loginController.LogOn("mft");

            // assert
            Mock.Assert(loginController);


I realized the ViewData is null so I modified the test like so:
            loginController.ViewData = new ViewDataDictionary();

However, this doesn't seem to be solving the problem. The actionResult keeps being null and I feel like I'm going the wrong way. There should be a simple way to instantiate a controller and call an action. Later on I will have to use a session cookie that I can get by calling something like:
[AcceptVerbs(HttpVerbs.Post)] public ActionResult LogOn(string userName, string password, string company, string returnUrl){}

I've been looking for examples all over but just couldn't find one that works.

Thanks,
Mihai
Ricky
Telerik team
 answered on 06 Jul 2012
3 answers
193 views

Hello,

this question has been ask here before, but I do not see how the answer is of any use in this case.

I want to test a method where I have something like this:

public string DoSomething()
        {        
            using (SPSite site = new SPSite("http://someURL"))
            {
                using (SPWeb web = site.OpenWeb())
                {
…

 

At this time the URL does not exist.

In the test case I create a mock for SPSite and SPWeb (SharePoint objects).

var spSite = Mock.Create<SPSite>();       
var spWeb = Mock.Create<SPWeb>();
Mock.Arrange(() => spSite.OpenWeb()).Returns(spWeb);
…

But I get this exception in the mehtod under test when the new SPSite is created:

System.IO.FileNotFoundException: The Web application at http://someUrl could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application.

How can I use the mock spSite when new SPSite("http://someURL")) is called?
IgnoreInstance only swaps method calls and does not work with constructor calls. (?)

Ricky
Telerik team
 answered on 05 Jul 2012
5 answers
2.2K+ views
I'm currently using the trial of JustMock.  I created a fresh JustMock Test project and I'm unable to mock the ConfigurationManger AppSettings.

This is the code I'm using:


[TestMethod]
public void TestMethod1()
{
    // Arrange
    var appSettings = new NameValueCollection { { "test1", "one" } };
 
    Mock.Arrange(() => ConfigurationManager.AppSettings)
        .Returns(appSettings)
        .MustBeCalled();
 
    // Act
    var test1 = ConfigurationManager.AppSettings["test1"];
 
    // Assert
    Assert.IsTrue(Mock.IsProfilerEnabled);
    Assert.AreEqual("one", test1);
}


This is the error I receive: 

Failed TestMethod1 JustMockTest Assert.AreEqual failed. Expected:<one>. Actual:<(null)>.

Ricky
Telerik team
 answered on 04 Jul 2012
3 answers
148 views
I am trying to Mock a method that Action<T> delegate. The goal is to mock the Action.Invoke and Assert if the correct value get sent back , but the following code does not seem to work. Any pointers ?

Jay


public interface IClientServerMockingTest
{
    void CallMethod(string id, Action<string> status);
}

[TestClass]
public class ClientServerMockingTest : IClientServerMockingTest
{
    [TestMethod]
    public void TestMethod1()
    {
        var clientServer = Mock.Create<ClientServerMockingTest>();
         var action = Mock.Create<Action<string>>();
         Mock.Arrange(() => clientServer.CallMethod("demo", action)).Raises(() => clientServer.CallMethod("demo", action));
        clientServer.CallMethod("demo", action);    
        Mock.Assert(clientServer);
    }
 
    public void CallMethod(string id, Action<string> action)
    {
        action.Invoke("worked");
    }
}
Ricky
Telerik team
 answered on 29 Jun 2012
1 answer
969 views
I have a method that takes a System.Data.DataSet and uses it to construct an object. I am trying to mock the dataset in order to test that the method constructs the object properly.

The method I am testing is the following:
public Box CreateBoxFromDataSet(DataSet dataSet, int rowNumber = 0)
{
    const int BOX_TABLE = 0;
    const int METADATA_TABLE = 1;
 
    Box box = new Box() {
        ID = Convert.ToInt64(dataSet.Tables[BOX_TABLE].Rows[rowNumber]["BoxID"]),
        Name = dataSet.Tables[BOX_TABLE].Rows[rowNumber]["Name"].ToString()
    };
 
    if (dataSet.Tables.Count > 1)
    {
        foreach(DataRow row in dataSet.Tables[METADATA_TABLE].Rows)
        {
            long propertyID = Convert.ToInt64(row["MetaPropertyID"]);
            string value = NullableConverter.ToString(row["MetadataValue"]);
            box.ApplyMetadata(propertyID, value);
        }
    }
 
    return box;
}

My test is the following:
[TestMethod]
public void CreateBoxFromDataSet_ReturnsBox()
{
    //Arrange
    long expectedID = 300;
    Box actual = null;
    var manager = new BoxManager();
    var dataset = new DataSet();
    dataset.Tables.AddRange(new [] { new DataTable("Box"), new DataTable("Metadata") });
    dataset.Tables[0].Rows.Add(dataset.Tables[0].NewRow());
    dataset.Tables[1].Rows.Add(dataset.Tables[1].NewRow());
    dataset.Tables[2].Rows.Add(dataset.Tables[2].NewRow());
    Mock.Arrange(() => dataset.Tables[0].Rows[0]["BoxID"]).Returns(expectedID);
    Mock.Arrange(() => dataset.Tables[0].Rows[0]["Name"]).Returns("BoxName");
    Mock.Arrange(() => dataset.Tables[1].Rows[0]["MetaPropertyID"]).Returns(700);
    Mock.Arrange(() => dataset.Tables[1].Rows[0]["MetadataValue"]).Returns("MetadataValue");
 
    //Act
    actual = manager.CreateBoxFromDataSet(dataset);
 
    //Assert
    Assert.IsNotNull(actual);
}

When I run this test if fails when data is read from the dataset with the following exception:
 "InvalidCastException : Object cannot be cast from DBNull to other types." 

I have tried mocking the DataSet several different ways and cannot get the test to work.
Before this I attempted to create mock tables using
Mock.Create<DataTable>() and
Mock.Arrange(() => dataset.Tables[0]).Returns(mockTable)
but the test still would fail because dataset.Table[0] would throw a IndexOutOfRangeException.

How can I properly mock a DataSet?

Thanks

Ricky
Telerik team
 answered on 28 Jun 2012
3 answers
233 views

I'm looking to see what is wrong with this code.  Looking at the samples it should work with the Telerik.JustMock.DLL referenced, but is throwing a build error instead:

using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;

namespace JustMock_Example
{
    public class ClassUnderTest
    {
        public bool ReturnsFalse()
        {
            return false;
        }
    }

    [TestClass]
    public class IgnoreInstanceTest
    {
        [TestMethod]
        public void ExampleTest()
        {
            var fake = Mock.Create<ClassUnderTest>();
            Mock.Arrange(() => fake.ReturnsFalse()).Returns(true).IgnoreInstance();

            Assert.IsTrue(new ClassUnderTest().ReturnsFalse());
        }
    }
}

///Throws the following:
Error 1 'Telerik.JustMock.Expectations.Abstraction.IAssertable' does not contain a definition for 'IgnoreInstance' and no extension method 'IgnoreInstance' accepting a first argument of type 'Telerik.JustMock.Expectations.Abstraction.IAssertable' could be found (are you missing a using directive or an assembly reference?) c:\~\~\documents\visual studio 2010\Projects\JustMock Example\Class1.cs 23 67 JustMock Example

This is with the most recent build, and hopefully I'm missing something small.
Thanks!

Ricky
Telerik team
 answered on 21 Jun 2012
1 answer
92 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
Narrow your results
Selected tags
Tags
+? more
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?