Telerik Forums
JustMock Forum
3 answers
190 views

Just need some clarification...

I am trying to use JustMock Debug View and it is not working. I am using NUnit. However, all of the examples online are using MSTest framework, so I am wondering if maybe the debug view is only supported in MSTest. The documentation does say that it only works with the [TestMethod] attribute. If that attribute is the trigger, then it seems reasonable that it may not work with [TestFixture] or [Test] attributes from Nunit.   

Mihail
Telerik team
 answered on 28 Sep 2018
1 answer
283 views
I do partial mocking of specific method through Mock.Arrange. Is there way to unmock this method to call the original method next time ?
Mihail
Telerik team
 answered on 28 Sep 2018
4 answers
165 views

I'm using NLog with the ILogger interface (and XUnit.net).  I want to verify that the Error() function is called, and I want to make the test as non-fragile as possible.  Today, the call within the function under test calls it _log.Error("format string", string, string), but that may change later and I don't want to rewrite the test every time that might get updated.  All I actually care about is that the error was logged rather than the specifics of how.

I found another person's question that was similar (Here), but the suggestion there didn't work as I'd hoped (probably because his didn't use overloads).

Today, this works:

var log = Mock.Create<ILogger>();
Mock.Arrange(() => log.Error(Arg.IsAny<string>(), Arg.IsAny<string>(), Arg.IsAny<string>())).IgnoreArguments().OccursOnce();
Assert.Throws<ApplicationException>(() => myObject.Function(badParameter);
Mock.Assert(log);

 

What I'd prefer is something like what the other linked article suggested:

var log = Mock.Create<ILogger>();
Mock.Arrange(() => log.Error(string.Empty).IgnoreArguments().OccursOnce();
Assert.Throws<ApplicationException>(() => myObject.Function(badParameter);
Mock.Assert(log);

 

I've also tried:

Mock.Arrange(() => log.Error(Arg.IsAny<string>(), Arg.IsAny<object[]>()).IgnoreArguments().OccursOnce();

 

The only one that works presently is the match with three string arguments. 

I'm assuming this is due to all of the overloads that might match (see below).  In this situation, is there any way to accomplish a more generic way of ensuring that the Error function is called without having to make it tied to the argument count?

Here's the most likely matches based on the overloads:
Public method   Error(Object)
Public method   Error(String,Object[])
Public method   Error(String, String)
Public method   Error(String, Object, Object)

Here's the full specification.

 

 

David
Top achievements
Rank 2
 answered on 09 Sep 2018
2 answers
465 views

I'm trying to use JustMock to test void methods in my class, seeing if underlying conditions are triggered by trying to asserting occurrence on underlying calls. I can't seem to find a good example of this. Here is some quick code to show what I mean.

Example Class:

    public class MockingOccurrance
    {
        public void MyVoidMethod(string myString)
        {
            switch (myString)
            {
                case "goodstring":
                    GoodString(myString);
                    break;
                default:
                    BadString(myString);
                    break;
            }
        }

        public void BadString(string badString) =>  Console.WriteLine($"{badString} is a bad string");
        public void GoodString(string goodString) => Console.WriteLine($"{goodString} is a good string");
    }

 

Example Test:

       [Test]
        public void TestMethod1()
        {
            var mo = new MockingOccurrance();
            mo.MyVoidMethod("a bad string");

            Mock.Assert(() => mo.BadString(Arg.AnyString), Occurs.Once());
        }

Obviously this doesn't work. Is there any way to make the test detect the call of BadString(string badString) without alot of smelly interfaces?

Thanks!
-Geoff

geoff
Top achievements
Rank 1
 answered on 17 Aug 2018
16 answers
285 views

We are moving to Visual Studio Team Services online and I am having trouble getting JustMock to work in the builds.  I am getting the error  "The profiler must be enabled to mock, arrange or execute the specified target".  After a lot of Googling and trial and error I edited the build definition we are using per the instructions found here : http://www.telerik.com/help/justmock/integration-tfs-2013.html

However, this is still not working.  I don't think VSTS uses the XAML build definitions anymore, and I cannot force the build to use them.  

Is there any way to get JustMock and the profiler to work with VSTS?  This is a big issue for us before I we purchase the license for the next version of JustMock.  We've invested a lot into the unit tests and not having Continuous Integration is not an option.  

Thanks,

Andrew

Mihail
Telerik team
 answered on 02 Aug 2018
1 answer
103 views

I have been trying to chase down a problem with some Unit Tests I have that use the JustMock profiler. Basically the underlying .net framework's Enum.IsDefined function is throwing a System.InvalidOperationException when passing it an int with a value of 0, which should never happen. After initially reporting this as a bug in VS/.Net to Microsoft and providing them with detailed trace information they have come back and said "We took a look at the dump and the failure appears related to methods rewritten by Telerik.CodeWeaver profiler. There is likely a bug or configuration issue with how it is rewriting these methods which lead to the unpredictable behavior you are seeing. I would recommend trying with the profiler off and then following up with Teletrik on why it is failing."

 

Below is a link to the bug report, however for some reason a large chain of the conversation including screenshots etc is locked to moderators and OP only which means you wont be able to see it. I have therefore copied the entire thread into a document and saved it as a pdf. I have attached it to this thread with a fake .png extension because this website only supports image attachments, so once downloaded just rename it to .pdf and you will be able to see the full contents of the discussion with MS.

https://developercommunity.visualstudio.com/content/problem/293705/enumisdefined-unexpected-invalidoperationexception.html

 

Mihail
Telerik team
 answered on 27 Jul 2018
3 answers
358 views

We use the commercial version of JustMock and are working on a new prototype. Along the way, somehow, my Mock.Arranges for one test class have stopped working.

These are tests for our Azure KeyVault Wrapper and are super simple.

            IKeyVault keyVault;

            [SetUp]
            public void SetUp()
            {
                var keyVaultClient = Mock.Create<IKeyVaultClient>();
                Mock.Arrange(() => keyVaultClient.GetSecretAsync("http://www.myKeyStore.com/Key1", new CancellationToken()))
                    .Returns(Task.FromResult(new SecretBundle { Value = "Secret1" }));

                Mock.Arrange(() => keyVaultClient.GetSecretAsync("http://www.myKeyStore.com/Key2", new CancellationToken()))
                    .Returns(Task.FromResult(default(SecretBundle)));

                keyVault = new KeyVault(keyVaultClient);
            }

            [Test]
            public async Task NewSecret_ShouldSucceed()
            {
                var secret = await keyVault.GetSecretAsync("Key1");

                Assert.AreEqual("Secret1", secret);
            }

            [Test]
            public async Task ShouldReturnNull_GetSecretAsync()
            {
                var secret = await keyVault.GetSecretAsync("Key2");

                Assert.AreEqual(null, secret);
            }

Both tests are returning SecretBundle objects with all default fields which seems to be an implementation from JustMock (not default(SecretBundle)). Neither have the correct values. The Arrange is simply not working.

I suspect this has something to do with references no longer being updated from Lite to Commercial, but I have no idea how to update them. The Update Reference button in the JustMock menu doesn't seem to do anything. 

Any help on how to troubleshoot would be much appreciated. We plan to depend heavily on JustMock for testing this project. Note that these tests, in their current form, were working just fine and the underlying code hasn't changed.

-Geoff

Ivo
Telerik team
 answered on 27 Jul 2018
5 answers
489 views

Not sure if this is an XUnit.Net or JustMock (or both) issue.  I have several tests on a solution that run and show passed but grayed out after a test run or build.  VS2017 shows "Unexpected error detected.  Check the Tests Output Pane for details.   The Test Output pane has a dump (see below).  The tests when run individually seem to pass and generate no errors, only when "Run All Tests" or as a result of a Build (run all tests after build set) do you see several tests grayed out.  It's always the same four tests.  Three have JustMock objects, one does not.

VS2017 Enterprise 15.2 (26430.12)

JustMock 2017.2.5303.3 (internal build to fix the 2017 profiler item)

This might be an internal build issue which is why I'm not logging it as a ticket, but thought I'd throw this in here to let you know about it.  

 

------ Run test started ------
[xUnit.net 00:00:00.2643557]   Discovering: UnitTests
[xUnit.net 00:00:01.0713800]   Discovered:  UnitTests
[xUnit.net 00:00:01.4834782]   Starting:    UnitTests
[xUnit.net 00:00:03.0127894]     [FATAL ERROR] System.ArgumentException
[xUnit.net 00:00:03.0171999]       System.ArgumentException : 'this' type cannot be an interface itself.
[xUnit.net 00:00:03.0198958]       Stack Trace:
[xUnit.net 00:00:03.0207009]        
[xUnit.net 00:00:03.0214322]         Server stack trace:
[xUnit.net 00:00:03.0221175]            at System.RuntimeTypeHandle.VerifyInterfaceIsImplemented(RuntimeTypeHandle handle, RuntimeTypeHandle interfaceHandle)
[xUnit.net 00:00:03.0227770]            at System.RuntimeTypeHandle.VerifyInterfaceIsImplemented(RuntimeTypeHandle interfaceHandle)
[xUnit.net 00:00:03.0232817]            at System.RuntimeType.GetInterfaceMap(Type ifaceType)
[xUnit.net 00:00:03.0239207]            at Telerik.JustMock.Core.MockingUtil.IsImplementedBy(MethodInfo interfaceMethod, MethodBase implMethod)
[xUnit.net 00:00:03.0243577]            at Telerik.JustMock.Core.Context.HierarchicalTestFrameworkContextResolver.MatchTestClassDispose(MethodBase method, String[] testMethodAttributes)
[xUnit.net 00:00:03.0249418]            at Telerik.JustMock.Core.Context.HierarchicalTestFrameworkContextResolver.<>c__DisplayClass31.<SetupStandardHierarchicalTestStructure>b__1f(MethodBase method)
[xUnit.net 00:00:03.0255662]            at Telerik.JustMock.Core.Context.HierarchicalTestFrameworkContextResolver.<>c__DisplayClassa.<FindTestMethod>b__9(RepositoryOperationsBase repo)
[xUnit.net 00:00:03.0261179]            at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source, Func`2 predicate)
[xUnit.net 00:00:03.0266557]            at Telerik.JustMock.Core.Context.HierarchicalTestFrameworkContextResolver.<FindTestMethod>b__8(MethodBase method)
[xUnit.net 00:00:03.0271733]            at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
[xUnit.net 00:00:03.0276714]            at System.Linq.Enumerable.<DistinctIterator>d__63`1.MoveNext()
[xUnit.net 00:00:03.0281930]            at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
[xUnit.net 00:00:03.0286994]            at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
[xUnit.net 00:00:03.0292425]            at Telerik.JustMock.Core.Context.HierarchicalTestFrameworkContextResolver.FindTestMethod(Int32& repoIdx, RepositoryOperationsBase& entryOps)
[xUnit.net 00:00:03.0297270]            at Telerik.JustMock.Core.Context.HierarchicalTestFrameworkContextResolver.ResolveRepository(UnresolvedContextBehavior unresolvedContextBehavior)
[xUnit.net 00:00:03.0301511]            at Telerik.JustMock.Core.Context.MockingContext.ResolveRepository(UnresolvedContextBehavior unresolvedContextBehavior)
[xUnit.net 00:00:03.0305562]            at Telerik.JustMock.Core.MocksRepository.GetMockMixin(Object obj, Type objType)
[xUnit.net 00:00:03.0309488]            at Telerik.JustMock.Core.Invocation..ctor(Object instance, MethodBase method, Object[] args)
[xUnit.net 00:00:03.0313652]            at Telerik.JustMock.Core.ProfilerInterceptor.InterceptCall(RuntimeTypeHandle typeHandle, RuntimeMethodHandle methodHandle, Object[] data)
[xUnit.net 00:00:03.0318462]            at System.MarshalByRefObject.GetIdentity(MarshalByRefObject obj, Boolean& fServer)
[xUnit.net 00:00:03.0323720]            at System.Runtime.Remoting.IdentityHolder.FindOrCreateServerIdentity(MarshalByRefObject obj, String objURI, Int32 flags)
[xUnit.net 00:00:03.0328321]            at System.Runtime.Remoting.RemotingServices.GetOrCreateIdentity(MarshalByRefObject Obj, String ObjURI, Boolean isInitializing)
[xUnit.net 00:00:03.0363414]            at System.Runtime.Remoting.RemotingServices.MarshalInternal(MarshalByRefObject Obj, String ObjURI, Type RequestedType, Boolean updateChannelData, Boolean isInitializing)
[xUnit.net 00:00:03.0369562]            at System.Runtime.Remoting.RemotingServices.MarshalInternal(MarshalByRefObject Obj, String ObjURI, Type RequestedType, Boolean updateChannelData)
[xUnit.net 00:00:03.0375367]            at System.Runtime.Remoting.RemotingServices.MarshalInternal(MarshalByRefObject Obj, String ObjURI, Type RequestedType)
[xUnit.net 00:00:03.0381086]            at System.Runtime.Remoting.Messaging.MessageSmuggler.FixupArg(Object arg, ArrayList& argsToSerialize)
[xUnit.net 00:00:03.0386417]            at System.Runtime.Remoting.Messaging.MessageSmuggler.FixupArgs(Object[] args, ArrayList& argsToSerialize)
[xUnit.net 00:00:03.0390906]            at System.Runtime.Remoting.Messaging.SmuggledMethodCallMessage..ctor(IMethodCallMessage mcm)
[xUnit.net 00:00:03.0395394]            at System.Runtime.Remoting.Messaging.SmuggledMethodCallMessage.SmuggleIfPossible(IMessage msg)
[xUnit.net 00:00:03.0400477]            at System.Runtime.Remoting.Channels.CrossAppDomainSink.SyncProcessMessage(IMessage reqMsg)
[xUnit.net 00:00:03.0404910]        
[xUnit.net 00:00:03.0408806]         Exception rethrown at [0]:
[xUnit.net 00:00:03.0412930]            at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
[xUnit.net 00:00:03.0417710]            at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
[xUnit.net 00:00:03.0623429]     [FATAL ERROR] System.ArgumentException
[xUnit.net 00:00:03.0998317]     [FATAL ERROR] System.ArgumentException
[xUnit.net 00:00:04.3804395]   Finished:    UnitTests
========== Run test finished: 35 run (0:00:04.5228864) ==========
Mihail
Telerik team
 answered on 26 Jul 2018
5 answers
242 views

Hi,

I'm trying to generate a code coverage report using JetBrains dotCover and the JustMockRunner. I have the following batch file, which I plan to run on a schedule, which links dotCover, runs the coverage, and then unlinks dotCover.

1.start /wait "" "C:\Program Files (x86)\Telerik\JustMock\Libraries\Telerik.JustMock.Configuration.exe" /link "dotCover"
2."dotCover.exe" cover "C:\Temp\Settings.xml"
3.start /wait "" "C:\Program Files (x86)\Telerik\JustMock\Libraries\Telerik.JustMock.Configuration.exe" /unlink "dotCover"

 

The dotCover settings file has the following settings.

01.<?xml version="1.0" encoding="utf-8"?>
02.<AnalyseParams>
03.    <TargetExecutable>C:\JustMock\JustMockRunner.exe</TargetExecutable>
04.    <TargetArguments>"C:\Program Files (x86)\NUnit 2.6.4\bin\nunit-console.exe" "C:\Temp\Release64\JustMock.Tests.dll" /noshadow /xml="C:\Temp\Coverage JustMock Test Results.xml"</TargetArguments>
05.    <Output>C:\Temp\Coverage Snapshot JustMock.dcvr</Output>
06.    <Scope>
07.        <ScopeEntry>C:\Temp\Release64\TestClass.dll</ScopeEntry>
08.    </Scope>
09.</AnalyseParams>

 

Everything seems to work correctly, with all tests passing, but I don't get any code coverage.

Have I missed something?

Mihail
Telerik team
 answered on 05 Jun 2018
1 answer
140 views

I'm attempting to update (not add) a record in a mocked DB and am not succeeding. I have a FakeDbEntries that is an IList<LogEntry>. I have Mocked my DbContext as

_mockLogRepo = Mock.Create<ILogRepo>();

_mockLogRepo.Arrange(m => m.LogEntries).ReturnsCollection(FakeDbEntries());

 

When I run the unit under test that calls the ILogRepo and does the update, the SaveChanges() never sticks.

Mihail
Telerik team
 answered on 08 May 2018
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?