JMockit: alter parameter of a mocked method - jmockit

Can JMockit modify the parameters of methods that it mocks? It's certainly easy to modify the return value of the method it mocks, but how about modifying the parameters themselves? I know it's possible to at least capture and test the mocked parameters using Verifications, but this happens after the fact.
Here is my simplified code:
class Employee{
Integer id;
String department;
String status;
//getters and setters follow
}
The method I want to test:
public int createNewEmployee() {
Employee employee = new Employee();
employee.setDepartment("...");
employee.setStatus("...");
//I want to mock employeeDao, but the real DAO assigns an ID to employee on save
employeeDao.saveToDatabase(employee);
return employee.getId(); //throws NullPointerException if mocked, because id is null
}

Use a Delegate object assigned to the result field, when recording an expectation on employeeDao.saveToDatabase(...). The delegate method (with an arbitrary name) should declare a Employee emp parameter; then simply call emp.setId(...) with whatever id value you want.
For examples, see the documentation.

Related

Alternate implementation of Builder Pattern. Anything wrong with this?

Most of the implementations of Builder pattern I have seen are along these lines:
https://github.com/Design-pattrns/Builder-Pattern/blob/master/src/Computer.java
Basically the nested builder class needs to mirror all the attributes of the class that we need to build objects of and then provide methods to set the said attributes and an additional build() method inside the builder class.
When I tried to implement builder on my own, I came up with this (I use an instance of Person object inside builder instead of copying all the attributes of the Person class)
public class Person {
private String firstName;
private String lastName;
public static class PersonBuilder{
private Person person = new Person();
public PersonBuilder firstName(String firstName){
person.firstName = firstName;
return this;
}
public PersonBuilder lastName(String lastName){
person.lastName = lastName;
return this;
}
public Person build(){
return person;
}
}
}
Benefits:
1). No need to repeat the attributes of the class we want to instantiate
2). build method is simplified, just need to return the person object.
3). The Person class need not have a constructor which takes the Builder object as argument
4). More easily "updatable". If new attributes are added to person class, all we need
to do is add the set method inside the builder class if needed. No need to
create another attribute.
Cons:
1). The person object is eager initialised?
So are there any issues with this implementation?
I would say the example above is "simpler" but it has none of the advantages a builder offers and its probably better to just use the new keywords where you need the object and adding the properties to the constructor. Id say the drawbacks compared to the builder are as follows:
it can only make a single instance
once the builder has "finished" it can continue to interact with the object as it still holds a reference to it.
its very tightly coupled to the product it is "building".
the fact that the person class has to expose a lot of properties as mutable for the builder, which you might want to not be mutable elsewhere in the code.
Its actually more of a configurator, I would not advise this pattern however you could pass the object to be configured into the constructor. In which case I would create two interfaces
IConfigurablePerson which includes the setters
IPerson which includes the getters
Give the configurator IConfigurablePerson to its constructor, so it can access the setters then give other classes IPerson with only the getters. The advantage this offers is that it can work with multiple implementations of IConfigurablePerson without needing to know the class its working with (decoupling).

Jackson deserialization: How to get a default value even if the JSON property was null

In my project I'm using Jersey 2.23.1 with Jackson for JSON support.
When I'm getting a request with something like { "foo":null, "bar":"123" } as JSON, matching with class A{String foo; String bar;} Jersey first creates and instance of A (with default values if specified in constructor), then deserialize JSON to a temporary object A', then copies all JSON fields that were specified in JSON from A' to A. If I have default values in A-class constructor, and have fields equal to null in JSON, all my default values are erased and replaced by null. So in the example above, if I have a default value for the foo field, it will be replaced by null in the object Jersey will return as param for my #Path annotated method.
I'm using #JsonInclude(Include.NON_NULL) on A class to avoid the transfer of null fields during Response. But it only works for serialization, what about deserialization? I mean, when having { "foo":null } as JSON results in field "foo" = null in new object instance after deserialization.
Here is some code to sum all of this :
#JsonIgnoreProperties(ignoreUnknown = true)
#JsonInclude(value = Include.NON_NULL)
public class User {
public enum EUserRole {
PARENT, STUDENT, PROF, ADMIN
}
#Id
public String id;
public String firstName;
public String lastName;
public EUserRole role;
public User() {
id = ObjectId.get().toString();
role = EUserRole.STUDENT;
lastName = "RandomLastName";
}
}
if I'm passing this kind of JSON
{
"id":null,
"lastName":null,
"firstName":"Random First Name",
"role":"STUDENT"
}
to my method (in controller)
#POST
public Response createUser(final User entity) {
}
it results that all null fields in JSON are set to null in my entity and not set to the constructor default values.
Do you know if there is a way to specify Jackson to ignore null fields during deserialization? Or is this a Jersey-related behavior?
There is no way to ignore data from JSON payload in that sense, based on value contained (you can use ignoral to just ignore all values for given property).
So if you want to avoid null assignment, you need define a setter that will just swallow null value (that is, only assign non-null).
Ability to prevent null assignment might a useful feature to add via #JsonFormat.Feature, something like:
// hypothetical no such feature exists yes
#JsonFormat(without = JsonFormat.Feature.ALLOW_NULL_ASSIGNMENT)
so perhaps this could be a feature request.
And the reason I think this belongs to per-property handling is that this seems like a specific rule for some of the properties. Although perhaps there could also be a matching global setting if it seems users really like such null-ignoral.

