Telerik Forums
JustMock Forum
1 answer
64 views

I've completed the instructions in the document on configuring Telerik.JustMock.Build.Workflow into our Build Template but unfortunately the build process no longer runs the tests. It just outputs 'No Test Results'. I've even went into the Test.csproj and added the before and after test and added the JustMock targets like the instructions for MSBuild state. 

Anyone seen this before?

Thanks,
Jason
Ricky
Telerik team
 answered on 02 Nov 2012
4 answers
58 views
Here is a unit test setup that I am having issues with....  This code exists within a class called TestBase which my unit test classes inherit from....
#region Mocked Members
 
       protected HardCodedSiteOptionsEntity Target;
       protected IDependencyInjection InjectorMock;
       protected IMessageOperations MessageMock;
 
       #endregion
 
       [SetUp]
       public void InitializeBase()
       {
           Target = Mock.Create<HardCodedSiteOptionsEntity>(Behavior.CallOriginal);
           InjectorMock = Mock.Create<IDependencyInjection>();
           MessageMock = Mock.Create<IMessageOperations>();
 
           Target.Arrange(mockedObject => mockedObject.MessageOperationsHelper).Returns(MessageMock);
 
           //Target.MessageOperationsHelper = MessageMock;
       }

The issue I am having is when I have the code setup as shown I recieve a NullReferenceException on the Target.Arrange method....  I am using the Q3 release of JustMock.

When I comment out the Target.Arrange line and uncomment the line afterwards, it seems to work as expected. 
Here is a snippet of the Target( class under test)

internal class HardCodedSiteOptionsEntity : ISiteOptions, IBlockEntityPartBuilder<uint>
    {
        #region Internal Properties
 
        internal virtual BitArray StatusMaskData { get; set; }
        internal virtual IDependencyInjection InjectorHelper { get; set; }
        internal virtual IMessageOperations MessageOperationsHelper { get; set; }
 
        #endregion
 
        #region Constructor
 
        internal HardCodedSiteOptionsEntity()
        {
            InjectorHelper = new DependencyInjector();
            MessageOperationsHelper = InjectorHelper.InjectEntity<IMessageOperations>();
            StatusMaskData = new BitArray(32, false);
        }
}

I have InternalsVisibleTo attribute set in my assemblyinfo.cs so the internal visibility shouldn't be causing the issue....
Ricky
Telerik team
 answered on 01 Nov 2012
5 answers
174 views

I have Visual Studio 2010 and Visual Studio 2012 installed. Using JustMock version 2012.3.1016.3

Running the tests below I get the following in both VS 2010 and 2012.

Test Name: TestReadXML
Test FullName: DemoSerializationExceptionMock.ReadXMLMockIBusinessPrincipal_Tests.TestReadXML
Test Source: C:\Projects\MAS Applications\Experimental\Source\DemoSerializationExceptionMock\DemoSerializationExceptionMock\ReadXMLMockIBusinessPrincipal_Tests.vb : line 47
Test Outcome: Failed
Test Duration: 0:00:00.00937

Result Message: 
Test method DemoSerializationExceptionMock.ReadXMLMockIBusinessPrincipal_Tests.TestReadXML threw exception:
System.Runtime.Serialization.SerializationException: Type is not resolved for member 'IPrincipalProxy+bce4039c8c9143c29217f51daf99a9a8,Telerik.JustMock, Version=1.0.0.0, Culture=neutral, PublicKeyToken=8b221631f7271365'.
Result StackTrace: 
at System.AppDomain.get_Evidence()
   at System.AppDomain.get_EvidenceNoDemand()
   at System.AppDomain.get_Evidence()
   at System.Configuration.ClientConfigPaths.GetEvidenceInfo(AppDomain appDomain, String exePath, String& typeName)
   at System.Configuration.ClientConfigPaths.GetTypeAndHashSuffix(AppDomain appDomain, String exePath)
   at System.Configuration.ClientConfigPaths..ctor(String exePath, Boolean includeUserConfig)
   at System.Configuration.ClientConfigPaths.GetPaths(String exePath, Boolean includeUserConfig)
   at System.Configuration.ClientConfigurationHost.RequireCompleteInit(IInternalConfigRecord record)
   at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
   at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
   at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
   at System.Configuration.ConfigurationManager.GetSection(String sectionName)
   at System.Xml.XmlConfiguration.XmlReaderSection.get_ProhibitDefaultUrlResolver()
   at System.Xml.XmlReaderSettings.GetXmlResolver_CheckConfig()
   at System.Xml.Schema.XmlSchemaSet.PreprocessSchema(XmlSchema& schema, String targetNamespace)
   at System.Xml.Schema.XmlSchemaSet.Add(String targetNamespace, XmlSchema schema)
   at System.Xml.Schema.XmlSchemaSet.Add(XmlSchema schema)
   at System.Xml.Schema.XmlSchemaInference.CreateXmlSchema(String targetNS)
   at System.Xml.Schema.XmlSchemaInference.AddElement(String localName, String prefix, String childURI, XmlSchema parentSchema, XmlSchemaObjectCollection addLocation, Int32 positionWithinCollection)
   at System.Xml.Schema.XmlSchemaInference.InferSchema1(XmlReader instanceDocument, XmlSchemaSet schemas)
   at System.Xml.Schema.XmlSchemaInference.InferSchema(XmlReader instanceDocument)
   at System.Data.DataSet.InferSchema(XmlDocument xdoc, String[] excludedNamespaces, XmlReadMode mode)
   at System.Data.DataSet.ReadXml(XmlReader reader, Boolean denyResolving)
   at System.Data.DataSet.ReadXml(TextReader reader)
   at DemoSerializationExceptionMock.ReadXMLMockIBusinessPrincipal_Tests.TestReadXML() in C:\Projects\MAS Applications\Experimental\Source\DemoSerializationExceptionMock\DemoSerializationExceptionMock\ReadXMLMockIBusinessPrincipal_Tests.vb:line 43

 

