get field value of mocked object by reflection - reflection

class Person {
private String firstName;
private String lastName;
// getters and setters for firstName, lastName
}
#Test
void test() {
Person p = mock(Person.class);
when(p.getFirstName()).thenReturn("John");
when(p.getLastName()).thenReturn("Peter");
Map<String, Object> someContainerLikeMap = new HashMap<>();
org.springframework.util.ReflectionUtils.doWithFields(p.getClass(), field -> {
someContainerLikeMap.put(field.getName(), field.get(p));
// field.get(p) above, always get null
}
}
I've got two questions:
get by field reflection, field.get(p), always get null;
iteration of fields, what's the best way to just have fields defined in class Person included, that is, firstName, lastName?

Mockito works entirely through subclassing methods automatically with a "proxy object"; it doesn't override, change, or mock fields at all. You'll need a different tool for that.

Related

What's the best way to model Custom Object for Document ID in Firestore?

Say I have a collection of 'Users', and am happy for their ID to be the generated Firestore documentId, something like:
Users Collection
GENERATED_FIRESTORE_ID1:
name: "User 1 name"
...: etc.
GENERATED_FIRESTORE_ID2:
name: "User 2 name"
...: etc."
and I am adding them, and retrieving them with a custom object (I'm using Android at the moment but the question I guess is more generalistic). I don't want to have an extra "id" field in the document, just use the document.getId() method to get the generated firestore ID.
Is there a correct way to map a POJO to not have an indivual ID field, but when querying set it for application usage? I am doing it using the #Exclude annotation as follows:
public class User {
// as a side question, do I need #exclude on the field or just the getter?
#Exclude
String uId;
String name;
String email;
//... additional fields as normal
public User() {
}
#Exclude
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.displayName = name;
}
//... etc. etc.
}
and then I create the User object and set its ID as follows:
for (DocumentSnapshot doc : documentSnapshots) {
User user = doc.toObject(User.class);
user.setId(doc.getId());
users.add(user );
}
This works fine, and apologies if this is indeed the way, but I'm new to FireStore (am loving it) and want to make sure I'm doing it right. I just wondered if there was a way this would all be automatic, without #Exclude and then manually setting the ID after doc.toObject(MyCustomObject.class)
There is now an Annotation for this -
You could simply use
#DocumentId
String uID
https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/DocumentId.html

Custom class level bean validation constraint

I already know how to add annotation based validation on specific attributes in Entity class like :-
public class Person {
#NotNull
private String firstName;
private String lastName;
//...
}
But is it possible to add annotation on class Person, in order to validate all the attributes inside this class, by creating a Customised Validation Class and handling validation there somewhere like :-
#Retention(value = RetentionPolicy.RUNTIME)
#Target(value = ElementType.METHOD)
public #interface PersonneName {
public String firstName();
}
I am working on a project to get Constraints from Database and creating Customised Validation Class and applying on the Entity class attributes according to the constaints got from DB.
Please suggest.
Yes, of course, it's possible. First, create the definition of your annotation. Pretty much like you did in your example, however, with a different #Target type
#Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
#Retention(RetentionPolicy.RUNTIME)
#Constraint(validatedBy = PersonValidator.class)
public #interface ValidPerson {
String message () default "Your custom message";
Class<?>[] groups () default {};
Class<? extends Payload>[] payload () default {};
}
Then implement the validator whose isValid method takes the instance of your Person class:
public class PersonValidator implements ConstraintValidator<ValidPerson, Person> {
#Override
public boolean isValid (Person person, ConstraintValidatorContext context) {
// your validation logic
}
}
Sure it is possible, just check the documentation regarding how to write custom class level constraints - http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-class-level-constraints
The important thing of course is that you make sure that one can actually place the constraint annotation on the type level. For that you need to add ElementType.TYPE to the #Target annotation.

Usage of ReflectionUtils and BeanUtils for private fields

I need to set some private fields in an object using another object's fields. Those two objects may not be instances of same class.
What I see from a short reading, I can use Apache's BeanUtils and Spring's ReflectionUtils for that. I couldn't find a satisfying explanation for them regarding security, performance, support etc.
The solution will be used in production environment too, so I need a concrete solution.
Which approach do you suggest for such a task.
I think you need use just the BeanUtils library. See my sample, i do a copy properties from CustomerBean to SellerBean.
package testes.beanutils;
import org.apache.commons.beanutils.BeanUtils;
public class Main {
public static void main(String[] args) throws Exception {
Customer customer = new Customer();
customer.setId((long)1);
customer.setName("Bruno");
customer.setLastname("Tafarelo");
Seller seller = new Seller();
BeanUtils.copyProperties(seller, customer);
System.out.println(customer);
System.out.println(seller);
}
}
class Customer {
private Long id;
private String name;
private String lastname;
//getters and setters
//toString
}
class Seller {
private Long id;
private String name;
private int sales;
//getters and setters
//toString
}

Value object design pattern in Flex

I am just looking design patterns used in Flex. Please tell me about value object design pattern and how is it implemented in Flex. Thank you.
A Value Object is really nothing more than a data object. It is OK to have some methods on a Value Object, in my opinion... but they exist for convenience and don't really add any behavior. For instance, here is an example of a VO:
[Bindable]
public class PersonVO {
public var firstName:String;
public var lastName:String;
public function PersonVO(firstName:String, lastName:String) {
this.firstName = firstName;
this.lastName = lastName;
}
public function clone():PersonVO {
return new PersonVO(firstName, lastName);
}
}
Note that this class is mutable by default which is why I added the [Bindable] tag. You are likely to want to use data binding with this class and you need [Bindable] (or some equivalent) to make that happen.
I actually prefer immutable value objects in many cases. Here is how you would implement a mutable VO:
public class PersonVO {
private var _firstName:String;
private var _lastName:String;
public function PersonVO(firstName:String, lastName:String) {
_firstName = firstName;
_lastName = lastName;
}
public function get firstName():String { return _firstName; }
public function get lastName():String { return _lastName; }
}
A VO is similar to a bean if you are from a Java background. I would code a VO as
public class UserVO
{
private var _name:String;
public function set name(value:String):void
{
_name = value;
}
public function get name():String
{
return _name;
}
}
Here we declare private variables and provide setter and getter methods to set the value for the members variables. Although it is not advised, you can perform range checking before assigning values inside the setter method. You can access the members as :
var userVo:UserVO = new UserVO();
userVo.name = "some name";
The following site is worth to have a look: http://www.flashmonkey.co.uk/using-value-objects-in-flash/

Custom JsonSerialization

I have a simple class in asp.net mvc that looks like this:
public class JsonResponseItem
{
public string Key { get; set; }
public string Value { get; set; }
public JsonResponseItem(string key, string value)
{
Key = key;
Value = value;
}
}
In my controllers I create a list of that type
List<JsonResponseItem> response = new List<JsonResponseItem>();
so I can easily manage and add to the Json response. A dictionary object is kind of hard to do that with.
When I return the json object
return Json(response);
It deserializes it so I have to reference everything by index first, because of the list. So if I had a property called "IsValid" I would have to reference it like this "IsValid[0]". I have way too much javascript code to make these changes.
How could I deserialize the JsonResponseItem class so I don't need the index reference in there?
Thanks!
A Dictionary<string, string> would serialize into exactly the Json you're asking for. If you don't want to expose directly a dictionary, wrap it around in another class or use Json(response.ToDictionary(item => item.Key).

Resources