Telerik Forums
JustMock Forum
6 answers
419 views
Here is a sample I am working with. My repository works with a LINQ data context against SQL Server 2008. I  would like to assert that my repository works without actually adding records to the database. I am not sure I am doing the correctly. I would like to write tests for my Add, Edit, Delete, and List functions. This is about as simple as it gets for repo's. Can you give me a hand figuring this out?

I have interfaces and classes for my problem domain; and interfaces and classes for my repositories. What must I do to mock my repositories for testing?

    [TestFixture] 
    class TextHTMLRepositoryTests 
    { 
        TextHTMLRepository _repo; 
 
        [TestFixtureSetUp] 
        public void TestSetup() 
        { 
            _repo = Mock.Create<TextHTMLRepository>(); 
        } 
 
        [Test] 
        public void CreateMockRepo() 
        { 
            Assert.IsNotNull(_repo); 
        } 
 
        [Test] 
        public void NullListTest() 
        { 
            var _texts = _repo.List(); 
            Assert.IsNull(_texts); 
        } 
 
        [Test] 
        public void PostTest() // This test fails 
        { 
            TextHTML _text = Mock.Create<TextHTML>(); 
            _text.TextID = 1; 
            Mock.Assert(() => _repo.Post(_text)); 
        } 
 
        [TestFixtureTearDown] 
        public void TestTearDown() 
        { 
            // TODO: Tear down loose objects 
        } 
    } 

Thanks,

John


Ricky
Telerik team
 answered on 26 Aug 2011
5 answers
118 views
Hi,

When trying to run tests with TestDriven.Net i get the following exception:

 An error occured executing PopulateHolidays method. ---> Telerik.JustMock.MockException: Exception has been thrown by the target of an invocation.
at .ƒ.( expecation, Object[] userArgs)
at .ƒ.–( invocation)
at ..( invocation)
at ..( invocation)
at ..Intercept(MockInvocation invocation)
at Telerik.JustMock.Weaver.Interceptors.WeaverInterceptor.€(IInvocation invocation)
at PersistenceManager_Interceptor_63dc8f881d054338ad4e199360304e8a.Intercept(PersistenceManager , Boolean& )
 at PersistenceManager.GetCalendarData()

Though when running it with MSTest runner the breakpoint stops correctly on my function.

The code of the test is something like this:
Mock.Arrange(() => PersistenceManager.GetCalendarData()).Returns(() => myDataSet());

Where GetCalendarData is the static method being mocked.

Any idea why this is happening?

Ricky
Telerik team
 answered on 18 Aug 2011
5 answers
147 views
I dug through the forums and found this post
http://www.telerik.com/community/forums/justmock/general-discussions/how-to-set-up-property-assignment.aspx

I have the Free Edition, Telerik.JustMock.dll File Version 2011.1.315.0
The promise of a build available next week in August 2010, doesn't prove to work with Behavior.CallOriginal.  (an empty Constructor works though).

Here is a sample of my TestMethod
public interface ISamplePoco
{
  string Name { get; set; }
}
 
[TestMethod]
public void GenerateMockWithPocoPropertyBehaviour()
{
  // arrange
  var target = Mock.Create<ISamplePoco>(Behavior.CallOriginal);   
  // act
  target.Name = "Dude";
  target.Name += "s";   
  // assert
  Assert.AreEqual("Dudes", target.Name);
}

I tried the above code with no parameters for the constructor, all 3 behaviour enums for the Constructor, but nothing works.
I tried to do some code where I stored the name parameter as a local variable to the test and implement my own logic, but I can't seem to get the actual value in ArrangeSet.  I tried to do something like:

string name = string.Empty;
Mock.Arrange(() => target.Name).Returns(name);
Mock.ArrangeSet((string val) => { name = val; }).IgnoreArguments();

But there is nothing like that. Is there another solution?
Thanks
Jeff
Top achievements
Rank 1
 answered on 17 Aug 2011
6 answers
310 views
Hello,

