Telerik Forums
JustMock Forum
3 answers
180 views
Hi,

is it possible to mock P/Invoke (Windows API) calls using JustMock commercial edition? I have a helper class which uses a few APIs from advapi32.dll and kernel32.dll to log-on to a remote file share and would like to unit test it and assert whether the right APIs were called with the right parameters.

E.g. the API
[DllImport("advapi32.dll", SetLastError = true)]
>
private static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);


is called in my code and I'd like to assert that the correct user name, domain, password etc. were passed to it.

Regards, Robert
Ricky
Telerik team
 answered on 19 Apr 2011
3 answers
183 views
Hi,

let's take the following method which saves a MemoryStream to a file:

public void Write(MemoryStream stream, string fileName)
{
    using (FileStream fs = new FileStream(fileName, FileMode.Create))
    {
        stream.WriteTo(fs);
    }
}

I would like to write a unit test that ensures that the the FileStream instance in this method was created with the particular constructor (string path, FileMode mode) and that correct parameters were passed to it (the value of fileName and FileMode.Create in this case). At the same time, I'd like that the FileStream instance created in this method does nothing, i.e. that nothing is saved to the file system upon calling this method in a unit test. So essentially, I would need to mock the FileStream object so that it a) does nothing and b) I can check whether the particular constructor was called with particular parameters.

Any way to achieve this using JustMock (commercial edition)?

Thanks, Robert
Robert
Top achievements
Rank 1
 answered on 08 Apr 2011
1 answer
173 views
I'm getting a NullReferenceException when I try to Arrange a basic property:

Source:
public DbEntityEntry<TEntityType> Entry<TEntityType>(TEntityType Entity) where TEntityType : class
{
    if (_entries.ContainsKey(Entity))
    {
        return _entries[Entity] as DbEntityEntry<TEntityType>;
    }
    else
    {
        var mockEntry = Mock.Create<DbEntityEntry<TEntityType>>();
        Mock.Arrange<TEntityType>(() => mockEntry.Entity).Returns(Entity as TEntityType);
        _entries.Add(Entity, mockEntry);
        return mockEntry;
    }
}