How to test a service method that returns a model?

So I have a service method that modifies a model object
public function doSomething() {
$model = new Model();
// Modify the model with a bunch of private methods
return $model;
}
If I want to test doSomething, I really only have $model to work with. And the only way I can write assertions on $model is to use its public interfaces.
$this->assertEquals($model->getName(), 'name');
What confuses me here is what exactly am I testing with that assertion? Am I testing that getName works properly or am I testing doSomething works properly?
In order for me to test doSomething, I have to assume that getName works. So how do I make sure that is the case?
Based on your code, I would test that I got an instance of Model returned. And then using the public accessors or assertAttributeEquals to check that the properties of the object were correct. This does test the getters of the model, however the object having certain properties is what you are expecting to happen.
Though as your class is both creating the object and modifying it. I would change the method to take a Model as an argument. This way in my test I can create a mockModel and make sure that any public setters are called with the proper arguments. Doing this, I don't have to worry about any of the logic that Model has for properties that get set.
For Example:
Test Function:
public function testDoSomething() {
$mockModel = $this->getMock('Model');
$mockModel->expects($this->once())
->method('foo')
->with('some argument');
$mockModel->expects($this->once())
->method('bar')
->with('some other argument');
$sut = new SUT();
$sut->doSomething($mockModel);
}
Your function doSomething only needs to become this:
public function doSomething(Model $model) {
/** Do stuff with private methods **/
}
Now you are able to make sure that properties of Model are set with the proper values and not depending on the logic that may or may not exist in the class. You are also helping to specify the contract that Model needs to fill. Any new methods that you are depending on will come out in your integration / system tests.
Your contract with doSomething() is, that it has to return an object of type "Model". Your contract is not getName() working on a returned object. As result, test $model to be of correct type:
$this->assertInstanceOf('Model', $model);
Documentation: PHPUnit -> assertInstanceOf()
As a hint, "[i]deally, each test case is independent from the others" 2014-10-21 wikipedia.org/wiki/Unit_testing.
So, in your test_doSomethingTest*(), you are supposed to test only what happens within that function. Check for return type, and whatever happens withing that function. Testing getName() should be in it's own test_getName*().

Can a class return an object of itself

