There is one interface where when I try to mock it it throws an exceptions
System.IO.FileLoadException : Could not load file or assembly 'MyFramework, Version=2017.12.12.1, Culture=neutral, PublicKeyToken=null' or one of its dependencies. A strongly-named assembly is required.
None of our projects are strong named, and my best guess is that it has something to do with the nature of the interface we're trying to mock. For simplicity sake I'll describe our project like this:
One of the methods in the IMessageLogger interface has an argument where the type is defined in the MyFramework project.
When I call Mock.Create<IMessageLogger>() I get the error above. My only thought is that because the Telerik.JustMock assembly is strong named, it is for some reason having trouble loading the MyFramework assemble even though it can miraculously load the MyFramework.Lib assembly.
I was wondering if there is any workaround I might be able to try so that I can mock this piece. I can live without mocking this specific interface, but I may not be so lucky with others...
Hello,
I'm trying to write a powershell script to run my tests, create code coverage using OpenCover and then generate a report using ReportGenerator. However I'm running into the Profiler error:
The profiler must be enabled to mock, arrange or execute the specified target.
Detected active third-party profilers:
* (from process environment)
This only happens when run from the powershell, if I run it from command line the tests run fine. The command I am using is:
packages\OpenCover.4.6.519\tools\OpenCover.Console.exe -mergebyhash -target:"%VS140COMNTOOLS%\..\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe" -targetargs:"JustMockUnitTests\bin\x64\Debug\JustMockUnitTests.dll /InIsolation /platform:x64 /logger:trx /Parallel" -output:"OpenCover.xml"
Any thoughts would be much appreciated.
Thanks
-Steve
Is there any way to enable profiler in JetBrains Rider?
I have a scenario that I cannot seem to get working just like i would like.
I have been able to successfully write a test method against my private method just fine.
Now, I'm trying to write a test against my public method. In the public method, i want to the call to the private method to be mocked and return a mocked value so the remainder code in my public method will handle that result.
However, when it comes time to execute the line of code in the public method that would call the private method, all that comes back is NULL. I don't get my mocked value.
Here is my current test
var mockedClass = Mock.Create<JHADirectoryServiceAPI>(Constructor.Mocked);
var autoFix =
new
Fixture();
var otherPhoneDtoCollection_AM = autoFix.Create<IEnumerable<OtherPhoneDto>>();
var inst =
new
PrivateAccessor(mockedClass);
Mock.NonPublic.Arrange<IEnumerable<OtherPhoneDto>>(mockedClass,
"GetOtherPhonesByOfficeID"
, Arg.AnyGuid)
.DoInstead(()=> inst.CallMethod(
"GetOtherPhonesByOfficeID"
, Arg.AnyGuid)).ReturnsCollection(otherPhoneDtoCollection_AM);
Assume the below code...
Public
IEnumerable<Object>
GetDetails(Guid value)
{
//do some local stuff
var result = GetOtherPhonesByOfficeID(value);
//eval result
return
myList
}
private
IEnumerable<OtherPhoneDto>
GetOtherPhonesByOfficeID(Guid value)
{
//Do some Stuff
return
myList
;
}
public class MyClass
{
public void MyMethod<
T
>()
{
//
}
}
var service = Mock.Create<
MyClass
>();
Mock.Arrange(() => service.MyMethod<
T
>()).OccursNever();
So I have a method that I'm trying to test that looks something like the following:
public void MethodToTest(List<Object> importEntities, short id)
{
var relevantObjects = importEntities.Select(some code).Distinct();
var list1= new Dictionary<string, NewTenantRange>();
var list2= new Dictionary<string, NewTenantRange>();
var list3= new Dictionary<string, NewTenantRange>();
foreach (var obj in relevantObjects)
{
if (!list1.ContainsKey(obj.key))
{
var item1 = NewTenantRange.GetBwTenantRange(obj);
list1.Add(item1.Number, item1);
}
if (!list2.ContainsKey(obj.key))
{
var item2 = NewTenantRange.GetBbTenantRange(obj);
list2.Add(item2.Number, item2);
}
if (!list3.ContainsKey(obj.key))
{
var item3 = NewTenantRange.GetVsTenantRange(obj);
list3.Add(item3.Number, item3);
}
}
InsertRange(list1.Values, tenantId, Ranges.Range1);
InsertRange(list2.Values, tenantId, Ranges.Range2);
InsertRange(list3.Values, tenantId, Ranges.Range3);
}
And my test so far:
[TestMethod]
public void TestMethodToTest()
{
//Arrange
var service = Mock.Create<myService>(Constructor.Mocked, Behavior.CallOriginal);
var entities = FakeLf10Orders().ToList(); //returns list of fake objects
Mock.NonPublic.Arrange(service, "InsertRange",
ArgExpr.IsAny<IEnumerable<TenantRangeService.NewTenantRange>>(), Arg.AnyShort, Arg.IsAny<Ranges>())
.DoNothing().Occurs(3);
//Act
service.MethodToTest(entities, Arg.AnyShort);
//Assert
Mock.AssertAll(service);
}
Now, everuthing is working fine until the method InsertRange is called for the second time. Then instead of DoNothing(), the code is executed and therefore fails. Anyone with any ideas?
Thank you!
//Petter
I have a class which has a large number of properties each of which returns a double, and a method under test which takes a string, and an instance of the class, and calls one of these properties based on the value of the string (effectively, it calls the property whose name is the string). I am using NUnit, which provides for parameterised testing. I would like to test the method with a set strings, but this means arranging for the specific property call. I am quite close, but I can't quite get it to work.
So far I have the following. A set of test parameters, defined as a Dictionary:
public static Dictionary<string, System.Linq.Expressions.Expression<Func<IMyClass, double>>> SpecialProperties = new Dictionary<string, System.Linq.Expressions.Expression<Func<IMyClass, double>>>()
{
{"InlineLength", x=>x.InLineLength},
{"BranchLength", x=>x.BranchLength},
{"TotalLength", x=>x.TotalLength},
{"CentreLineLength", x=>x.CentreLineLength},
{"SurfaceArea", x=>x.SurfaceArea},
}
Then I have the test method:
[Test]
[TestCaseSource("SpecialProperties")]
public void SpecialProperties_Test(string specialPropertyName, System.Linq.Expressions.Expression<Func<IMyClass, double>> specialProperty)
{
IMyClass mockMyClass = Mock.Create<IMyClass>(Behavior.Strict);
mockMyClass.Arrange(specialProperty).Returns(9.99);
double result = _concreteInstanceOnTest.MethodOnTest(specialPropertyName, mockMyClass);
Assert.AreEqual(9.99, result);
}
This very nearly works, but I get an Inconsistent Accessibility error - Expression<Func<IMyclass, double>> is less accessible than SpecialProperties_Test(). I'm obviously not doing it quite right. Can anybody help?
I'm not sure if this is a JustMock question, but it may be. I'm trying to test a Kendo datasource 'read' method which is implemented in my MVC controller. The datasource is actually part of a grid definition, but I have others that are in auto-complete controls.
The following is a fragment of my grid definition in the view.
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(10)
.Events(events => events.Error("error_handler").RequestEnd("onGridRequestEnd"))
.Model(model =>
{
model.Id(p => p.Id);
model.Field(p => p.Id).Editable(false);
model.Field(p => p.PostedStr).Editable(false);
model.Field(p => p.UpdatedStr).Editable(false);
})
.Read(read => read.Action("_GetBulletins", "Bulletins").Type(HttpVerbs.Get))
.Create(create => create.Action("_CreateBulletin", "Bulletins").Type(HttpVerbs.Post).Data("sendAntiForgery"))
.Update(update => update.Action("_UpdateBulletin", "Bulletins").Type(HttpVerbs.Post).Data("sendAntiForgery"))
.Destroy(update => update.Action("_DeleteBulletin", "Bulletins").Type(HttpVerbs.Post).Data("sendAntiForgery"))
)
My controller methods is:
[AcceptVerbs(HttpVerbs.Get)]
[AjaxOnly]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult _GetBulletins(DataSourceRequest request)
{
var model = (BulletinsViewModel)ViewModels.GetModel(HttpContext, Constants.Session.Model.BulletinsViewModelId);
var enumerableModel = model.Bulletins.AsEnumerable();
return Json(enumerableModel.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
and a fragment of my test is:
var request = new DataSourceRequest()
{
Aggregates = new List<
AggregateDescriptor
>(),
Filters = new List<
IFilterDescriptor
>(),
Groups = new List<
GroupDescriptor
>(),
Sorts = new List<
SortDescriptor
>(),
Page = 1,
PageSize = 10
};
// Act
var result = controller._GetBulletins(request) as JsonResult;
var model = result.Data as BulletinsViewModel;
When I run my test, the controller throws and exception:
System.ArgumentNullException: 'Value cannot be null.' Message:"Value cannot be null.\r\nParameter name: source"
Obviously I'm not setting up the 'request' properly, althought I don't exactly know what's wrong.
Rather than spin my wheels trying to figure that out, I wonder if you can advise me on the recomended approach to testing datasources.
TIA
Dave