Change value of parameter in NSubstitute - unit-testing

I have this method to mock with NSubstitute:
public T VoerStoredProcedureUit<T>(string naam, params SqlParameter[] parameters)
The test method using it sends 2 SqlParameters to this method. VoerStoredProcedureUit is supposed to change the values of these parameters so the tested method can extract that.
I created the following with NSubstitute:
SqlParameter[] param =
{
new SqlParameter("#pat_id", SqlDbType.BigInt) {Direction = ParameterDirection.Output, Value = "Melding"},
new SqlParameter("#Melding", SqlDbType.VarChar, 4096) {Direction = ParameterDirection.Output, Value = 2}
};
productieVerbinding.VoerStoredProcedureUit<PatientNieuwResultaat>(Arg.Any<string>(),
Arg.Any<SqlParameter[]>()).ReturnsForAnyArgs(x =>
{
x[1] = param;
return PatientNieuwResultaat.Succes;
});
The setup however rises an exception:
A first chance exception of type 'NSubstitute.Exceptions.ArgumentIsNotOutOrRefException' occurred in NSubstitute.dll
Additional information: Could not set argument 1 (SqlParameter[]) as it is not an out or ref argument.
How do you return a value if the method uses implicitly by reference values?

If I understand your question correctly, you're trying to return the contents of param when VoerStoredProcedureUit<PatientNieuwResultaat> is called.
In ReturnsForAnyArgs, x[1] refers to the second parameter which is an SqlParameter[]. This isn't a ref/out parameter so you can't reassign it in the caller, which is why you get an error. Instead, you need to copy the elements from your template, into the supplied array. Something like this:
productieVerbinding.VoerStoredProcedureUit<PatientNieuwResultaat>(Arg.Any<string>(),
Arg.Any<SqlParameter[]>()).ReturnsForAnyArgs((x) =>
{
for (int i = 0; i < param.Length; i++)
{
((SqlParameter[])x[1])[i] = param[i];
}
return PatientNieuwResultaat.Succes;
});
You could obviously remove the for loop, since you know how many parameters you need to copy...
productieVerbinding.VoerStoredProcedureUit<PatientNieuwResultaat>(Arg.Any<string>(),
Arg.Any<SqlParameter[]>()).ReturnsForAnyArgs((x) =>
{
((SqlParameter[])x[1])[0] = param[0];
((SqlParameter[])x[1])[1] = param[1];
return PatientNieuwResultaat.Succes;
});

I found a working solution. Assigning a new variable to the parameters did't work somehow, but changing them does. Also, the second of the method parameter is an array, so it should be treated as such.
productieVerbinding.VoerStoredProcedureUit<PatientNieuwResultaat>(Arg.Any<string>(),
Arg.Any<SqlParameter[]>()).ReturnsForAnyArgs(x =>
{
paramPatId = ((SqlParameter[])x[1])[0];
paramMelding = ((SqlParameter[])x[1])[1];
paramPatId.Value = (long)2;
paramMelding.Value = "Melding";
return PatientNieuwResultaat.Succes;
});

Related

NoSuchMethodError. The method "add" was called on null even after initializing List

I have created a TextFormField in flutter. I have a class named ParticipantsData with a few properties listed. I can access and store values in all of those properties by making an object of ParticipantsData class in another class named "RegistrationForm". However I am unable to store data in the properties that are of type List even after having initialized them.
I have tried:
- List.filled()
- =[]
- =[""]
- List.generate()
- List()
- List<String>()
- List<String>(length)
I have changed my code multiple times over and tried many methods but nothing seems to work. I don't post here much because I usually find solutions on stackoverflow but this time I couldn't find anything.
Unable to post the whole code because it is too long. Below is the relevant code:
ParticipantsData class:
class ParticipantsData {
List name = []; //members
bool paymentstatus = false; //payment
String email = ""; //email
String address = ""; //address
List contact = []; //contact
String collegename = ""; //collegename
String password = ""; //password
String teamname = ""; //teamname
var modules = List<String>(6); //modules
ParticipantsData({
this.name,
this.email,
this.contact,
this.collegename,
this.address,
this.modules,
this.password,
this.paymentstatus,
this.teamname,
});
}
Below is the relevant code for Register class:
class _RegistrationForm extends State<RegistrationForm> {
final ParticipantsData data = new ParticipantsData();
//This is the onSaved method of a TextFormField, which is in a loop.
(String value) { //Tried this...
data.name[i + 1] = value;
print('${data.name[i + 1]}');
}),
(String value) { //And this too...
data.name.add(value);
print('${data.name[i + 1]}');
}),
The assigned values become null when initialized inside the constructor. If you don't include the fields in the constructor, they will not reset to null.
However, you may want to assign the values in the constructor and want some default value if the field is not provided while creating the instance. Here is how to do so:
class MyClass {
// Don't initialize here
List x;
int y;
MyClass({
this.x,
this.y = 10, // If y is not assigned, it will take a default value of 10
}) {
// Constructor body
this.x = this.x ?? []; // If x is not assigned, it will take a value of []
}
}
Notice that y can be provided with the default value directly as 10 is a constant value. You can only assign constant default values in the constructor parameter list. Since [ ] is not a constant expression or value, it can't be directly assigned as the default value hence, you need to define the constructor body assigning x = [ ] if x is null.
this.x = this.x ?? [];
You can initialize the others in a similar way.