Can a class return an object of itself.
In my example I have a class called "Change" which represents a change to the system, and I am wondering if it is in anyway against design principles to return an object of type Change or an ArrayList which is populated with all the recent Change objects.
Yes, a class can have a method that returns an instance of itself. This is quite a common scenario.
In C#, an example might be:
public class Change
{
public int ChangeID { get; set; }
private Change(int changeId)
{
ChangeID = changeId;
LoadFromDatabase();
}
private void LoadFromDatabase()
{
// TODO Perform Database load here.
}
public static Change GetChange(int changeId)
{
return new Change(changeId);
}
}
Yes it can. In fact, that's exactly what a singleton class does. The first time you call its class-level getInstance() method, it constructs an instance of itself and returns that. Then subsequent calls to getInstance() return the already-constructed instance.
Your particular case could use a similar method but you need some way of deciding the list of recent changes. As such it will need to maintain its own list of such changes. You could do this with a static array or list of the changes. Just be certain that the underlying information in the list doesn't disappear - this could happen in C++ (for example) if you maintained pointers to the objects and those objects were freed by your clients.
Less of an issue in an automatic garbage collection environment like Java since the object wouldn't disappear whilst there was still a reference to it.
However, you don't have to use this method. My preference with what you describe would be to have two clases, changelist and change. When you create an instance of the change class, pass a changelist object (null if you don't want it associated with a changelist) with the constructor and add the change to that list before returning it.
Alternatively, have a changelist method which creates a change itself and returns it, remembering the change for its own purposes.
Then you can query the changelist to get recent changes (however you define recent). That would be more flexible since it allows multiple lists.
You could even go overboard and allow a change to be associated with multiple changelists if so desired.
Another reason to return this is so that you can do function chaining:
class foo
{
private int x;
public foo()
{
this.x = 0;
}
public foo Add(int a)
{
this.x += a;
return this;
}
public foo Subtract(int a)
{
this.x -= a;
return this;
}
public int Value
{
get { return this.x; }
}
public static void Main()
{
foo f = new foo();
f.Add(10).Add(20).Subtract(1);
System.Console.WriteLine(f.Value);
}
}
$ ./foo.exe
29
There's a time and a place to do function chaining, and it's not "anytime and everywhere." But, LINQ is a good example of a place that hugely benefits from function chaining.
A class will often return an instance of itself from what is sometimes called a "factory" method. In Java or C++ (etc) this would usually be a public static method, e.g. you would call it directly on the class rather than on an instance of a class.
In your case, in Java, it might look something like this:
List<Change> changes = Change.getRecentChanges();
This assumes that the Change class itself knows how to track changes itself, rather than that job being the responsibility of some other object in the system.
A class can also return an instance of itself in the singleton pattern, where you want to ensure that only one instance of a class exists in the world:
Foo foo = Foo.getInstance();
The fluent interface methods work on the principal of returning an instance of itself, e.g.
StringBuilder sb = new StringBuilder("123");
sb.Append("456").Append("789");
You need to think about what you're trying to model. In your case, I would have a ChangeList class that contains one or more Change objects.
On the other hand, if you were modeling a hierarchical structure where a class can reference other instances of the class, then what you're doing makes sense. E.g. a tree node, which can contain other tree nodes.
Another common scenario is having the class implement a static method which returns an instance of it. That should be used when creating a new instance of the class.
I don't know of any design rule that says that's bad. So if in your model a single change can be composed of multiple changes go for it.

Dynamic Table Names in Linq to SQL

Hi all I have a horrid database I gotta work with and linq to sql is the option im taking to retrieve data from. anywho im trying to reuse a function by throwing in a different table name based on a user selection and there is no way to my knowledge to modify the TEntity or Table<> in a DataContext Query.
This is my current code.
public void GetRecordsByTableName(string table_name){
string sql = "Select * from " + table_name;
var records = dataContext.ExecuteQuery</*Suppossed Table Name*/>(sql);
ViewData["recordsByTableName"] = records.ToList();
}
I want to populate my ViewData with Enumerable records.
You can call the ExecuteQuery method on the DataContext instance. You will want to call the overload that takes a Type instance, outlined here:
http://msdn.microsoft.com/en-us/library/bb534292.aspx
Assuming that you have a type that is attributed correctly for the table, passing that Type instance for that type and the SQL will give you what you want.
As casperOne already answered, you can use ExecuteQuery method first overload (the one that asks for a Type parameter). Since i had a similar issue and you asked an example, here is one:
public IEnumerable<YourType> RetrieveData(string tableName, string name)
{
string sql = string.Format("Select * FROM {0} where Name = '{1}'", tableName, name);
var result = YourDataContext.ExecuteQuery(typeof(YourType), sql);
return result;
}
Pay attention to YourType since you will have to define a type that has a constructor (it can't be abstract or interface). I'd suggest you create a custom type that has exactly the same attributes that your SQL Table. If you do that, the ExecuteQuery method will automatically 'inject' the values from your table to your custom type. Like that:
//This is a hypothetical table mapped from LINQ DBML
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.ClientData")]
public partial class ClientData : INotifyPropertyChanging, INotifyPropertyChanged
{
private int _ID;
private string _NAME;
private string _AGE;
}
//This would be your custom type that emulates your ClientData table
public class ClientDataCustomType
{
private int _ID;
private string _NAME;
private string _AGE;
}
So, on the former example, the ExecuteQuery method would be:
var result = YourDataContext.ExecuteQuery(typeof(ClientDataCustomType), sql);