Telerik Forums
JustMock Forum
1 answer
135 views
Hi,

suppose my applicaiton contains several layers, the lowest one is a DAL (Data Access Layer) interfacing with a DB.
Now, I want to unit-test a method of a class in the upper layer which eventually calls a method in the DAL. Naturally, I want to mock only the DB, not the mid-layer classes.
How should I go about unit-testing a high-layer method as mentioned above?

Thanks,
Michael
Kaloyan
Telerik team
 answered on 08 Aug 2013
1 answer
140 views
Hi, I am running into a small issue with justmock. I am using nunit as my testing framework which allows base classes with multiple TestFixtureSetup methods when running a single test. I will create and inject my common mocks in the base class TestFixtureSetup method. Then my test class(inheriting the base class) will do the arranging and testing.

The issue is when the method being mocked is called, it acts like the arrange never excuted. I can verify that all the code ran in the order expected, but my mocked methods are just returning nulls.

Below I have a simple example of what I'm trying to explain.


[TestFixture]
public abstract class TestBase
{
    public IClientService ClientService;
 
    [TestFixtureSetUp]
    public void InitFixture()
    {
        ClientService = Mock.Create<IClientService>();
    }
}

[TestFixture]
public class ClientServiceTests : TestBase
{
    [Test]
    public void Test()
    {
        Mock.Arrange(() => ClientService.Retrieve(Arg.AnyLong))
            .Returns(() => new Client());
 
        var client = ClientService.Retrieve(0);
 
        Assert.IsNotNull(client);
    }
}

This does work when the test class has a TestFixtureSetUp of its own and calls the base class setup method, but the base class setup method cannot have the TestFixtureSetUp attribute. Does this mean that the arrange has to execute within the same fixture as the create?
Is there a better way to utilize a base class in this manner? Is this intended?

On a side note, this method was working a couple days ago when I had checked my code in. I will revert my tests to see if i stumbled upon some way to get this to work, I may have had the attributes in just the right places possibly?
Kaloyan
Telerik team
 answered on 02 Aug 2013
3 answers
313 views

class and method
public class A
{
  public static bool TryGet<T>(string key, out T obj)
  {
      ....
  }
}
 
usage
public static object AMethod(string key)
{
object values;
 
if (A.TryGet(key, out values))
{
  return values;
}
 
return null;
}

now i want to write a test for method AMethod and mock A.TryGet. How can I do that? I tried different approaches, but wasnt able to create a mock of the TryGet extension. I want to set the "obj" variable in the "TryGet" method do different values depending on the passed key (using "Returns" or "DoInstead")


Kaloyan
Telerik team
 answered on 25 Jul 2013