Imports Microsoft.VisualStudio.TestTools.UnitTesting.Web
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Imports Telerik.JustMock
Imports System.Security.Principal
 
<TestClass()> _
Public Class ReadXMLMockIBusinessPrincipal_Tests
    Private testContextInstance As TestContext
 
    Public Property TestContext As TestContext
        Get
            Return testContextInstance
        End Get
        Set(ByVal Value As TestContext)
            testContextInstance = Value
        End Set
    End Property
 
    <TestInitialize()>
    Public Sub TestInit()
        Dim idnty As IIdentity = Mock.Create(Of IIdentity)()
        Mock.Arrange(Function() idnty.AuthenticationType).Returns("MOCK")
        Mock.Arrange(Function() idnty.IsAuthenticated).Returns(True)
        Mock.Arrange(Function() idnty.Name).Returns("mockident")
        Dim prince As IPrincipal = Mock.Create(Of IPrincipal)()
        Mock.Arrange(Function() prince.Identity).Returns(idnty)
        Mock.Arrange(Function() prince.IsInRole(Arg.AnyString())).Returns(True)
        System.Threading.Thread.CurrentPrincipal = prince
    End Sub
 
    Dim elem As XElement = <Root>
                           </Root>
 
    <TestMethod()> _
    Public Sub TestReadXML_IgnoreSchema()
        Dim ds As New DataSet
        ds.ReadXml(New IO.StringReader(elem.ToString), XmlReadMode.IgnoreSchema) '<- Passed
    End Sub
 
    <TestMethod()> _
    Public Sub TestReadXML()
        Dim ds As New DataSet
        ds.ReadXml(New IO.StringReader(elem.ToString)) '<-Fails
    End Sub
End Class            
Ricky
Telerik team
 answered on 01 Nov 2012
15 answers
342 views
Hi,
     I downloaded the trial version of Justmock. I'm trying to run the tests in HttpContextTest.cs. I'm getting the following error while running it. Here is the code it's trying to run. JustMock was enabled in the menu.
[TestClass]
    public class HttpContextTest
    {
       static HttpContextTest()
        {
            Mock.Partial<HttpContext>().For<HttpContext, HttpRequest>(x => x.Request);
            Mock.Partial<HttpContext>().For(() => HttpContext.Current);
        }
        [TestMethod]
        public void ShouldMockCurrentHtppContext()
        {
            bool called = false;
            Mock.Arrange(() => HttpContext.Current).DoInstead(() => called = true);
            var ret = HttpContext.Current;
            Assert.True(called);
        }
}


Test 'Telerik.JustMock.Tests.Elevated.Integration.HttpContextTest.ShouldMockCurrentHtppContext' failed: 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.ThrowForInvalidCall(IInvocation invocation)
at Telerik.JustMock.Expectations.Expectation.Process[TResult](IInvocation invocation)
at Telerik.JustMock.Mock.<>c__DisplayClass1`1.<Arrange>b__0(MockContext`1 x)
at Telerik.JustMock.MockContext.Setup[TDelgate,TReturn](Instruction instruction, Func`2 function)
at Telerik.JustMock.Mock.Arrange[TResult](Expression`1 expression)
Elevated\Integration\HttpContextTest.cs(32,0): at Telerik.JustMock.Tests.Elevated.Integration.HttpContextTest.ShouldMockCurrentHtppContext()
Kaloyan
Telerik team
 answered on 26 Oct 2012