The NullReferenceException throws on the "Mock.Arrange..." line, with the following stack trace:

   at Telerik.JustMock.DynamicProxy.MethodInvocation.Continue() in c:\B\Basilisk\Basilisk CI Build\Sources\CodeBase\Telerik.JustMock\DynamicProxy\MethodInvocation.cs:line 159
   at Telerik.JustMock.Interceptors.ProxyInterceptor.Intercept(IInvocation invocation) in c:\B\Basilisk\Basilisk CI Build\Sources\CodeBase\Telerik.JustMock\Interceptors\ProxyInterceptor.cs:line 31
   at DbEntityEntry`1_Proxy_d3528d76a583445191d2089b7dd0b53f._GetHashCode(MethodInvocation , Int32 , Boolean )
   at DbEntityEntry`1_Proxy_d3528d76a583445191d2089b7dd0b53f.GetHashCode()
   at Telerik.JustMock.Weaver.ContainerContext.GetKey(Type targetType, MethodInfo methodInfo, Object target) in c:\B\Basilisk\Basilisk CI Build\Sources\CodeBase\Telerik.JustMock\Weaver\ContainerContext.cs:line 134
   at Telerik.JustMock.Weaver.ContainerContext.Get(Type targetType, MethodInfo methodInfo, Object target) in c:\B\Basilisk\Basilisk CI Build\Sources\CodeBase\Telerik.JustMock\Weaver\ContainerContext.cs:line 91
   at Telerik.JustMock.Weaver.ContainerContext.Get(MethodInfo mi, Object target) in c:\B\Basilisk\Basilisk CI Build\Sources\CodeBase\Telerik.JustMock\Weaver\ContainerContext.cs:line 77
   at Telerik.JustMock.Weaver.Interceptors.WeaverInterceptor.OnInvocation(IInvocation invocation) in c:\B\Basilisk\Basilisk CI Build\Sources\CodeBase\Telerik.JustMock\Weaver\Interceptors\WeaverInterceptor.cs:line 97
   at Telerik.JustMock.Weaver.Interceptors.WeaverInterceptor.Telerik.JustMock.Weaver.Interceptors.Abstraction.IWeaverInterceptor.Intercept(IInvocation invocation) in c:\B\Basilisk\Basilisk CI Build\Sources\CodeBase\Telerik.JustMock\Weaver\Interceptors\WeaverInterceptor.cs:line 44
   at Telerik.JustMock.MockContext`1.SetupMock(Object obj, Type mockTarget, MethodInfo method, Expression expression) in c:\B\Basilisk\Basilisk CI Build\Sources\CodeBase\Telerik.JustMock\MockContext.cs:line 109
   at Telerik.JustMock.MockContext`1.SetupMock(Expression`1 expression) in c:\B\Basilisk\Basilisk CI Build\Sources\CodeBase\Telerik.JustMock\MockContext.cs:line 26
   at Telerik.JustMock.Mock.<>c__DisplayClass1`1.<Arrange>b__0(MockContext`1 x) in c:\B\Basilisk\Basilisk CI Build\Sources\CodeBase\Telerik.JustMock\Mock.cs:line 74
   at Telerik.JustMock.MockContext.Setup[TDelgate,TReturn](Instruction instruction, Func2`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
...


I am using the Free Edition and just updated to the March 16 release, but this didn't help.  Any ideas what I might be doing wrong?

Thanks
Ricky
Telerik team
 answered on 29 Mar 2011
1 answer
73 views
How can I arrange the mock to assert that a property setter is never called?

I've tried the following: 
Mock.ArrangeSet(() => mockVirtualEntity.EffectiveFrom = DateTime.Now).IgnoreArguments().OccursNever();

I dont care what the value being set is - I just want to make sure the property setter is never called?

Ricky
Telerik team
 answered on 25 Mar 2011
1 answer
237 views
I'm evaluating JustMock and have some unit tests that I want to write against an abstract base class. I wish to test some functionality in the base class. Can JustMock create a concrete class in which I can test with or do I need to implement a derived class myself? I want the base class method called, I just would like to know if JustMock provides any support here.
Ricky
Telerik team
 answered on 24 Mar 2011
3 answers
197 views

I'm trying to mock out adding a folder to a SPList, using the code below:

SPWeb web = Mock.Create<SPWeb>();
SPListCollection lists = Mock.Create<SPListCollection>();
SPList list = Mock.Create<SPList>();
SPListItemCollection listItems = Mock.Create<SPListItemCollection>();
SPListItem li = Mock.Create<SPListItem>();
  
Mock.Arrange(() => web.Lists).Returns(lists);
Mock.Arrange(() => lists[Arg.AnyString]).Returns(list);
Mock.Arrange(() => list.Items).Returns(listItems);
Mock.Arrange(() => list.Folders).Returns(listItems);
Mock.Arrange(() => li.Web).Returns(web);
  
li = list.Items.Add("",SPFileSystemObjectType.Folder, "Folder One");
li.Update();

The exception I'm getting when I execute my test in Gallio is a NullReferenceException below:
System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.SharePoint.SPListItem.get_Web()
   at Microsoft.SharePoint.SPListItem.UpdateInternal(Boolean bSystem, Boolean bPreserveItemVersion,
            Guid newGuidOnAdd, Boolean bMigration, Boolean bPublish,
            Boolean bNoVersion, Boolean bCheckOut, Boolean bCheckin, Boolean suppressAfterEvents)
   at Microsoft.SharePoint.SPListItem.Update()
   at CreateFoldersInSpList.Tests.TestSuite.GetSpList()
            in C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\Projects\
            CreateFoldersInSpList\CreateFoldersInSpList.Tests\TestSuite.cs:line 57

For this reason, I added the Mock.Arrange(() => li.Web).Returns(web) statement but am still getting this exception.

What do I need to do to be able to continue with this test?
Ricky
Telerik team
 answered on 23 Mar 2011
1 answer
208 views
I am in the second iteration of an Agile project developing a SharePoint solution and I am struggling with Unit Testing our SharePoint code.

I am trying to Mock up a SPListItemCollection with a specific structure: ID, Name, Department, Division, and I want to populate the list with test data so I can Unit Test our code.

Here is where I get stuck.

I have the following example working but I am at a loss as to how I create the fields and populate the list. I would appreciate any help on this.

            var spWeb = Mock.Create<SPWeb>();
            var spList = Mock.Create<SPList>();
            var spListCollection = Mock.Create<SPListCollection>();
            var spListItemCollection = Mock.Create<SPListItemCollection>();


            Mock.Arrange(() => spWeb.Lists).Returns(spListCollection);
            Mock.Arrange(() => spListCollection[Arg.AnyString]).Returns(spList);
            Mock.Arrange(() => spList.GetItems(Arg.IsAny<SPQuery>())).Returns(spListItemCollection);


            Assert.AreEqual(spListCollection, spWeb.Lists);
            Assert.AreEqual(spList, spWeb.Lists["myList"]);
            Assert.AreEqual(spListItemCollection, spWeb.Lists["myList"].GetItems(new SPQuery()));

Many thanks

Gary
Ricky
Telerik team
 answered on 10 Mar 2011
3 answers
177 views
Okay, I am quite new at UnitTesting and the Mocking thing so bear with me an my ignorance.
Since MVC is great for UnitTesting, I thought I would start to try to wrap my head around these concepts/practices for several reasons. 
So...I was looking at MOQ and then I remembered Telerik had a beta going of JustMock, So I decided to try JustMock first.

So, in delving into unit tests, mocking, and MVC, I came across the following link: http://www.hanselman.com/blog/ASPNETMVCSessionAtMix08TDDAndMvcMockHelpers.aspx which has some Mvc http mocking helpers.  Which I want to ultimately try to use to test a controller doing a post.  Since my controller also looks/processes some info from the HttpRequestBase Controller.Request, I think I need to mock the request in my unit test (could be wrong, but makes sense). Anyway, after reading the above link, it became painfully obvious that different mock libraries use different syntax, making things all that more confusing. The link uses examples for Rhino, Moq, and TypeMock..all slightly different.. grrr.  I learn by examples, trying, so I am trying to equate what I see in the above link to how it needs to be in JustMock.

In their example (I'll just focus on the Moq, since that's my second choice for mocking and seems to be a good/acceptable mocking tool)
Moq:
public static void SetHttpMethodResult(this HttpRequestBase request, string httpMethod) 
    Mock.Get(request) 
    .Expect(req => req.HttpMethod) 
    .Returns(httpMethod); 
 
 
 
is the following a correct JustMock equiv?
public static void SetHttpMethodResult(this HttpRequestBase request, string httpMethod) 
    var test = Mock.Create<HttpRequestBase>(); 
    Mock.Arrange(() => test).Returns(request); 
    Mock.Arrange(() => test.HttpMethod).Returns(httpMethod); 
 

and another:
//Moq: 
public static HttpContextBase FakeHttpContext() 
    var context = new Mock<httpcontextbase>(); 
    var request = new Mock<httprequestbase>(); 
    var response = new Mock<httpresponsebase>(); 
    var session = new Mock<httpsessionstatebase>(); 
    var server = new Mock<httpserverutilitybase>(); 
 
    context.Expect(ctx => ctx.Request).Returns(request.Object); 
            context.Expect(ctx => ctx.Response).Returns(response.Object); 
    context.Expect(ctx => ctx.Session).Returns(session.Object); 
    context.Expect(ctx => ctx.Server).Returns(server.Object); 
 
    return context.Object; 
 
//my attempt to convert to JustMock: 
public static HttpContextBase FakeHttpContext() 
    var context = Mock.Create<HttpContextBase>(); 
    var request = Mock.Create<HttpRequestBase>(); 
    var response = Mock.Create<HttpResponseBase>(); 
    var session = Mock.Create<HttpSessionStateBase>(); 
    var server = Mock.Create<HttpServerUtilityBase>(); 
 
    Mock.Arrange(() => context.Request).Returns(request); 
    Mock.Arrange(() => context.Response).Returns(response); 
    Mock.Arrange(() => context.Session).Returns(session); 
    Mock.Arrange(() => context.Server).Returns(server); 
 
    return context; 
 
 
Right? Wrong?

Thank you for your time.


Ricky
Telerik team
 answered on 09 Mar 2011
1 answer
144 views
I just started using JustMock but I've searched for a solution to this problem and haven't found it yet so I'll pose the problem here.
As in the distilled example below, I have a class that inherits from another class.  The parent class defines multiple protected virtual methods that the child class does not override.  I'm interested in testing a specific protected virtual method the child does implement but my attempts to mock the non-overridden parent methods fail with the following exception:

[System.ArgumentException] = {"Could not resolve the target method; make sure that you have provided arguments correctly."}

(In the example, it is thrown on the call to Mock.NonPublic.Arrange(..) )

Am I doing something wrong? Is there a way within JustMock to get around this error? Or must I subclass my child class further and override all the methods I'm interested in mocking in order to get it to work?  That last option does work, but it's not exactly ideal.
Any help is greatly appreciated!

Charles

public class Foo
{
    public Foo()
    {
    }
 
    protected virtual void MethodToMock()
    {
    }
 
    protected virtual void MethodToTest()
    {
    }
}
 
 
public class Bar : Foo
{
    public Bar()
    {
    }
 
    protected override void MethodToTest()
    {
        MethodToMock();
    }
}
 
 
[TestMethod]
public void BarTest()
{
    var mock = Mock.Create<Bar>(Behavior.CallOriginal);
    Mock.NonPublic.Arrange(mock, "MethodToMock").DoNothing();
 
    // Test MethodToTest here
}
Ricky
Telerik team
 answered on 09 Mar 2011
3 answers
116 views
Is it possible to use JustMock for Compact Framework projects in VS 2008? For now, I am using the free edition.
The following does not compile, where "IService" is just an example interface with a single method, "DoSomething()":

            IService service =  Mock.Create<IService>();
                
Mock.Arrange(()=>service.DoSomething()).MustBeCalled();

The compiler spits out this error:
Error 2 Cannot convert lambda expression to type 'System.Linq.Expressions.Expression`1<Telerik.JustMock.Action2>' because it is not a delegate type
Ricky
Telerik team
 answered on 24 Feb 2011
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?