Hi,
I have 2 interfaces (I1 and I2) that have a property called FileName. Another interface is inheriting these two interfaces. Let us call it I3.In I3, I am using new modifier (this is C#) so that in my code I do not get FileName property displayed twice and prevent compiler ambiguity errors.
When I mock interface I3 and set the FileName value, this value does not propagate to interfaces I1 and I2. This is not an issue in my actual code.
I have attached a sample pictures of the code. The first assert works. Second and third fail.
Assert.IsTrue(toTest.FileName == @"test file name", "FileName missing"); //1
Assert.IsTrue((toTest as Interface1).FileName== @"test file name","FileName missing"); //2
Assert.IsTrue((toTest as Interface2).FileName == @"test file name", "FileName missing"); //3
Am I doing something wrong OR is this a bug with the lite version of JustMock?
Thank you for time taken to read and any direction to resolve my challenge.
Sainath
Hi there
Is there any early access program or something similar for JustMock? Due to some license problems I had to move to Visual Studio 2017 RC and now I desperately need the JustMock Profiler...
Any chance?
Thank you for your help
Mike
[ClassInitialize()]
public
static
void
MyClassInitialize(TestContext testContext)
{
Mock.Partial<EagleUtility>().For(() => EagleUtility.ValidateMessage(Arg.IsAny<byte[]>(), Arg.AnyInt, TowerTypes.Unified)); Mock.Partial<UnifiedProtocolTranslator>();
}
public
void
RecieveIncomingMessageTest()
{
var expectedTower = TestContext.DataRow[
"Tower"
].ToString();
var expectedEventDescription = TestContext.DataRow[
"EventDescription"
].ToString().TrimStart(
'\r'
,
'\n'
,
' '
);
expectedEventDescription = expectedEventDescription.TrimEnd(
' '
,
'\n'
,
'\r'
,
'\0'
);
var rawDataToUse = Convert.FromBase64String(TestContext.DataRow[
"RawData"
].ToString());
var called =
false
;
var target =
new
UnifiedProtocolTranslator();
;
int
byteCount = rawDataToUse.Length;
EagleIncomingMessageStatus expected = EagleIncomingMessageStatus.Complete;
EagleIncomingMessageStatus actual;
Mock.NonPublic.Arrange<bool>(target, "ProcessIncomingMessage", rawDataToUse, 0).IgnoreArguments().DoInstead((byte[] arg1,int arg2) => called =true).Returns(true).MustBeCalled();
Mock.NonPublic.Arrange(target,
"CompileIncomingMessage"
).DoNothing().MustBeCalled();
actual = target.RecieveIncomingMessage(rawDataToUse, byteCount);
Mock.Assert(target);
Assert.AreEqual(expected, actual);
}
public
EagleIncomingMessageStatus RecieveIncomingMessage(
byte
[] message,
int
byteCount)
{
var messageType = (UnifiedIncomingMessageTypes) message[0];
EagleIncomingMessageStatus returnValue = EagleIncomingMessageStatus.Continue;
if
(EagleUtility.ValidateMessage(message, byteCount, TowerTypes.Unified))
{
if
(ProcessIncomingMessage(message, byteCount))
{
CompileIncomingMessage();
returnValue = EagleIncomingMessageStatus.Complete;
}
}
return
returnValue;
}
Just started getting this on multiple machines trying to execute tests via the Resharper Test Runner while collecting coverage via dotcover. Profiling is enabled and dotcover is selected as an additional profiler. This configuration has been working for a while, its a very large solution with 100's of devs so its very possible a version changed etc. Just looking for some direction on where to start looking.
At the same time of the errors I see the following two entries in the System Event Log.
.NET Runtime version 4.0.30319.0 - The profiler was loaded successfully. Profiler CLSID: '{b7abe522-a68f-44f2-925b-81e7488e9ec0}'. Process ID (decimal): 180616. Message ID: [0x2507].
.NET Runtime version 2.0.50727.5485 - Failed to CoCreate profiler.
System.Runtime.Serialization.SerializationException
Type 'Telerik.JustMock.Core.Behaviors.EventStubsBehavior+EventsMixin' in Assembly 'Telerik.JustMock, Version=2016.1.307.3, Culture=neutral, PublicKeyToken=721b6c5bc0326b3a' is not marked as serializable.
Server stack trace:
at System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type)
at System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context)
at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo()
at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder)
at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter, SerializationBinder binder)
at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Write(WriteObjectInfo objectInfo, NameInfo memberNameInfo, NameInfo typeNameInfo)
at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck)
at System.Runtime.Remoting.Channels.CrossAppDomainSerializer.SerializeMessageParts(ArrayList argsToSerialize)
at System.Runtime.Remoting.Messaging.SmuggledMethodCallMessage..ctor(IMethodCallMessage mcm)
at System.Runtime.Remoting.Messaging.SmuggledMethodCallMessage.SmuggleIfPossible(IMessage msg)
at System.Runtime.Remoting.Channels.CrossAppDomainSink.SyncProcessMessage(IMessage reqMsg)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Xunit.Abstractions.IMessageSink.OnMessage(IMessageSinkMessage message)
at Xunit.Sdk.SynchronousMessageBus.QueueMessage(IMessageSinkMessage message) in C:\BuildAgent\work\cb37e9acf085d108\src\xunit.execution\Sdk\SynchronousMessageBus.cs:line 24
at ReflectionAbstractionExtensions.CreateTestClass(ITest test, Type testClassType, Object[] constructorArguments, IMessageBus messageBus, ExecutionTimer timer, CancellationTokenSource cancellationTokenSource) in C:\BuildAgent\work\cb37e9acf085d108\src\xunit.execution\Extensions\ReflectionAbstractionExtensions.cs:line 45
at Xunit.Sdk.TestInvoker`1.CreateTestClass() in C:\BuildAgent\work\cb37e9acf085d108\src\xunit.execution\Sdk\Frameworks\Runners\TestInvoker.cs:line 121
at Xunit.Sdk.TestInvoker`1.<<RunAsync>b__45_0>d.MoveNext() in C:\BuildAgent\work\cb37e9acf085d108\src\xunit.execution\Sdk\Frameworks\Runners\TestInvoker.cs:line 160
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Xunit.Sdk.ExceptionAggregator.<RunAsync>d__10`1.MoveNext() in C:\BuildAgent\work\cb37e9acf085d108\src\xunit.core\Sdk\ExceptionAggregator.cs:line 107
I have not used JustMock in the past year or so but I used to use it to do future mocking of objects that are created in the code. But now I cannot find any examples of this in my own code or online, so I am not sure how to do this. But I have done it before so I know it is possible. So I'm hoping someone can point me in the right direction here.
The code below shows what I am doing. I setup a mock of my class that I am testing, but as a PrivateAccessor so I can use that as needed. So I grab the instance as my sut. There there, when I run into code that creates another object and does not pass that object in using DI, I thought that you were able to mock that with a .Returns() so that it returns a fake version of whatever object you typically return. However, I cannot get the context to work with the arrange object and I cannot figure out what I need to do. I did try adding the arrange to the sut, but I could not figure out the syntax.
The first two lines... the mock and sut work fine. Then the next two lines also work fine, the Mock.Arrage and my test below it to get LoanData. But now when my sut runs and does things and encounters code such as var something = new LoanData() it is not using the arrange, but the actual code.
So what am I missing? How can I get that Mock.Arrange to apply to the code from within the Sut? I can do Sut.Array() but I cannot figure out the syntax.
Any suggtions are appreciated. I'm sure it is just a syntax issue and I don't see how to set it up.
public
PricingBase()
{
var mock =
new
PrivateAccessor(
new
Classes.PricingEngine.Refactor.PricingEngine(
new
PricingEngineService()));
Sut = (Classes.PricingEngine.Refactor.PricingEngine)mock.Instance;
Mock.Arrange(() =>
new
LoanData()).IgnoreArguments().Returns(CreateFakeLoanData());
var test =
new
LoanData();
}
Hello,
I see from answers to two old posts to this forum (URLs below) that a license for each build server or agent was not necessary as recently as March 2012, but that was quite some time ago. Could someone from Telerik confirm that the same licensing policy remains in effect? And if not, whether I need to acquire licenses per server or per build agent (we have some build servers running multiple agents), and whether the licensing mechanism plays well with VMs (all of our build servers are VMs). Thanks in advance.
http://www.telerik.com/forums/do-you-need-to-install-on-the-build-server
http://www.telerik.com/forums/justmock-licensing-tfs-2010
Also, perhaps it would be worthwhile to have licensing questions like this in some FAQs area of the main site.
Tom Slavens,
Configuration Architect, Platform Architecture, Software Services
Veterans United Home Loans
I'm having an issue with running xUnit with JustMock and dotCover on TeamCity.
I've setup my environment parameter JUSTMOCK_INSTANCE=1 on the build configuration and linked the dotCover profiler on the "Telerik JustMock Configuration" interface.
I'm using the "xUnit.net + dotCover 💕" metarunner and it is executing the tests. But after it has executed the tests (no errors), dotCover does not finish generating the coverage data file. The process just "hangs", so to speak, after the last test.
When I unlink the dotCover profiler on the "Telerik JustMock Configuration" interface, and use JustMockRunner.exe, the process does finish, but no coverage data is generated.
TeamCity Command Line script (in stead of meta runner):
When running xUnit directly is does not execute most of the unit tests, because JustMock is not in elevated mode of course, but it does finish the process generate the coverage data. Indicating for me, that dotCover is working fine.
TeamCity command line script (in stead of meta runner):
%teamcity.tool.dotCover%\dotcover cover /TargetExecutable="%system.teamcity.build.workingDir%\packages\xunit.runner.console.2.2.0\tools\xunit.console.exe" /TargetArguments="mytestassembly.dll" /ReturnTargetExitCode
It makes sense that the dotCover profiler should run together with JustMock so the data can be generated, but every time I link the profiler, the process hangs after all tests have been executed.
Different test assemblies show the same result.
Versions:
JustMock: 2016.3.914.2
Team City 10.0.2 (build 42234)
xUnit: 2.2.0
dotCover: 2016.2.2
Is this a known issue? Please let me know if you need more information.
Thanks.
I have to implement a unit test method that needs to mock datacontextcontainer. Below is the code i have to mock
using (var dcc = new DataEntities.DataContextContainer())
{
}
How can i mock DataEntities.DataContextContainer(). When ever i use to call this statement i m getting new instance. Can some please help me on this.
Hello,
I'm new to JustMock and have been playing with it only for a few hours. I have been able to convert a few of my existing tests from Microsoft Fakes to JustMock. However, there's one test, where I'm having a lot of trouble and I'm hoping someone can help me with it.
I have a class that derives from the System.Web.Http.ApiController and here is a snapshot of it:
public class MyApiController : ApiController {
public HttpResponseMessage Post(EPAQuestionsetLookupRequest lookup) {
try {
if (!ModelState.IsValid) {
return new HttpResponseMessage(HttpStatusCode.NotAcceptable);
}
return new HttpResponseMessage(HttpStatusCode.OK);
} catch {
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
}
}
I have a test written as the follows:
[TestMethod]
public void PostNotValidState() {
var controller = Mock.Create<
MyApiController
>();
Mock.Arrange(() => controller.ModelState.IsValid).Returns(false).MustBeCalled();
// Mock.Arrange(() => ((ApiController)controller).ModelState.IsValid).Returns(false).MustBeCalled();
var response = controller.Post(lookup);
Assert.AreEqual(HttpStatusCode.NotAcceptable, response.StatusCode);
Mock.Assert(controller);
}
I've tried it in the above way and also using a Container instead. But, in both cases, it seems like the ModelState.IsValid is continuing to return true (or the method during the test, is actually not using the arrangement I have, which is confirmed by the fact that the Mock.Assert is failing on the MustBeCalled) and is failing my test. What's the best way for me to be able to mock the ModelState.IsValid to return false and for it to be honored?
There is a private variable that in a static class:
public static class Common {
private static EMailSetting _mailSetting;
......
public void BeTest()
{
if(_mailSetting=null){
//do something
}
........
}
}
How can I mock "_mailSetting"?
I try this code, It's not work:
Mock.SetupStatic(typeof(Common), Behavior.CallOriginal, StaticConstructor.Mocked);
Mock.NonPublic.Arrange<EMailSetting>(typeof(Common), "_mailSetting")
.Returns(() => {
var mockMailSetting = Mock.Create<EMailSetting>();
mockMailSetting.mailFrom = "C";
mockMailSetting.mailTo = "D";
return mockMailSetting;
});
Common.BeTest();