Assert a method was called whilst verifying the parameters are correct - unit-testing

Given the following snippet from my test:
var mockProvider = MockRepository.GenerateMock<IItemProvider>();
var target = new ItemService(mockProvider);
target.SaveItem(item);
Internally target.SaveItem makes a call like this:
provider.SaveItem(new SaveContract(item.Id, user, contents)); where provider is the local name for the mockProvider passed in.
How do I:
Verify provider.SaveItem is called whilst also
Asserting that the values of item.Id, user and contents are as they should be.
I think I might be able to use mockProvider.AssertWasCalled but can't figure out the syntax to set the condition of the parameters passed to the constructor of SaveContract.
TIA

Ok so based on this I did something like the following:
var mockProvider = MockRepository.GenerateMock<IItemProvider>();
var target = new ItemService(mockProvider);
Item testItem = null;
mockProvider.Expect(c => c.SaveItem(Arg<Item>.Is.Anything))
.WhenCalled(call =>
{
testItem = (Item)call.Arguments[0];
});
target.SaveItem(item);//item initialised elsewhere
Assert.AreEqual(item.Id, testItem.Id);

Related

Get object with the GloabId

Is it possible to find an object in an IFC file using Xbim.Essentials with the GlobalId value?
I saw this kind of code supposing I know the type...But I'd like to first find the object without knowing the type.
var id = "2AswZfru1AdAiKfEdrNPnu";
var theDoor = model.Instances.FirstOrDefault<IIfcDoor>(d => d.GlobalId == id);
Console.WriteLine($"Door ID: {theDoor.GlobalId}, Name: {theDoor.Name}");
I think you can use IIfcProduct interface from
Xbim.Ifc4.Interfaces
like:
var ifcProduct = model.Instances.FirstOrDefault<IIfcProduct>(d => d.GlobalId == id);
should work on walls, slabs, columns etc...

Scala.js js.Dynamic usage leads to a recursively infinite data structure

I'm trying to use Google Visualizations from Scala.js. I generated the type definitions using TS importer and the relevant portion it generated is:
#js.native
trait ColumnChartOptions extends js.Object {
var aggregationTarget: String = js.native
var animation: TransitionAnimation = js.native
var annotations: ChartAnnotations = js.native
// ... more
}
#js.native
trait TransitionAnimation extends js.Object {
var duration: Double = js.native
var easing: String = js.native
var startup: Boolean = js.native
}
Now, I'm trying to figure out how to actually use this and came up with:
val options = js.Dynamic.literal.asInstanceOf[ColumnChartOptions]
options.animation = js.Dynamic.literal.asInstanceOf[TransitionAnimation] // comment this and the next line and chart will appear
options.animation.duration = 2000
options.title = "Test Chart"
options.width = 400
options.height = 300
This works if I don't set the animation settings, but fails with the chart showing "Maximum call stack size exceeded" if I do.
I debugged, and found the following:
So animation contains a reference to itself, but I don't feel like this should happen based on the code above.
Ideas how to fix it?
Any other suggestions on how to best use the generated types to provide a type-safe way of creating the JavaScript objects which Google Visualizations expects? I tried new ColumnChartOptions {} which looks cleaner than js.Dynamic but that failed with "A Scala.js-defined JS class cannot directly extend a native JS trait."
P.S. I'd like to note that
options.animation = js.Dynamic.literal(
easing = "inAndOut",
startup = true,
duration = 2000
).asInstanceOf[TransitionAnimation]
actually works, but isn't type-safe (a mis-spelling of duration to durration won't be caught).
Your code lacks () when calling literal(), so the fix would be:
val options = js.Dynamic.literal().asInstanceOf[ColumnChartOptions]
options.animation = js.Dynamic.literal().asInstanceOf[TransitionAnimation] // comment this and the next line and chart will appear
In Scala (and therefore in Scala.js), the presence or absence of () is sometimes meaningful. literal is the singleton object literal, whereas literal() calls the method apply() of said object.