Assert a method was called whilst verifying the parameters are correct

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);

Qjson handling an returned array of ojbects

I'm using Qjson to parse a json object that is returned from a web service. I'm stuck on handling an array of complex ojects.
At the first level the web service returns a map consisting of "error", "id", and "return". If there are no errors I can get the first level value by using
nestedMap = m_jsonObject["result"].toMap();
group = new Group();
group->Caption = nestedMap["Caption"].toString();
group->CollectionCount = nestedMap["CollectionCount"].toInt();
I can even get a date item value that is at the second level using
group->ModifiedOn = nestedMap["ModifiedOn"].toMap()["Value"].toDateTime();
I have an object called "Elements" that consists of 29 key-value pairs. The web service is returning an array of these "Elements" and I am unable to find the right way to parse it. In the header file the container for the elements is defined as
QList<GroupElement> Elements;
The line
group->Elements = nestedMap["Elements"].toList();
causes the compiler to throw an error 'error: no match for 'operator=' in '((MyClass*)this)->MyClass::group->Group::Elements = QVariant::toMap() const()'
I would like to learn the correct syntax to put this element into the class.
Update: I wrote another function to convert the QVariantMap object to a
first:
The group-> Elements object was changed to a
class ParentClass{
QList<SharedDataPointer<Address> > Elements;
other class memmbers...
};
Second:
A method to convert the QMap object to an Address object was created
QSharedDataPointer<Address>
API_1_6::mapToAddress(QVariantMap o)
{
QSharedDataPointer<Address> address (new Address());
address-> FirstName = o["FirstName"].toString();
address->LastName = o["LastName"].toString();
address->CompanyName = o["CompanyName"].toString();
address->Street = o["Street"].toString();
address->Street2 = o["Street2"].toString();
address->City = o["City"].toString();
address->Zip = o["Zip"].toString();
address-> State = o["State"].toString();
address->Country = o["Country"].toString();
address->Phone = o["Phone"].toString();
address->Phone2 = o["Phone2"].toString();
address-> Fax = o["Fax"].toString();
address-> Url = o["Url"].toString();
address->Email = o["Email"].toString();
address->Other = o["Other"].toString();
return address;
}
third: In the code, foreach is used to walk through the list and create and store the new objects
// get the list of the elements
elementsList = nestedMap["Elements"].toList();
// Add the element, converted to the new type, to the Elements object of the'parent' class
foreach(QVariant qElement, elementsList){
group-> Elements.append(mapToAddress(qElement))
}

Reflection on EmberJS objects? How to find a list of property keys without knowing the keys in advance