1 answer
132 views
Hi I am trying to set up a unit test that has reference of membership.provider in it.  This is done in MVC3. 

I tried doing a couple things but I got no luck. 

On this accountcontroller, the Login Method goes through a large amount of logic. 

I tried this:

Mock.Arrange(() => Membership.Provider).Returns(fakeProvider);


where fakeprovider was Mock.Create<CustomMembershipProvider>();

It is always returning as null. 

I was able to get my unit test to make sure that it can check the logic of the !ModelState.IsValid, but I cannot seem to get the two bolded lines in the code below to return what I want it to return.

I tried to use the doinstead but I had to make the Arrange/ArrangeSet in a try/catch block. 

Is there something that I am missing that is making this always null. 

Any help would be greatly appreciate.  Thanks.

 

public ActionResult Login(AccountLogin accountLogin)
if (!ModelState.IsValid)
{
return View(accountLogin);
}
CustomMembershipProvider membershipProvider = Membership.Provider as CustomMembershipProvider;
MembershipUser user = membershipProvider.GetUser(accountLogin.UserName);
 
if (user != null && user.LastLoginDate.AddDays(180) < DateTime.Now)
{
      membershipProvider.LockUser(user.UserName);
ModelState.AddModelError("", inactivityLockedMessage);
return View(accountLogin);
 }