What are alternatives for Sinon.js (JS mocking library)?

Are there any worthwhile alternatives for Sinon.js?
Thanks.
Testdouble.js
There is also library called testdouble.js. Which is a kind of more object-oriented than sinon.js.
Also, this article from testdouble guys explain the differences between sinon.js and testdouble.js.
Example
var td = require('testdouble');
var fetch = td.function();
td.when(fetch(42)).thenReturn('Jane User');
fetch(42); // -> 'Jane User'
Not quite as advanced, but you can look at Jack.
I just started a new project called candy-wrapper that may be an alternative to Sinon in some instances:
https://www.npmjs.com/package/candy-wrapper
Here are some examples of how to use it, I would love feedback if anyone has any insights as to how to make it better:
var Wrapper = require("candy-wrapper");
// a simple test object
var myDrone = {
name: "DJI",
fly: function(direction) {
return true;
}
}
new Wrapper(myDrone, "name");
new Wrapper(myDrone, "fly");
myDrone.fly("north");
myDrone.fly("west");
// evaluating previous calls through the 'historyList' and 'Filters'
myDrone.fly.historyList.filterFirst().expectCallArgs("north"); // true
myDrone.fly.historyList.filterSecond().expectCallArgs("east"); // false
myDrone.fly.expectReportAllFailtures(); // throws an error about the "east" expecation failing
// modifying behavior using 'Triggers'
myDrone.fly.triggerOnCallArgs("east").actionReturn(false); // will return 'false' when called with "east"
myDrone.fly("east"); // false
myDrone.fly("west"); // true (the default return value)
// working with properties
myDrone.name.triggerOnSet().actionThrowException(new Error("do not set the name"));
myDrone.name = "Bob"; // throws Error: "do not set the name"
var ret = myDrone.name; // ret = "DJI"

Returning a complex data type from arguments with Rhino Mocks

I'm trying to set up a stub with Rhino Mocks which returns a value based on what the parameter of the argument that is passed in.
Example:
//Arrange
var car = new Car();
var provider= MockRepository.GenerateStub<IDataProvider>();
provider.Stub(
x => x.GetWheelsWithSize(Arg<int>.Is.Anything))
.Return(new List<IWheel> {
new Wheel { Size = ?, Make = Make.Michelin },
new Wheel { Size = ?, Make = Make.Firestone }
});
car.Provider = provider;
//Act
car.ReplaceTires();
//Assert that the right tire size was used when replacing the tires
The problem is that I want Size to be whatever was passed into the method, because I'm actually asserting later that the wheels are the right size. This is not to prove that the data provider works obviously since I stubbed it, but rather to prove that the correct size was passed in.
How can I do this?
"This is not to prove that the data provider works ... but rather to prove that
the correct size was passed in."
Not sure if it works that well for this particular case, but generally I've found it easiest to test these sorts of things indirectly via the stub.
Rather than checking the output of the stubbed call, explicitly specify the arguments to your stub and then verify that the return value was used as expected (regardless of the actual data returned). If it was, then you know that your stub was called correctly.
//Arrange
var wheels = new List<IWheel>();
const int wheelSize = 17;
var car = new Car();
car.WheelSize = wheelSize;
var provider= MockRepository.GenerateStub<IDataProvider>();
provider
.Stub(x => x.GetWheelsWithSize(wheelSize))
.Return(wheels);
car.Provider = provider;
//Act
car.ReplaceTires();
//Assert that the right-sized wheels from the provider were
//used when replacing the tires
Assert.That(car.Wheels, Is.SameAs(wheels));
If this approach doesn't work for you in this case then you can use WhenCalled to inspect the call arguments and/or modify the return value.
provider
.Stub(x => x.GetWheelsWithSize(Arg<int>.Is.Anything))
.WhenCalled(x => x.ReturnValue = CreateWheelsOfSize((int) x.Arguments[0]));
In this case CreateWheelsOfSize(int) will just create your list of wheels.
Hope this helps.
You can use the Do() functionality in order to achieve dynamic return value. For example:
[Test]
public void DynamicallyFakeReturnValue()
{
var calculatorStub = MockRepository.GenerateStub<ICalculator>();
calculatorStub.Stub(address => address.AddOne(Arg<int>.Is.Anything))
.Do((Func<int, int>) (x => x - 1));
Assert.That(calculatorStub.AddOne(1), Is.EqualTo(0));
}
In your case it will probably be:
provider.Stub(
x => x.GetWheelsWithSize(Arg<int>.Is.Anything))
.Do((Func<int, List<IWheel>>) (size => new List<IWheel> {
new Wheel { Size = size, Make = Make.Michelin },
new Wheel { Size = size, Make = Make.Firestone }
}));