1 answer
1.7K+ views
hello,
I try to create a mock for System.Enum. That works for all public static methods of the System.Enum class (i.e. Enum.GetValues). But I have no idea how to set up the mock for the ToString() method of the Enum object.
(all C# .NET)

method:
public static void TestThis(ListControl ctrl, Type enumType, Enum enumItem= null)
{
    int[] itemValues = Enum.GetValues(enumType).ToArray<int>();
    string[] itemNames = Enum.GetNames(enumType);
 
    string s = enumItem.ToString();
}

mock:
Mock.SetupStatic(typeof(Enum), Behavior.Strict);
Mock.Arrange(() => Enum.GetValues(Arg.IsAny<Type>())).Returns(new int[] { 1, 2, 3 });
Mock.Arrange(() => Enum.GetNames(Arg.IsAny<Type>())).Returns(new string[] { "1", "2", "3" });
 
//--- this causes an exception (Cannot create mock for type due to CLR limitations.)
Enum e = Mock.Create<Enum>();
Mock.Arrange(() => e.ToString()).IgnoreArguments().IgnoreInstance().Returns("2");
//---

//--- in that case null is returned instead of "2"; compiler never steps into the mocked "returns"
TestEnum e = Mock.Create<TestEnum>();
Mock.Arrange(() => e.ToString()).IgnoreArguments().IgnoreInstance().Returns("2");
//---

DropDownList ddlTestList = new DropDownList();
TestThis(ddlTestList, typeof(TestEnum), TestEnum.Empty)
Stefan
Telerik team
 answered on 24 Jul 2013
3 answers
183 views
I am trying to test my application that uses Tasks. I have arranged a static method, if I call that method right after arranging it, I get the Mocked return value. But, if I call the method from a task, the method is not mocked.
I am running on version 2011.2.713.2  as my subscription has run out, and since this is a static method, I cannot use the free edition.

I do have JustMock enabled in the VS menu Telerik->JustMock->Enable JustMock
I managed to reproduce the problem with a simple example:

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
  
namespace TestMockingStatic
{
   public class ClassWithStatic
   {
      public static int NumGot = 0;
      public static int GetANumber(int foo, int bar)
      {
         throw new NotImplementedException();
      }
   }
     
   [TestClass]
   public class UnitTest1
   {
      public void GetValue()
      {
         Task.Factory.StartNew(() =>
         {
            ClassWithStatic.NumGot = ClassWithStatic.GetANumber(5, 10);
         });
      }
  
      [TestMethod]
      public void TestMethod1()
      {
         Mock.SetupStatic<ClassWithStatic>(Behavior.Strict);
         Mock.Arrange(() => ClassWithStatic.GetANumber(Arg.AnyInt, Arg.AnyInt)).Returns(42);
  
         Assert.AreEqual(42, ClassWithStatic.GetANumber(5, 10), "Mocked Method did not return expected result");
  
         GetValue();
         SpinWait.SpinUntil(() => ClassWithStatic.NumGot > 0, 20000);
  
         Assert.AreEqual(42, ClassWithStatic.NumGot, "Mocked method called via TASK, did not return correct value");
      }
   }
}

Any help would be great,
Todd
Kaloyan
Telerik team
 answered on 22 Jul 2013
1 answer
90 views
Hi there.  I'm trying to figure out if there's a way to reference the runtime value of a matcher for use in a Returns call.  This seems like a pretty straightforward question, but I wasn't able to find quite what I'm wanting in the documentation, so apologies if I missed something obvious.  Regardless, here's the call I'm trying to make.

service.Arrange<Employee>(emp => emp.LoadByName(Arg.AnyString)).Returns(data.employees.Where(e => e.Name == /* whatever the value matched by Arg.AnyString was */));

Is there another method I should be calling to accomplish the same thing, or is there simply a way to reference the matcher's value?
Stefan
Telerik team
 answered on 11 Jul 2013
14 answers
169 views
Hello I have a question about SharePoint Faking.
in my Class unter Test I have an method that use following code.
 public Guid CreateNewSite(String siteUrl, string newSite)
{

using
(SPSite site = new SPSite(siteUrl))
                {
                    if (!site.AllWebs.Names.Contains(newSite))
                    {
                        return site.AllWebs.Add(newSite, newSite, "New Website", 1033, "STS#1", true, false).ID;
                    }
} 
and this is my Testcode:
SPSite fakeSite = Mock.Create<SPSite>();
          Mock.Arrange(() => fakeSite.AllWebs.Names).ReturnsCollection<string>(new[] { "nonExistsWeb" });
          Mock.Arrange(() => fakeSite.AllWebs.Add(Arg.AnyString, Arg.AnyString, Arg.AnyString, (uint)Arg.AnyInt, Arg.AnyString, Arg.AnyBool, Arg.AnyBool).ID).Returns(SomeGuid);
 
Guid actual = spListCreator.CreateNewSite("http://local""SomeSite");
But this will not work. I get this error:
System.IO.FileNotFoundException: The Web application at http://local 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.

Why?


Regards
Stefan
Telerik team
 answered on 05 Jul 2013
4 answers
105 views

Hello, I have some questions about unit testing with Justmock.

I have this very simple method (Share Point code):

Code:

public Guid CreateNewSite(String siteUrl, string newSite)
       {
           if (!(string.IsNullOrEmpty(newSite) || string.IsNullOrEmpty(siteUrl)))
           {
               using (SPSite site = new SPSite(siteUrl))
               {
                   if (!site.AllWebs.Names.Contains(newSite))
                   {
                       return site.AllWebs.Add(newSite, newSite, "New Website", 1033, "STS#1", true, false).ID;
                   }
               }
           }
           return Guid.Empty;
       }

1 question.
 Is it ok, that I test the methods return (Guid). I mean I test the contract of the method "CreateNewSite". If the site that should be created not exist, and the parameters are not empty, the new site will be created and a Guid != Guid.Empty will be returned. Otherwise return Guid.Emtpy.

Or should I test, that the method site.AllWebs.Add(newSite, newSite, "New Website", 1033, "STS#1", true, false).ID; was called with the right parameters?

2 question.
How can I unit test the void methods (interaction testing) with Justmock.
For example this code:
public void AddSplistItemToList(SPWeb web, Guid listId, String listItemTitle)
        {
            if (!(listId == Guid.Empty || listId == Guid.Empty || string.IsNullOrEmpty(listItemTitle)))
            {
                SPList list = web.Lists[listId];
                SPListItem item = list.Items.Add();
                item["Title"] = listItemTitle;
                item.Update();
            }
        }
Because the  AddSplistItemToList is void, I want to test, that item["Title"] would set correctly (value from listItemTitle parameter). How I can test and fake this with Justmock?

I hope my questions are not too confused :)

Artiom
Top achievements
Rank 1
 answered on 03 Jul 2013
3 answers
327 views
Hello,

I'm trying to use the licensed JustMock version for developing some unit tests.

I was having some issues when running existing unit tests (created by other people on the project), as the error: "Telerik.JustMock.MockException: Profiler must be enabled to mock/assert target ..." kept appearing over and over. I tried registering the dlls for Profiles and it did succesfully, but I'm still getting the same problem. If I open the JustMock configuration, no Profile is available. If I check the Telerik menu in VS 2010, the profiler is enabled. These is the result of the process and environment variables I get:
  • ProcessID=7428
  • JUSTMOCK_INSTANCE=5716
  • COR_ENABLE_PROFILING=
  • COR_PROFILER=
(last two variables in blank) Then I set the variables as you indicated in: http://www.telerik.com/community/forums/justmock/general-discussions/profiler-must-be-enabled-to-mock-error.aspx to:
  • JUSTMOCK_INSTANCE = 1
  • COR_ENABLE_PROFILING = 1
  • COR_PROFILER = {B7ABE522-A68F-44F2-925B-81E7488E9EC0}
Close VS, reopen again. When reopening the project, I get first the following error: vs error.png Then, I close it and then I get the following error: vs error 2.png I realized this doesn't happen if I don't set the COR_ENABLE_PROFILING variable (VS doesn't show that error again if I delete that variable). Also, when trying to run some of the tests using JustMock, VS closes unexpectedly. What can I do to fix it? How can I make JustMock work with VS 2010? Thanks, Pablo.

Stefan
Telerik team
 answered on 02 Jul 2013
2 answers
1.2K+ views
I've set up a mocked object with a couple of arranged methods. How do I pass in parameters to exercise the arranged methods?
When i call target.GetValue with 5/Aug/2012, the GetData method receives the value of 1/Jan/1983 in its startDate parameter. What do i need to do in order for the arranged methods to receive the required parameter value?

------- set up mocking ------------
            var dataAccess = Mock.Create<IDataAccess>();
            Mock.Arrange(() => dataAccess.DataExists(Arg.IsAny<SiteLocation>(), Arg.Matches<DateTime>(d => d >= startDate), Arg.Matches<DateTime>(d => d <= endDate))).Returns(true);
            Mock.Arrange(() => dataAccess.RetrieveData(Arg.IsAny<SiteLocation>(), Arg.Matches<DateTime>(d => d >= startDate), Arg.Matches<DateTime>(d => d <= endDate))).Returns(data);
            DataLoader target = new DataLoader(dataAccess);

            // act
            int actual;
            actual = target.GetValue(location, date)[0];

-------------------- called method on non-mocked object ---------------
        public List<int> GetValue(SiteLocation location, DateTime date)
        {
            var data = new List<int>();

            var temp = GetData(location, date, DateTime.Now);
            if (temp.Count > 0)
            {
                // todo: if there are gaps in the data fill with -999
                data = temp.Select(t => t.Value).ToList();
            }
            else { }

            return data;
        }

------------------------ called method on mocked object ------------------
        public List<DataRecord> GetData(SiteLocation location, DateTime startDate, DateTime endDate)
        {
            var data = new List<DataRecord>();

            if (dataAccess.DataExists(location, startDate, endDate))
            {
                data = dataAccess.RetrieveData(location, startDate, endDate);
            }else{}

            return data;
        }
Simon
Top achievements
Rank 1
 answered on 27 Jun 2013
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?