Is there a way to retrieve the set-at-creations properties of an EmberJS object if you don't know all your keys in advance?
Via the inspector I see all the object properties which appear to be stored in the meta-object's values hash, but I can't seem to find any methods to get it back. For example object.getProperties() needs a key list, but I'm trying to create a generic object container that doesn't know what it will contain in advance, but is able to return information about itself.
I haven't used this in production code, so your mileage may vary, but reviewing the Ember source suggests two functions that might be useful to you, or at least worth reviewing the implementation:
Ember.keys: "Returns all of the keys defined on an object or hash. This is useful when inspecting objects for debugging. On browsers that support it, this uses the native Object.keys implementation." Object.keys documentation on MDN
Ember.inspect: "Convenience method to inspect an object. This method will attempt to convert the object into a useful string description." Source on Github
I believe the simple answer is: you don't find a list of props. At least I haven't been able to.
However I noticed that ember props appear to be prefixed __ember, which made me solve it like this:
for (f in App.model) {
if (App.model.hasOwnProperty(f) && f.indexOf('__ember') < 0) {
console.log(f);
}
};
And it seems to work. But I don't know whether it's 100% certain to not get any bad props.
EDIT: Adam's gist is provided from comments. https://gist.github.com/1817543
var getOwnProperties = function(model){
var props = {};
for(var prop in model){
if( model.hasOwnProperty(prop)
&& prop.indexOf('__ember') < 0
&& prop.indexOf('_super') < 0
&& Ember.typeOf(model.get(prop)) !== 'function'
){
props[prop] = model[prop];
}
}
return props;
}
Neither of these answers are reliable, unfortunately, because any keys paired with a null or undefined value will not be visible.
e.g.
MyClass = Ember.Object.extend({
name: null,
age: null,
weight: null,
height: null
});
test = MyClass.create({name: 'wmarbut'});
console.log( Ember.keys(test) );
Is only going to give you
["_super", "name"]
The solution that I came up with is:
/**
* Method to get keys out of an object into an array
* #param object obj_proto The dumb javascript object to extract keys from
* #return array an array of keys
*/
function key_array(obj_proto) {
keys = [];
for (var key in obj_proto) {
keys.push(key);
}
return keys;
}
/*
* Put the structure of the object that you want into a dumb JavaScript object
* instead of directly into an Ember.Object
*/
MyClassPrototype = {
name: null,
age: null,
weight: null,
height: null
}
/*
* Extend the Ember.Object using your dumb javascript object
*/
MyClass = Ember.Object.extend(MyClassPrototype);
/*
* Set a hidden field for the keys the object possesses
*/
MyClass.reopen({__keys: key_array(MyClassPrototype)});
Using this method, you can now access the __keys field and know which keys to iterate over. This does not, however, solve the problem of objects where the structure isn't known before hand.
I use this:
Ember.keys(Ember.meta(App.YOUR_MODEL.proto()).descs)
None of those answers worked with me. I already had a solution for Ember Data, I was just after one for Ember.Object. I found the following to work just fine. (Remove Ember.getProperties if you only want the keys, not a hash with key/value.
getPojoProperties = function (pojo) {
return Ember.getProperties(pojo, Object.keys(pojo));
},
getProxiedProperties = function (proxyObject) {
// Three levels, first the content, then the prototype, then the properties of the instance itself
var contentProperties = getPojoProperties(proxyObject.get('content')),
prototypeProperties = Ember.getProperties(proxyObject, Object.keys(proxyObject.constructor.prototype)),
objectProperties = getPojoProperties(proxyObject);
return Ember.merge(Ember.merge(contentProperties, prototypeProperties), objectProperties);
},
getEmberObjectProperties = function (emberObject) {
var prototypeProperties = Ember.getProperties(emberObject, Object.keys(emberObject.constructor.prototype)),
objectProperties = getPojoProperties(emberObject);
return Ember.merge(prototypeProperties, objectProperties);
},
getEmberDataProperties = function (emberDataObject) {
var attributes = Ember.get(emberDataObject.constructor, 'attributes'),
keys = Ember.get(attributes, 'keys.list');
return Ember.getProperties(emberDataObject, keys);
},
getProperties = function (object) {
if (object instanceof DS.Model) {
return getEmberDataProperties(object);
} else if (object instanceof Ember.ObjectProxy) {
return getProxiedProperties(object);
} else if (object instanceof Ember.Object) {
return getEmberObjectProperties(object);
} else {
return getPojoProperties(object);
}
};
In my case Ember.keys(someObject) worked, without doing someObject.toJSON().
I'm trying to do something similar, i.e. render a generic table of rows of model data to show columns for each attribute of a given model type, but let the model describe its own fields.
If you're using Ember Data, then this may help:
http://emberjs.com/api/data/classes/DS.Model.html#method_eachAttribute
You can iterate the attributes of the model type and get meta data associated with each attribute.
This worked for me (from an ArrayController):
fields: function() {
var doc = this.get('arrangedContent');
var fields = [];
var content = doc.content;
content.forEach(function(attr, value) {
var data = Ember.keys(attr._data);
data.forEach(function(v) {
if( typeof v === 'string' && $.inArray(v, fields) == -1) {
fields.push(v);
}
});
});
return fields;
}.property('arrangedContent')

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 }
}));