if (Membership.ValidateUser(accountLogin.UserName, AESCryptography.Encrypt(accountLogin.Password)))
      {
  // store single session ID
user.Comment = Guid.NewGuid().ToString();
Membership.UpdateUser(user);
public void Login_Where_ModelState_IsNot_Valid_test() //this unit test passes with no issue
{
var target = new AccountController();
var accountLogin = new AccountLogin();
var result = new ViewResult();
  
Mock.Arrange(() => target.Login(accountLogin)).OccursOnce();
//to make target.ModelState.IsValid return false
target.ModelState.AddModelError("key", "needs to be false");
  
result = (ViewResult)target.Login(accountLogin);
  
Assert.IsTrue(target.ModelState.IsValid == false);
Assert.IsTrue(result.ViewName == string.Empty);
Mock.Assert(target.Login(accountLogin));
}

 

 

 

 

[TestMethod]
public void Login_Where_Inactivity_is_Hit_test()
{
    string inactivityLockedMessage = "Your account is locked due to inactivity.  Please contact AI Portal support.";
       //Arrange
    controller = Mock.Create<AccountController>();
    accountLogin = new AccountLogin { UserName = "" } //string.empty;
    action = Mock.Create<ActionResult>(); 

    Mock.Arrange(() => controller.ModelState.IsValid).Returns(true);
    CustomMembershipProvider fakeProvider = Mock.Create <CustomMembershipProvider>();
    MembershipUser user = Mock.Create<MembershipUser>();
             
    bool called = false
    try
     {
     Mock.ArrangeSet(() => action = controller.Login(Arg.IsAny<AccountLogin>()))
     .DoInstead(() =>
     {
     Mock.ArrangeSet(() => user.LastLoginDate.AddDays(180));
     Mock.Arrange(() => user.LastLoginDate < DateTime.Now).Returns(true);
     controller.ModelState.AddModelError("", inactivityLockedMessage);
     called = true;
     })
     .Returns(action);
     }
     catch (NullReferenceException)
     {
    Mock.Arrange(() => fakeProvider.LockUser(accountLogin.UserName)).Returns(true);
    Mock.ArrangeSet(() => user.LastLoginDate.AddDays(180));
    Mock.Arrange(() => user.LastLoginDate < DateTime.Now).Returns(true);
    controller.ModelState.AddModelError("", inactivityLockedMessage);
    called = true;
     }
  
    //Assert 
    Mock.Assert(user.LastLoginDate);
    Mock.Assert(fakeProvider);
    Assert.IsTrue(called);
    Assert.IsFalse(controller.ModelState.IsValid);
    Assert.IsTrue(controller.ModelState.Count==1, "should not be more than 1 error");
    string modelerror = controller.ModelState[""].Errors[0].ErrorMessage;
    Assert.IsTrue(inactivityLockedMessage==modelerror, "should be equal");  
}

Kaloyan
Telerik team
 answered on 25 Oct 2012
3 answers
118 views

I'm having trouble mocking File.WriteAllBytes. Here's my test code:

var called = false;
var ccr = new Ccr { Pdf = new byte[73], SubmissionId = 3 };
Mock.Replace<string, byte[]>((s, b) => File.WriteAllBytes(s, b)).In<CcrFileWriter>(x => x.WriteToDisk(ccr));
Mock.Arrange(() => File.WriteAllBytes(null, null)).IgnoreArguments().DoInstead(()=> called = true);
var writer = new CcrFileWriter();
writer.WriteToDisk(ccr);
Assert.IsTrue(called);

It's not working. It's not bypassing File.WriteAllBytes and the test fails.
Maybe I'm not understanding how this should work?

Ricky
Telerik team
 answered on 24 Oct 2012
7 answers
135 views
Does JustMock support silverlight code? If not are there any plans to support this in the future?
Kaloyan
Telerik team
 answered on 24 Oct 2012
1 answer
222 views
I have a unit test that is attempting to test a very simple method.  The method under test simply calls two other methods (interface methods that are marked as virtual in the implementation).  I use the following code in the unit test....
IEnumerable<byte> passedMessage1 = new byte[16];
 
            Mock.Arrange(() => MessageOperationsMock.InsertNetworkAddressIntoMessage
                (Target.PrimaryReportingAddress, passedMessage1, 3))
                .DoNothing()
                .Returns(passedMessage1)
                .OccursOnce();
 
            Mock.Arrange(() => MessageOperationsMock.InsertNetworkAddressIntoMessage
                (Target.AlternateReportingAddress, passedMessage1, 25))
                .DoNothing()
                .Returns(passedMessage1)
                .OccursOnce();
 
            Target.PrimaryReportingAddress = LocalTestScenarios.TestIPAddress1;
            Target.AlternateReportingAddress = LocalTestScenarios.TestIPAddress2;
 
            Target.InsertNetworkAddressesIntoPart(passedMessage1);
 
            Mock.Assert(MessageOperationsMock);


The Target method is....
internal virtual IEnumerable<byte> InsertNetworkAddressesIntoPart(IEnumerable<byte> messageBeingCreated)
        {
            messageBeingCreated = MessageOperationsHelper.InsertNetworkAddressIntoMessage(PrimaryReportingAddress, messageBeingCreated, 3);
            messageBeingCreated = MessageOperationsHelper.InsertNetworkAddressIntoMessage(AlternateReportingAddress, messageBeingCreated, 25);
 
            return messageBeingCreated;
        }

and here is the mocking setup....

protected HardCodedMonitoringSettingsEntity Target;
        protected IDependencyInjection InjectorMock;
        protected IValidationOperations ValidatorMock;
        protected IMessageOperations MessageOperationsMock;
 
        [SetUp]
        public void InitializeBase()
        {
            Target = Mock.Create<HardCodedMonitoringSettingsEntity>(Behavior.CallOriginal);
            InjectorMock = Mock.Create<IDependencyInjection>();
            ValidatorMock = Mock.Create<IValidationOperations>();
            MessageOperationsMock = Mock.Create<IMessageOperations>();
 
            Target.DependencyInjector = InjectorMock;
            Target.ValidationOperationsHelper = ValidatorMock;
            Target.MessageOperationsHelper = MessageOperationsMock;
        }


The problem is the test says that expected called once but was called 0 times.  What I see when I debug the code is that my passedMessage variable goes from a byte array to some other type of object (goes from saying byte[16] to count = 0 after the first method is called.

Any thoughts?
Kaloyan
Telerik team
 answered on 24 Oct 2012
1 answer
114 views
I have this target inside my build file

<target name="Test" description="Test" depends="Build">
      <loadtasks assembly="C:\Program Files (x86)\Telerik\JustMock\Libraries\Telerik.JustMock.NAnt.dll" />
      <justmockstart />
      <nunit2>
          <formatter type="Xml" usefile="true" extension=".xml" outputdir="${build.dir}" />
          <test assemblyname="Tests/bin/release/Tests.dll" appconfig="Tests/bin/release/Tests.dll.config">
              <categories>
        <exclude name="FIXME" />
      </categories>
          </test>
      </nunit2>
      <justmockstop />
 
</target>

1. The "loadtasks" task works fine
2. justmockstart says nothing
3. I have a test with the following assert:

Assert.IsTrue(Mock.IsProfilerEnabled, "Profile is enabled");

And it fails, so Shouldn't the task "justmockstart" enable profiling in my tests?

Kaloyan
Telerik team
 answered on 23 Oct 2012
1 answer
54 views
Is this possible?

I would like to arrange mocks in a class that the test class instantiates. It seems that the mock context doesn't carry over though, as none of my arranges get used. If i simply move the arranges to the test class, all seems happy.
Kaloyan
Telerik team
 answered on 23 Oct 2012
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?