In Moq it's easy to set up property assignment behavior, for example:

            var monkey = new Mock<IMonkey>();
            monkey.SetupAllProperties();
            monkey.Object.Name = "Spike";
            Assert.AreEqual("Spike", monkey.Object.Name);

In Typemock it's not even necessary to call an analog of SetupAllProperties:

            var monkey = Isolate.Fake.Instance<IMonkey>();
            monkey.Name = "Spike";
            Assert.AreEqual("Spike", monkey.Name);

With JustMock I can't find any method that would assign a property value on a mocked instance. The following code fails in assertion:

            var monkey = Mock.Create<IMonkey>();
            Mock.ArrangeSet(() => { monkey.Name = "Spike"; });
            monkey.Name = "Spike";             Assert.AreEqual("Spike", monkey.Name); // FAILS!

How do I need to configure property assignment?

Thanks in advance
Jeff
Top achievements
Rank 1
 answered on 17 Aug 2011
1 answer
167 views
I have a unit test that, when run via the Resharper test runner (which uses NUnit), passes.  However, if I run the same test via the nunit-console (as executed by PartCover), I get the following error:

Test Error : Core.Busi.Unit_Tests.MILSearchJustMockTests.TestGetRetiredItemByID_JustMock
   Telerik.JustMock.MockException : There were some problems intercepting the mock call. Optionally, please make sure that you have turned on JustMock's profiler while mocking concrete members.
   at Telerik.JustMock.Expectations.Expectation.?(Invocation invocation) in c:\B\Basilisk\Basilisk CI Build\Sources\CodeBase\Telerik.JustMock\Expectations\Expectation.cs:line 37
   at Telerik.JustMock.Expectations.Expectation.Process[TResult](Invocation invocation) in c:\B\Basilisk\Basilisk CI Build\Sources\CodeBase\Telerik.JustMock\Expectations\Expectation.cs:line 18
   at Telerik.JustMock.Mock..?.?(? x) in c:\B\Basilisk\Basilisk CI Build\Sources\CodeBase\Telerik.JustMock\Mock.cs:line 75
   at ?.?.?[?,?]( instruction, Func`2 function) in c:\B\Basilisk\Basilisk CI Build\Sources\CodeBase\Telerik.JustMock\MockContext.cs:line 238
   at Telerik.JustMock.Mock.Arrange[TResult](Expression`1 expression) in c:\B\Basilisk\Basilisk CI Build\Sources\CodeBase\Telerik.JustMock\Mock.cs:line 72
   at Core.Busi.Unit_Tests.MILSearchJustMockTests.SetupMocks() in C:\sd\Trunk\core\Asm\Busi\Busi\Unit Tests\MILSearch.JustMock.cs:line 51

I made sure the JustMock is enabled.  I even recompiled the PartCover.dll with the instructions mentioned here, but I still get the same issue.  Is there something I need to register to run the console version of nunit/PartCover? 

Please let me know if you need more information.  Thanks!


   at Core.Busi.Unit_Tests.MILSearchJustMockTests.TestGetRetiredItemByID_JustMock() in C:\sd\Trunk\core\Asm\Busi\Busi\Unit Tests\MILSearch.JustMock.cs:line 67
Ricky
Telerik team
 answered on 12 Aug 2011
1 answer
295 views
I'm trying to Mock an HttpWebRequest (from the System.Net namespace) object, but I keep getting runtime errors.  It seems that the only constructor for HttpWebRequest is protected and has been Deprecated by Microsoft.  If this is the case, how would I could about Mocking an object which doesn't give access to it's constructor?

Here is my code.  It dies when Arranging the HttpUtils.CreateWebRequest call.  CreateWebRequest is  a static method of the non-static class HttpUtils.

private HttpWebRequest _webRequestMock;

