Telerik Forums
JustMock Forum
4 answers
1.0K+ views

Hello,

 

I'm trying to use JustMock to mock some classes from the TIA Openness https://support.industry.siemens.com/cs/document/108716692/tia-portal-openness%3A-introduction-and-demo-application?dti=0&lc=en-WW library, but I'm having trouble getting the most basic mocking to happen. The TIA Openness classes are referenced through a Siemens.Engineering.dll (which I don't think I'm allowed to link here, sorry)

 

The Project class is written as following:

namespace Siemens.Engineering {
    [DebuggerNonUserCode]
    public sealed class Project : IEngineeringObject, IEngineeringCompositionOrObject, IEngineeringInstance, ITransactionSupport, IMasterCopyTarget, IInternalObjectAccess, IInternalInstanceAccess, IInternalBaseAccess, IEngineeringServiceProvider, IServiceProvider, IEquatable<object> {
        public HardwareUtilityComposition HwUtilities { get; }
        public FileInfo Path { get; }
        public string Name { get; }
        public string LastModifiedBy { get; }
        public DateTime LastModified { get; }
        public bool IsModified { get; }
        public string Family { get; }
        public DateTime CreationTime { get; }
        public string Copyright { get; }
        public string Author { get; }
        public UsedProductComposition UsedProducts { get; }
        public DeviceSystemGroup UngroupedDevicesGroup { get; }
        public SubnetComposition Subnets { get; }
        public ProjectLibrary ProjectLibrary { get; }
        public IEngineeringObject Parent { get; }
        public LanguageSettings LanguageSettings { get; }
        public string Version { get; }
        public HistoryEntryComposition HistoryEntries { get; }
        public MultiLingualGraphicComposition Graphics { get; }
        public DeviceComposition Devices { get; }
        public DeviceUserGroupComposition DeviceGroups { get; }
        public MultilingualText Comment { get; }
        public long Size { get; }
 
        public void Close();
        public override bool Equals(object obj);
        public void ExportProjectTexts(FileInfo path, CultureInfo sourceLanguage, CultureInfo targetLanguage);
        public IList<object> GetAttributes(IEnumerable<string> names);
        public override int GetHashCode();
        public T GetService<T>() where T : class, IEngineeringService;
        public ProjectTextResult ImportProjectTexts(FileInfo path, bool updateSourceLanguage);
        public void Save();
        public void SetAttributes(IEnumerable<KeyValuePair<string, object>> attributes);
        public void ShowHwEditor(View view);
        public override string ToString();
    }
}

 

And I'm trying to get the mocking started just by mocking the getter on Name as follows:

[TestMethod]
        public void Simplest() {
            var ret = Mock.Create<Project>(Behavior.Strict);
            Mock.Arrange(() => ret.Name).Returns("Mocked project");
            Assert.AreEqual("Mocked project", ret.Name);
        }

 

But everytime the test fails with the same error:

Message: Test method UnitTestProject.SequenceTests.Simplest threw exception:
System.IO.FileNotFoundException: Could not load file or assembly 'Siemens.Engineering.Contract, Version=1500.0.2601.1, Culture=neutral, PublicKeyToken=37a18b206f7724a6' or one of its dependencies. The system cannot find the file specified.

 

The stack trace is just

Project.get_name()

SequenceTests.Simplest()

 

The actual usage of TIA Openness requires, for example, for the user to be in a specific Windows user group etc., but I thought I could just intercept all calls to the actual TIA Openness and mock everything away? I was under the impression (and that is what happens when I test JustMock on a class I wrote) that I could overwrite the whole getter of Name (and in the future other, more relevant properties)? But it doesn't seem that is the case. If someone could point me in the right direction, it would be appreciated.

Ivo
Telerik team
 answered on 13 Nov 2018
1 answer
231 views

Hi,

Our Visual Studio and VSCde extension, VS Live Share, contains a private dotnet core executable, vsls-agent.exe. The extension spawns this process within Visual Studio and VSCode. We got some crash reports for it on Windows. We think the crashes happen due to dotnet core issue https://github.com/dotnet/coreclr/issues/17943 which in turn assumes an external profiler is to blame. I see that Telerik.CodeWeaver.Profiler.dll module is loaded in vsls-agent process in all of the crash dumps, which makes the assumption quite solid.

So the questions to the community and Telerik devs:

1. Why Telerik.CodeWeaver.Profiler.dll can be loaded into our process?

2. How can we prevent this from happening? 

Thanks,
Ilya

Mihail
Telerik team
 answered on 29 Oct 2018
6 answers
973 views
How do I mock out and ref params? Example:

void Parent(int x) {
  var y = f(x, out y);
  ...
}

private int f(int x, out int y) {
...
}

How can I mock the call to f()? Does Arg.OutRefResult<T> help? I´m unfortunately unable to figure out, how it´s supposed to work.
And there seem to be no examples online.

-Ralf

Amit
Top achievements
Rank 1
 answered on 25 Oct 2018
3 answers
204 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
313 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
191 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
499 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
296 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
112 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
388 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
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?