Moq - How to unit test changes on a reference in a method

Another day , another question. My service layer has the following method
public MatchViewData CreateMatch(string user)
{
var matchViewData = !HasReachedMaxNumberOfMatchesLimit(user) ?
CreateMatchAndAddToRepository(user) :
MatchViewData.NewInstance(new Match(user));
matchViewData.LimitReached = HasReachedMaxNumberOfMatchesLimit(user);
return matchViewData;
}
The method calls the this helper method to create a new match object:
private MatchViewData CreateMatchAndAddToRepository(string user)
{
var match = new Match(user);
MatchRepository.Add(match);
return MatchViewData.NewInstance(match);
}
The repository stores the given match object and sets the id to some value > 0.
public void Add(Match match)
{
Check.Require(match != null);
var numberOfMatchesBefore = Matches.Count;
SetIdPerReflection(match, NextVal());
Matches.Add(match);
Check.Ensure(numberOfMatchesBefore == Matches.Count - 1);
}
The matchviewdata object copies some properties of the the match object (including the id).
My unit test should verify that the resulting viewdata object in the service has an id > 0. To archieve this, i have to mock the repository and the behaviour of the add method. But the service method creates a new match object every time its been called and the add method on the repository updates the referenced match object (there is no need for a return value). I have no idea to solve this with moq.
This is my unit test so far:
[Test]
public void ServiceCreateMatchReturnedMatchViewDataHasNonZeroId()
{
var match = TestUtils.FakePersistentMatch(User, 1);
var repositoryMock = new Mock<IMatchRepository>();
repositoryMock.Setup(
r => r.Add(It.IsAny<Match>())).Callback(() => match.Id = 1);
var serviceFacade = new DefaultServiceFacade(repositoryMock.Object);
var returnedMatch = serviceFacade.CreateMatch(User);
Assert.That(returnedMatch.Id, Is.GreaterThan(0));
}
I tried some other variations - nothing works.
It looks to me your problem is in this line;
repositoryMock.Setup(
r => r.Add(It.IsAny<Match>())).Callback(() => match.Id = 1);
What you're actually doing here is setting the id of the first match object you have declared in your test, NOT the new match created in your service.
Because the Match object you will be supplying to the Repository is created internally, I can't think of an easy way to reference it in your Test method to setup a callback for it. To me, this is a sign you may be trying to test too much in one unit test.
I think you should simply test that the Add method is called and write a separate test to ensure that it works as exepected.
I propose something like this;
[Test]
public void ServiceAddsNewMatchToRepository()
{
var repositoryMock = new Mock<IMatchRepository>();
bool addCalled = false;
repositoryMock
.Expect(r => r.Add(It.Is<Match>(x => x.Id == 0))
.Callback(() => addCalled = true);
var serviceFacade = new DefaultServiceFacade(repositoryMock.Object);
serviceFacade.CreateMatch(User);
Assert.True(addCalled);
}
....
[Test]
public void AddingANewMatchGeneratesANewId()
{
var match = new Match(user);
var matchRepository = new MatchRepository();
var returnedMatch = matchRepository.Add(match);
Assert.That(returnedMatch.Id, Is.GreaterThan(0));
}