var template = Mock.Create<MessageType>
Mock.Arrange(() => template.Subject).Returns(
"This template has Zero tokens."
);
Mock.Arrange(() => template.Body).Returns(
"This template has {{number}} of {{tokens}}."
);
public
class
MessageType : BaseBusinessEntity
{
public
string
Body {
get
;
set
;}
public
int
DigestsToBeIncludedOn {
get
;
set
; }
public
Guid MessageReference {
get
;
set
; }
public
int
MessageTypeId {
get
;
set
; }
public
string
Name {
get
;
set
; }
public
int
PredefinedRecipients {
get
;
set
; }
public
string
Subject {
get
;
set
; }
}
I put out a question on stackoverflow, but did not get any response. So let me link it here: https://stackoverflow.com/questions/61074264/how-can-i-mock-multiple-instances-of-a-struct
For convenience a copy of the text:
I have a `struct` that I want to mock. In a more complex test I need several instances of this struct, each with it's own behavior. To facilitate this, I've created a helper method.
private MyStruct CreateMock(string toString) {
var mock = Mock.Create<MyStruct>();
Mock.Arrange(() => mock.toString()).Returns(toString);
return mock;
}
When I debug a test where this method is called multiple times, it appears as if the `Arrange` call is overwritten for ALL instances of the struct (or maybe I am using struct mocking instead of instance mocking?).
I've tried:
mock.Arrange(m => m.toString()).Returns(toString); // Using Helpers assembly, note the lowercase m at the start of the line.
But to no avail. How can I get multiple instances of a struct?
I'm using:
Microsoft Visual Studio Enterprise 2017
Version 15.9.17
VisualStudio.15.Release/15.9.17+28307.905
Microsoft .NET Framework
Version 4.8.03761
Installed Version: Enterprise
JustMock 2020.1.219.1
Telerik JustMock Extension.
**Example added**:
```
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Telerik.JustMock;
using Telerik.JustMock.Helpers;
namespace JustMockFramework
{
public struct MyStruct
{
public readonly string Id;
public MyStruct(string id)
{
Id = id;
}
public new string ToString()
{
return "Never read me!";
}
}
[TestClass]
public class MWE
{
[TestMethod]
public void TestSimpleStruct()
{
var simpleTest = new MyStruct("1");
Assert.AreEqual("Never read me!", simpleTest.ToString());
}
[TestMethod]
public void TestMockOfStruct()
{
var mock = Mock.Create<MyStruct>();
Mock.Arrange(() => mock.ToString()).Returns("Read me!");
Assert.AreEqual("Read me!", mock.ToString());
}
[TestMethod]
public void TestTwoMocksOfStruct()
{
var firstMock = Mock.Create<MyStruct>();
Mock.Arrange(() => firstMock.ToString()).Returns("Read me!");
var secondMock = Mock.Create<MyStruct>();
Mock.Arrange(() => secondMock.ToString()).Returns("Read me too!");
Assert.AreEqual("Read me!", firstMock.ToString()); // Fails with "Read me too!"
Assert.AreEqual("Read me too!", secondMock.ToString());
}
[TestMethod]
public void TestTwoMocksOfStructCreatedInHelper()
{
var firstMock = CreateMockOfStruct("Read me!");
var secondMock = CreateMockOfStruct("Read me too!");
Assert.AreEqual("Read me!", firstMock.ToString()); // Fails with "Read me too!"
Assert.AreEqual("Read me too!", secondMock.ToString());
}
private MyStruct CreateMockOfStruct(string toString)
{
var mock = Mock.Create<MyStruct>();
Mock.Arrange(() => mock.ToString()).Returns(toString);
return mock;
}
[TestMethod]
public void TestTwoMocksOfStructCreatedInHelperWithHelper()
{
var firstMock = CreateMockOfStructWithHelper("Read me!");
var secondMock = CreateMockOfStructWithHelper("Read me too!");
Assert.AreEqual("Read me!", firstMock.ToString()); // Fails with "Read me too!"
Assert.AreEqual("Read me too!", secondMock.ToString());
}
private MyStruct CreateMockOfStructWithHelper(string toString)
{
var mock = Mock.Create<MyStruct>();
mock.Arrange((m) => m.ToString()).Returns(toString);
return mock;
}
}
}
```
hi mate, I was wondering if it is possible to mock the following case.
from school in dbContext.Schools
join student in dbContext.Students
on school.id equals student.schoolId into students
let firstStudent = students.FirstOrDefault()
select firstStudent.Name;
When all the tables are empty and there is no school and no student in the tables, a real sql execution just returns an empty object of IEnuemrable<string> type. If I mock 'dbContext.Schools' and 'dbContext.Students', 'firstStudent.Name' throws a null exception because 'firstStudent' is null.
Is there a way to conditionally mock only in this context of linq to sql so that we can bypass the null exception and get the mocked execution to run smoothly?
Hi ,
I am actually intended to write a UT for the following code.
Private void GetVersion(){
string version=GetLatest();
if(string.IsNullOrEmpty(version))
Throw new InvalidException("Ivalid version");
How to write a unit test for the above code?
Hello,
We're encountering the following type of error on our build servers:
X SendFile_GivenValidInformation_ShouldReturnSuccessResult [1ms]
Error Message:
Initialization method InsuranceApiLibrary.Syncronizers.<<redacted>>Tests.Setup threw exception. Telerik.JustMock.Core.ElevatedMockingException: Cannot mock '<<redacted>>SoapClient'. The profiler must be enabled to mock, arrange or execute the specified target.
Detected active third-party profilers:
* C:\Users\<<redacted-tfs-agent-service>>\.nuget\packages\microsoft.codecoverage\16.4.0\build\netstandard1.0\CodeCoverage\amd64\covrun64.dll (from process environment)
Disable the profilers or link them from the JustMock configuration utility. Restart the test runner and, if necessary, Visual Studio after linking..
Stack Trace:
at Telerik.JustMock.Core.ProfilerInterceptor.ThrowElevatedMockingException(MemberInfo member)
at Telerik.JustMock.Core.MocksRepository.Create(Type type, MockCreationSettings settings)
at Telerik.JustMock.Mock.<>c__DisplayClass47_0`1.<Create>b__0()
at Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal[T](Func`1 guardedAction)
at Telerik.JustMock.Mock.Create[T](Object[] args)
at InsuranceApiLibrary.Syncronizers.<<redacted>>Tests.Setup() in E:\AzDOS\Agents\Alpha\_work\8\s\<<redacted>>\<<redacted>>Test\Syncronizers\<<redacted>>Tests.cs:line 27
When we exclude code coverage, we get very similar errors, but without the lines about detected third-party active profilers. I have directly verified that the JM profiler settings are correct (see attached images).
Our build servers have Visual Studio Enterprise 2019 16.4.2, .NET Core SDK 3.1.100, and JustMock 2020.1.113.1 installed. The C# projects in question target .NET Core 3.1. The path to the JM DLL being referenced by those projects is "C:\Program Files (x86)\Progress\Telerik JustMock\Libraries\netcoreapp2.0\Telerik.JustMock.dll". I can find no obvious alternative path or DLL for .NET Core 3.x, so I assume that DLL applies to multiple .NET Core major versions.
This problem is blocking new initiatives. Thanks in advance for any assistance you can provide.
Regards,
Tom Slavens
Platform Configuration Architect, Software Services
Veterans United Home Loans
Hi ,
I want to write a unit test for a small class where it has following execution paths
private bool? DetermineCheckState()
{
try
{
//1.where ProjectsOperationData is a ObservableCollection<ProjectOperationData>{get;set;}
//2 IsSelected is a public property in ProjectOperationData Class
bool allChildrenChecked = ProjectsOperationData.Count(x => x.IsSelected == true) == ProjectsOperationData.Count;
if (allChildrenChecked)
{
return true;
}
//2. returns false if any project is not selected in Project Operations Form
bool allChildrenUnChecked = ProjectsOperationData.Count(x => x.IsSelected == false) == ProjectsOperationData.Count;
if (allChildrenUnChecked)
{
return false;
}
}
}
return null;
}
Can anyone suggest a way to write unit test?
I am trying to create a new .NET Core project and I am having issues using any JustMock functions/keywords. I have installed the latest available installer (JustMock.2019.1.207.1), we use JustMock in our other projects without any issues but these are all .NET 4.5. I would prefer to use the MSTest project as that is what the other projects use also and would like to keep things consistent. I have also tried creating a new NUnit and XUnit project but keep getting the same error. Solution builds without errors or warnings.
My Test Method only has one line in it for arranging, it's trying to mock the service. Here is the code:
var context = Mock.Create<IFileService>();
Here is the error I am getting:
Test method MSTestProject.LayoutControllerTest.FileController_TestCalls threw exception:
System.TypeInitializationException: The type initializer for 'Telerik.JustMock.Core.ProfilerInterceptor' threw an exception. ---> System.MissingMethodException: Method not found: 'System.Reflection.Emit.AssemblyBuilder System.AppDomain.DefineDynamicAssembly(System.Reflection.AssemblyName, System.Reflection.Emit.AssemblyBuilderAccess)'.
StackTrace:
at Telerik.JustMock.Core.Castle.DynamicProxy.ModuleScope.CreateModule(Boolean signStrongName)
at Telerik.JustMock.Core.Castle.DynamicProxy.ModuleScope.ObtainDynamicModuleWithStrongName()
at Telerik.JustMock.Core.MockingUtil.get_ModuleBuilder()
at Telerik.JustMock.Core.MockingUtil.CreateDynamicMethodWithVisibilityChecks(Type returnType, Type[] parameterTypes, Action`1 ilGen)
at Telerik.JustMock.Core.ProfilerInterceptor.CreateFieldAssignmentExpression(FieldInfo assignee, ParameterExpression valueParam)
at Telerik.JustMock.Core.ProfilerInterceptor.InitializeFieldAccessors[TFieldType](String fieldName, Func`1& getter, Action`1& setter)
at Telerik.JustMock.Core.ProfilerInterceptor..cctor()
--- End of inner exception stack trace ---
at Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal(Action guardedAction)
at MSTestProject.LayoutControllerTest.FileController_TestCalls() in C:\Repos\LTA-TelerikUIDotNetCore\MSTestProject\LayoutControllerTest.cs:line 33
I have a complex legacy application that I'm not allowed to refactor. I am trying to write tests and don't want to repeat the same set up multiple times. I created a helper class which holds the mocks (TargetMocks) with methods to set up most of the logging arrange statements so I could focus the test on a specific aspect of the system under test.
I've created an example NUnit test with a sample set of classes and Interfaces. All but one of the tests work and I don't understand why the failing test fails. It has the same exact Mock.Arrange statements that are executed in the same order. The only difference is the failing test has the Mock.Arrange statements in the test method while the working test has the Mock.Arrange methods in the TestMocks helper class.
public class TargetMocks
{
public ILogger Logger { get; } = Mock.Create<
ILogger
>();
public IUtility Util { get; } = Mock.Create<
IUtility
>();
public StringBuilder LoggerBuilder {get;} = new StringBuilder();
public void SetupMocks()
{
Mock.Arrange(() => Logger.Info(Arg.AnyString))
.DoInstead((string msg) =>
{
LoggerBuilder.AppendLine(msg);
});
}
public Target CreateTarget()
{
var sut = new Target();
Mock.Arrange(() => sut.Logger).Returns(Logger);
Mock.Arrange(() => sut.Util).Returns(Util);
return sut;
}
public Target CreateTargetAndSetupUtil()
{
var sut = new Target();
Mock.Arrange(() => sut.Logger).Returns(Logger);
Mock.Arrange(() => sut.Util).Returns(Util);
//Mock.Arrange(() => mock.Util.ChangeState(Arg.AnyInt, Arg.AnyString)).MustBeCalled();
Mock.Arrange(() => Util.SaveState(Arg.AnyInt, Arg.AnyString)).MustBeCalled();
return sut;
}
}
The following test fails
[Test()]
public void x3TestWidgetProcessUtilMethods_Test_TestUsesSeperateClassMocksAndCreatesSUT_But_Fails()
{
var expectedLog =
"target message 1\r\n" +
"Message 1\r\n" +
"Message 3\r\n" +
"target message 3\r\n";
var mock = new TargetMocks();
mock.SetupMocks();
var sut = mock.CreateTarget();
Mock.Arrange(() => mock.Util.ChangeState(Arg.AnyInt, Arg.AnyString)).MustBeCalled();
Mock.Arrange(() => mock.Util.SaveState(Arg.AnyInt, Arg.AnyString)).MustBeCalled();
sut.Process();
var log = mock.LoggerBuilder.ToString();
Assert.AreEqual(expectedLog, log, log);
Mock.Assert(mock.Util);
}
But this test works.
[Test()]
public void x3aTestWidgetProcessUtilMethods_Test_TestUsesSeperateClassMocksAndCreatesSUTAndSetsUpUtilMock_WorksAsExpected()
{
var expectedLog =
"target message 1\r\n" +
"Message 1\r\n" +
"Message 3\r\n" +
"target message 3\r\n";
var mock = new TargetMocks();
mock.SetupMocks();
var sut = mock.CreateTargetAndSetupUtil();
sut.Process();
var log = mock.LoggerBuilder.ToString();
Assert.AreEqual(expectedLog, log, log);
Mock.Assert(mock.Util);
}