private void SetupMocks()
{
	_webRequestMock = Mock.Create<HttpWebRequest>();
_webResponseMock = Mock.Create<WebResponse>(); Mock.SetupStatic<HttpUtils>(Behavior.Strict); Mock.Arrange(() => HttpUtils.CreateWebRequest(Arg.IsAny<string>())).Returns(_webRequestMock); Mock.Arrange(() => _webRequestMock.GetResponse()).Returns(_webResponseMock); }
Ricky
Telerik team
 answered on 10 Aug 2011
1 answer
340 views
Hi!

When I use Arg.IsAny in the arrange for a private method, as follows:

 

Mock.NonPublic.Arrange<bool>(

target,

"IsUSPriceChangeOnCanadianAdoptedRSTitle",

mockedDBTrans,

Arg.IsAny<TitleRequestDataset.TitleRequestRow>())

.DoInstead( () => {calledIsUSPriceChangeOnCanadianAdoptedRSTitle =  true;} )

.Returns(true);

 
I get an ArgumentException at run time with the following message:

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.

Please advise on how to get around this.

Thanks,
Asim

Ricky
Telerik team
 answered on 08 Aug 2011
3 answers
121 views
Hi,
I would really like to implement JustMock into some of our projects. However, it is causing our PostSharp aspects to puke during compilation when it is installed. Gael mentioned that they were able to work with TypeMock to work out conflicts between those products. Is there any possibility of you guys working with them to get these conflicts resolved too? We see major benefits to using both products and would love the ability for them to exist in harmony.
ian
Ricky
Telerik team
 answered on 05 Aug 2011
2 answers
140 views
Hi folks,

I am trying to use JustMock to mock a SharePoint collection (the real thing cannot be used as it fails without a SharePoint context). I cannot figure out how to add items the collection. Here is my code.
var uut = Mock.Create<SPRoleDefinitionBindingCollection>();
 
var role = Mock.Create<SPRoleDefinition>();
Mock.Arrange(() => role.BasePermissions)
    .Returns(SPBasePermissions.ViewUsageData | SPBasePermissions.EditListItems | SPBasePermissions.DeleteListItems);
uut.Add(role);
 
var result = uut.ContainsPermission(SPBasePermissions.DeleteListItems);
Assert.IsTrue(result);

I would like to add the SPRoleDefinition instance called role to the SPRoleDefinitionBindingCollection. The uut.Add call is obviously being ignored, which is indicated by the fact that uut.Count is zero. I would expect this to work...

Can you help?

Thanks in advance and kr, Bernd.
Bernd Rickenberg
Top achievements
Rank 1
 answered on 04 Aug 2011
1 answer
11.4K+ views
Hi!

Suppose my method-under-test looks like this:

public void TestMe()
{
    DataSet d1 = null;
    DataSet d2 = null;
    bool process = false;
    Helper helper = new Helper();
    process = helper.LoadFromDB(out d1, out d2) && d1 != null && d1.Tables[0] != null && d1.Tables[0].Count > 0

    if (process)
    {
        [...run business logic here...]
    }
    else
    {
        throw new Exception("Failed to load data from the db");
    }
}

In order to circumvent using a physical database, I mock "helper.LoadFromDB" in my unit test. The delegate I use in the "DoInstead" method populates the test1DS and test2DS datasets with made-up data, and the "Returns" in my arrange returns true.

 


Mock
.Arrange(() =>  helper.LoadFromDB(out test1DS, out test2DS))

.DoInstead(someDelegate)

.Returns(true);

 
The problem is that the data sets the mock implementation populates are the ones declared within the unit test, not the ones declared in the method-under-test. So the process flag in the code snippet above still returns false (due to d1 being null), and the business logic I wanted to test (within the "if (process)" block above) never gets run.

Is there a way to map (for lack of a better word) the test1DS and test2DS (that I declared in the unit test code and populated in my DoInstead delegate) to the data sets d1 and d2 declared within the method-under-test, so as to allow the process flag to evaluate to true once the mocked implementation has run?

Thanks,
Asim

Ricky
Telerik team
 answered on 01 Aug 2011
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?