In my unit tests I usually use reflection to manually inject a mock to the tested class' private field:
static void setFieldValue(Object instance, String fieldName, Object fieldValue, Class instanceClass) {
def field = instanceClass.getDeclaredField(fieldName)
field.accessible = true
field.set(instance, fieldValue)
}
Where instanceClass is the class/superclass, where the class is actually declared. How can I make it work or achieve same result for a private field being declared on a groovy trait?
My IDE helped me - just use the # attribute access notation, where the fieldname is package_dots_replaced_with_underscore_TraitName__fieldName, e.g.
testee.#pl_kamilroman_DeleteEntityBean__messages
Related
I'm trying to follow a tutorial on using the unit of work and repository pattern on MSDN but I've stumbled at the below:
private UnitOfWork unitOfWork = new UnitOfWork();
"This code adds a class variable for the UnitOfWork class. (If you were using interfaces here, you wouldn't initialize the variable here; instead, you'd implement a pattern of two constructors"
Basically, I need to call my UnitOfWork class in my LogController without actually using the above code as I'm using an interface? How is this possible? I'm not sure what it means by 'two constructors'.
Any advice would be appreiciated
In your class you define
Private IUnitOfWork _unitOfWork = null;
And you have one constructor which accepts an IUnitOfWork so the caller can pass in an implementation:
Public MyClass (IUnitOfWork unitOfWork) {
_unitOfWork = unitOfWork;
}
And you have another which does not, but knows how to go and find which implementation to create. Either it can use a default implementation, or it can go to some config file you've written to define which type to use, etc.
Within the MyClass you still call _unitOfWork.whateverMethod()
I have a big set of classes (like more that 100) and they are all extend from some abstract class, let's call it ParentClass. Let's call child classes ChildA,ChildB, etc. How can I register custom deserializer for all children and get class type inside my Deserializer?
I tried:
module.addDeserializer(ParentClass.class, new MyObjectDeserializer());
but it does not work.
I want to skip doing (what is working):
module.addDeserializer(ChildA.class, new MyObjectDeserializer(ChildA.class));
module.addDeserializer(ChildB.class, new MyObjectDeserializer(ChildB.class));
module.addDeserializer(ChildC.class, new MyObjectDeserializer(ChildC.class));
//etc......
Class type should be known, as I am use Jackson for spring #RequestBody method, what have defined class name there.
Any ideas how this can be done?
As far as I know, I don't think there is a mechanism in jackson that will address your exact needs.
However, there are a couple alternatives you can try.
Deserializing polymorphic types with Jackson describes one such alternative, however, you would still need to explicitly define all of the supported subtypes.
Another alternative that would not require you to explicitly define deserialization relationships would be to change your class hierarchy from one of inheritance to that of a container.
For example, converting your abstract parent class to a container like so:
public class DataContainer<T> {
String commonString;
Integer commonInteger;
T subData;
}
Would allow you to simply define in your controller input function as
public String controllerFunction(DataContainer<ClassA> classA);
without a need to define all these subclass deserializations.
Late to the party but I had a similar problem which I solved by registering a custom Deserializers to my SimpleModule. The code is in Kotlin but it should be easy to port it to Java.
The class itself:
class UseBaseClassSimpleDeserializers(
private val baseClass: Class<*>,
private val baseClassDeserializer: JsonDeserializer<*>
) : SimpleDeserializers() {
#Throws(JsonMappingException::class)
override fun findBeanDeserializer(
type: JavaType?,
config: DeserializationConfig?,
beanDesc: BeanDescription?
): JsonDeserializer<*>? {
val beanDeserializer = super.findBeanDeserializer(type, config, beanDesc)
return if (beanDeserializer == null && baseClass.isAssignableFrom(type!!.rawClass)) {
baseClassDeserializer
} else {
beanDeserializer
}
}
}
How to register the custom Deserializers class to a SimpleModule:
val simpleModule = SimpleModule()
simpleModule.setDeserializers(UseBaseClassSimpleDeserializers(ParentClass::class.java, ParentClassDeserializer()))
I need to bind request parameters to an instance of the following Java class (getters and setters omitted):
public class ShippingHouse {
private String name;
private String description;
private List<ShippingRule> shippingRules = new ArrayList<ShippingRule>();
}
public class ShippingRule {
private ShippingHouse shippingHouse;
private String name
}
Notice that there is a 1:N relationship between ShippingHouse and ShippingRule, but each ShippingRule also has a reference to the ShippingHouse thaat owns it.
If these were Grails command/domain classes, I would bind them with request parameters
name=foo&description=bar&shippingRules[0].name=sr0&shippingRules[1].name=sr1
But it doesn't seem like this will set the reference to the owning ShippingHouse within each ShippingRule. Is there a way I can bind this automatically, or must I write the code myself?
Don,
You will need to write code to do it yourself using BindUsing or some other approach. The binder doesn't (and shouldn't) assume anything about back references from a parent to a child. If these were GORM entities and the relationship was explicit, that is different, but in your case the binder should not assume that shippingHouse property in the ShippingRule class has anything to do with the shippingRules property in the ShippingHouse class.
Also note that lucke84 said that your "private" is implicit. Make sure you understand what that means if you are going to remove them. If you remove them the compiler is going to generate public getter and setter methods for those properties, which may or may not be what you want.
If you want to implement a 1:N relationship between the two classes, you should use the right grails approach. Something like this:
class ShippingHouse {
String name
String description
static hasMany = [shippingRules: ShippingRule]
}
class ShippingRule {
String name
static belongsTo = [shippingHouse: ShippingHouse]
}
Please note that semicolons are useless and the "private" declaration on class fields is implicit.
Maybe I should just make this a public member, but I keep thinking it should be a constant.
SCENARIO
I have forms I'm rendering into PDFs (using iTextSharp). In code, the forms themselves all inherit a base class (OrderForm). Within OrderForm, there are a list of constants that I use for measurements when aligning things for the PDF rendering, such as LEFT_MARGIN, etc. These constants are used in several functions to determine where things go.
All the forms are virtually identical as they are comprised of the same components (header, address boxes, items, etc). However, the layout of the forms differ slightly... on one form, the address box is an inch further to the right (to fit in the envelope window my employer uses).
ISSUE
Rather than create a slew of constants for each margin, padding, blah blah for each form in the base class, eg: PURCHASE_ORDER_LEFT_MARGIN, INVOICE_LEFT_MARGIN, etc, wouldn't it be better to create an overridable LEFT_MARGIN that can be set in the "inheritee" [sic] object? My reasoning is that it is a constant that will not change within that object, only form to form, yet the renderings in the base class will remain relative to whatever that constant is.
I know I could simply create a public member and set its value, but I'd like to know the right way to go about this.
Thanks.
Constants are implicitly static (Shared).
Use a Readonly Property instead, and then you can choose to override it whenever or wherever need be.
A quick example ....
Class BaseClass
' Assume this field is set with a value from somewhere else'
Private _leftmargin As Integer
Overridable Readonly Property LEFT_MARGIN As Integer
Get
Return _leftmargin
End Get
End Property
End Class
Class DerivedClass1
Inherits BaseClass
Overrides Readonly Property LEFT_MARGIN As Integer
Get
Return 5 'specialized case for this class'
End Get
End Property
End Class
Class DerivedClass2
Inherits BaseClass
'uses base class LEFT_MARGIN'
End Class
Constants are compiled as literal values. If you have this (C#) source code:
public static class MyStringTestClass
{
// Fields
public const string ConstString = "Const String";
public void TestMethod()
{
string sc = MyStringTestClass.ConstString;
SomeOtherFunction(sc);
}
}
then the compiler will produce this:
public static class MyStringTestClass
{
// I'm not 100% sure if this declaration is removed as well...
public const string ConstString = "Const String";
public void TestMethod()
{
// ...but I know for sure that it will be removed
// everywhere it's used - including other assemblies!
string sc = "Const String";
SomeOtherFunction(sc);
}
}
As you see, "ConstString" is completely GONE and it's literal value is inserted everywhere.
So use the VB.net equivalent of a ReadOnly Virtual Property (I think "virtual" is called "Overridable" in VB.net?) and override it.
What you want is a regular property ... Any value that changes is not a constant ... :)
What you can do is to use methods instead of constants. At the base class the method will return the value of the constant as it is now.
Inheriting class can provide a new value for the "constant" by overriding the corresponding method.
I have an actionscript class called Dimension, which allows a client to specify a dimension using a value and a unit such as "CM" or "Inches". I want to use an instance of this class as a property in MXML, so a user can write
<DimensionView value="2cm"/>
How do I make "2cm" an accepted string value for Dimension? I assume I need to write a parser method on my Dimension class, but I can't work out which interface I should be implementing to provide this functionality.
Can anyone help?
One option is to just type the value property as a String, write a getter and a setter for it and do the parsing there:
/**
* docs here
*/
[Bindable(event="valueChanged")]
public function get value():String
{
return _valueInt.toString();
}
/**
* #private
*/
public function set value(aVal:String):void
{
// parse the aVal String to an int (or whatever) here
_valueInt = parsed_aVal;
dispatchEvent(new Event("valueChanged"));
}
On a related note, the framework components implement the feature of allowing for the usage of percentage signs in some sizing properties, when assigned in MXML, by using an undocumented metadata field called PercentProxy. The below example is the width property getter and setter from mx.core.UIComponent:
[Bindable("widthChanged")]
[Inspectable(category="General")]
[PercentProxy("percentWidth")]
override public function get width():Number
{
// --snip snip--
}
override public function set width(value:Number):void
{
// --snip snip--
}