Often do I find myself creating the same unit tests methods to getters\setters, c'tors and Object methods (hashCode, equals and toString).
What I'm trying to achieve, with the help of Eclipse IDE, is automation of this procedure.
consider this example:
public Class Person {
private String id;
private String name;
public Person(String id, String name){
this.id = id;
this.name = name;
}
public String getId() { return id; }
public void setId(String id) {
this.id = id;
}
public String getName() { return name; }
public void setName(String name) {
this.name = name;
}
#override
public int hashCode(){ ... }
public boolean equals(Person other){ ... }
public String toString(){ ... }
/* this class may implement other logic which is irrelevant for the sake of question */
}
The unit test class will look something like this:
public class PersonTest extends TestCase
{
#override
public void setup() {
Person p1 = new Person("1","Dave");
Person p2 = new Person("2","David");
}
#override
public void tearDown() {
Person p1 = null;
Person p2 = null;
}
public void testGetId() {
p1.setId("11");
assertEquals("Incorrect ID: ", "11", p1.getId());
}
public void testGetName() { /* same as above */ }
public void testEquals_NotEquals() { /* verify that differently initialized instances are not equals */ }
public void testEquals_Equals() { /* verify that an object is equals to itself*/ }
public void testHashCode_Valid() { /* verify that an object has the same hashcode as a similar object*/ }
public void testHashCode_NotValid() { /* verify that different objects has different hashcodes*/ }
public void testToString() { /* verify that all properties exist in the output*/ }
}
This skeleton is similar to the vast majority of classes created.
can it be automated with Eclipse?
Have a look at Fast Code. It is an eclipse plugin that provides very nice feature of templating stuff which is what you seem to be looking for. On the documentation page look for Create Unit Test section.
A very useful feature of this plugin is to create unit tests automatically. Unit tests can be of type Junit 3, Junit 4 or TestNG. For Junit 4 or TestNG tests, appropriate annotations will be automatically added. One needs to configure it just once.
Unit tests are meant to show that an Object's behaviour is conforming to it's expected behaviour. They are not meant to make sure that the Java language is working correctly.
What you have here is a fancy data structure, with no behaviour. In that case every assignment is mediated by a method call, and every dereference is also mediated by a method call. Since Object Oriented programming is "data + behaviour" = objects, and this code lacks behaviour, it's a candidate for being called non-object-oriented code.
Sometimes Java uses non-object-oriented classes to facilitate transfer of information. The class guarantees that all information gets transferred as one unit when doing serialization. So having such a class isn't an indicator that the code is wrong; however, if you run into too many classes like this then something is very wrong.
One key element of testing is that it's not really a test if the test cannot fail. If the test cannot fail, it's just busywork. Assuming that one of these fields cannot be null then the setter might look like
public void setName(String name) {
if (name == null) throw new IllegalArgumentException("name cannot be null");
this.name = name;
}
And then you have something to test. Otherwise, your just checking to see if the assignment operator failed. As an aside, if the assignment operator failed, then I'd wager that the JVM is going to come down pretty hard sooner (rather than later) and you can't trust your tests to report correctly either.
Related
I try to understand a few unclear issues:
Which approach to composing objects/aggregates presented below is the best (examples below are simplified - normally I use vavr and FP instead of throwing exceptions)? DescriptionValidator is just a port. In his implementation I'm currently asking other microservice about description correctness.
a)
public class Description {
private final String text;
public Description(String text) {
this.text = text;
}
}
public class Item {
private final Description description;
public Item(Description description) {
this.description = description;
}
}
public class ItemService {
private final DescriptionValidator descriptionValidator;
private final ItemRepo itemRepo;
public void saveNewItem(String description) {
if(descriptionValidator.isValid(description)) {
itemRepo.save(new Item(new Description(description)));
}
}
}
b)
public class Description {
private final String text;
public Description(String text) {
this.text = text;
}
}
public class Item {
private final Description description;
public Item(String description) {
this.description = new Description(description);
}
}
public class ItemService {
private final DescriptionValidator descriptionValidator;
private final ItemRepo itemRepo;
public void saveNewItem(String description) {
if(descriptionValidator.isValid(description)) {
itemRepo.save(new Item(description));
}
}
}
c)
public class Description {
private final String text;
private Description(String text) {
this.text = text;
}
public static Description validated(String text, DescriptionValidator validator) {
if(validator.isValid(text)) {
return new Description(text);
}
throw new RuntimeException();
}
}
public class Item {
private final Description description;
public Item(String description, DescriptionValidator validator) {
this.description = Description.validated(description, validator);
}
}
public class ItemService {
private final DescriptionValidator descriptionValidator;
private final ItemRepo itemRepo;
public void saveNewItem(String description) {
itemRepo.save(new Item(description, descriptionValidator));
}
}
or
d)
public class Description {
private final String text;
private Description(String text) {
this.text = text;
}
public static Description validated(String text, DescriptionValidator validator) {
if(validator.isValid(text)) {
return new Description(text);
}
throw new RuntimeException();
}
}
public class Item {
private final Description description;
public Item(Description description) {
this.description = description;
}
}
public class ItemService {
private final DescriptionValidator descriptionValidator;
private final ItemRepo itemRepo;
public void saveNewItem(String description) {
itemRepo.save(new Item(Description.validated(description, descriptionValidator)));
}
}
TL; DR: Parse, Don't Validate
We normally prefer to convert unstructured/general-purpose inputs to structured inputs near the boundary. There are two reasons for this - first, that's the part of the code most likely to be able to report a problem correctly, and second that's the part of the code that is actually aware of the expected message format.
For instance, if we are dealing with something like an HTTP form submission, we normally want to verify that the data we find in the HTTP request actually conforms to our messaging schema (which is to say, the stable agreement about messages between this server and its clients).
Translation from the message schema to the in memory representations expected by the domain model is actually a separate concern.
That second concern should be addressed in your application layer - which is to say that it is the responsibility of your application code (the same "layer" that knows about your repositories, and transaction semantics, and so on) to translate from MessageSchema.Description to DomainModel.Description (and handle any edge cases where these two concepts are not actually aligned).
Validation within the domain value itself is a defensive programming tactic to ensure that the data structure within DomainModel.Description satisfies all of the preconditions necessary to ensure that the Description methods return consistent results.
Horses for courses.
I'll use your second code which contains a much more realistic example. Throughout this description I will refer to the Ubiquitous Language as UL.
Here are a few things I have picked up from this code that will matter to the design
Description is a value Object
Item is the Entity that owns Description (so, in UL Parlance: An Item has a description)
An Item contains a Description
Let's now look at your invariants from the context listed above.
Description cannot be NULL: This invariant, in your UL, will translate to Items always have a description. The best way to check for this kind of invariant is in the constructor of the Item itself.
public class Item {
...
public Item(string description) {
if (description == null) throw NoDescriptionException();
}
}
Cannot be too Long - This is an interesting one because you have not given enough information to allow me to glean how this can be represented in your UL. I'll assume the most basic UL representation and say your intent is Items have a max description of X length because <<Insert reason here>>. In this case, again the check will go in the Item Constructor.
public class Item {
...
private int MaxLength = 200;
public Item(string description) {
if (description == null) throw NoDescriptionException();
if (description.length > MaxLength) throw DescriptionTooLongException();
}
}
Cannot contain Profanities: In this case, the logic for checking for Profanities may be involved and contain things that are most likely out of the boundary of the Item Entity. That logic doesn't fit too well into any concepts but a service. So
public class ProfanityService implements IProfanityService
{
...
public bool ContainsProfanity(string text){...}
}
public class Item {
...
public Item(Description description, IProfanityService profanityService) {
if (description == null) throw NoDescriptionException();
if (description.length > MaxLength) throw DescriptionTooLongException();
if (profanityService.containsProfanity(description)) throw TooProfaneException();
}
}
There is an argument to be made against putting something like the Profanity Checker in a constructor and if someone pushed back on me because of that, I wouldn't fight too hard to keep that design. There are other ways to handle it that would be equally as robust as long as you keep the logic for such a check contained within a context that makes better sense than in the Item's context.
A few notes about my sample code above:
I haven't even created a Description class yet because there's no need for it. Description can stay as a native string until my UL exposes a requirement that says otherwise.
I didn't create a service to handle even the persistance of the entity because that doesn't belong in a service. The dynamics of implementing persistence in DDD is something that is relatively complex and there are many different ways to skin that cat. I usually have a Repository whose sole purpose is to persist the entity. So, I compose the new entity (directly by "newing it up" if it's simple enough or by using a Factory) and pass that entity to a repository ( through a call in the Application Service)
My use of a service only occured when the concept described by the UL didn't fit anywhere else. You want to avoid creating an Anaemic Model. You want to instead create rich Domain Entities that express your UL. Another change I would make to your code to further drive this point home is to generate the Id for the Item, inside the Id itself. I would do this in the constructor of the Item class.
Hibernate's validation (hibernate-validator) does validation when #Entity is being persisted (before). That is not enough as I want seamless validation on business layer.
So the goal is to validate fields on any change - meaning that e.g. #NotBlank applied to field will throw an exception whenever I call this.field = value; with blank variable (without calling outside validation service, so basically an aspect).
Based on my knowledge on AspectJ, there should be an existing possibility for javax.validation annotation applied on fields to be making them on-change sensitive.
My question is - what tools do I use and how do I configure them or what am I even looking for (I have no knowledge on this spec nor its implementations)?
My backend stack is Spring (Boot) with JPA (Hibernate) that ships with mentioned hibernate-validator, what else do I need to make my goal work with least code/config?
EDIT
To give example:
#NotBlank
private String name;
public void setName1(String name)
{
System.out.println("CHANGING 1");
this.name = name;
System.out.println("PASSED 1");
}
public void setName2(String name)
{
System.out.println("CHANGING 2");
this.name = name;
System.out.println("PASSED 2");
}
...with call:
public void test()
{
String newName = " ";
entity.setName1(newName);
entity.setName2(newName);
}
Should print:
CHANGING 1
and:
public void test2()
{
String newName = " "l
try { this.entity.setName1(newName); } catch (Exception e) { }
this.entity.setName2(newName);
}
Should print:
CHANGING 1
CHANGING 2
I thought of using private setter like:
private void setNamePriv(String name)
{
this.name = name;
}
private void setName1(String name) // or setName2
{
this.setNamePriv(name);
}
...but then I still don't know how to make name argument checked for #NotBlank when method is ran. Apparently syntax:
private void setNamePriv(#NotBlank String name)
{
this.name = name;
}
...is supported, but what library/configuration actually would make it work (currently used hibernate-validator doesn't do it by default).
Then again - using private setters introduces more boilerplate code across all entity classes and I am already using lombok to make those setters. Would have to make public setters with lombok and private myself or other way around.
What technology (library/config) am I looking for here?
EDIT 2
To clarify even more - I do know the reasons why it's not supported out-of-box:
Spring AOP uses proxies and does so only on #Beans (which are proxied).
For validation to take place #Bean (e.g. #Component or #Service) must also have #Validated.
As described that is a no-go, since e.g. #Entity is not a #Bean. As mentioned, I am probably looking for AspectJ solution but apparently there is nothing I could find. I don't think writing own aspect is that hard for this, but how come i can't find existing solution?
Im writing unit test using testng and mockito.
Im normally practice to call one method few times inside same test method by using different values / condition to check all scenarios.
Please dont think about the logic, and design i have provided. this is just sample for clear what actually i want to make.
Review code below.
public class Human {
private String name;
private boolean parent;
private List<Human> childs = new ArrayList<>();
public String getName() {
return name;
}
public boolean isParent() {
return parent;
}
public void setParent(boolean parent) {
this.parent = parent;
}
public void addChild(List<Human> childs) {
this.childs = childs;
}
public List<Human> getChilds() {
return childs;
}
}
public class Validator {
public boolean isParent(Human human) {
if (null == human) {
return false;
}
if (human.isParent()) {
return true;
}
if (human.getChilds().size() > 0) {
return true;
}
return false;
}
}
Im writing test case for Validator isParent method by using mockito.
public class ValidatorTest {
public void testIsParent() throws Exception {
Validator validator = Mockito.spy(new Validator());
Human human = Mockito.mock(Human.class);
Mockito.when(human.isParent()).thenReturn(false);
boolean isParent = validator.isParent(human);
Mockito.verify(human).getChilds();
Mockito.when(human.isParent()).thenReturn(true);
isParent = validator.isParent(human);
Mockito.verify(human).getChilds();
}
In here i want to verify that getChilds() never call for second method call to validator.isParent(human) because mocked human set to return true when call human.isParent();
I used Mockito.verifyZeroInteractions() but it says fail
As i understand Mockito.verifyZeroInteractions() check through all test. not only for particular method call.
I want to know is there some way to verify that method is not call for some cases and method call for same cases within same test method.
Or should i should practice test one scenario in one test method.
It's a good practice to have "one scenario per one one test method" (see How many unit tests should I write per function/method? )
Technically it's still possible to reset mocks with Mockito.reset(...), but this what official documentation says about it:
Smart Mockito users hardly use this feature because they know it could be a sign of poor tests.
Normally, you don't need to reset your mocks, just create new mocks for each test method.
Instead of reset() please consider writing simple, small and focused test methods over lengthy, over-specified tests. First potential code smell is reset() in the middle of the test method. This probably means you're testing too much. Follow the whisper of your test methods: "Please keep us small & focused on single behavior".
See https://static.javadoc.io/org.mockito/mockito-core/2.9.0/org/mockito/Mockito.html#17
The verify method can accept a second argument where you can specify how many times the method has been called. You can use this to say the method was never called, called once, twice etc.
For example:
import static org.mockito.Mockito.never;
...
public void testIsParent() throws Exception {
Validator validator = Mockito.spy(new Validator());
Human human = Mockito.mock(Human.class);
Mockito.when(human.isParent()).thenReturn(false);
boolean isParent = validator.isParent(human);
Mockito.verify(human).getChilds();
Mockito.when(human.isParent()).thenReturn(true);
isParent = validator.isParent(human);
Mockito.verify(human, never()).getChilds();
}
The documentation for this is here: http://static.javadoc.io/org.mockito/mockito-core/2.9.0/org/mockito/Mockito.html#4
I want to point out that this question seriously abuses mocking, for testing something that can easily and cleanly be tested without any mocks.
This is what the tests should look like:
public class ValidatorTest {
final Validator sut = new Validator();
#Test
public void checkThatNoHumanIsNotAParent() {
boolean isParent = sut.isParent(null);
assertFalse(isParent);
}
#Test
public void checkHumanThatIsNotAParent() {
Human notAParent = new Human();
boolean isParent = sut.isParent(notAParent);
assertFalse(isParent);
}
#Test
public void checkParentHumanWithNoChildIsAParent() {
Human parentWithNoChildren = new Human();
parentWithNoChildren.setParent(true);
boolean isParent = sut.isParent(parentWithNoChildren);
assertTrue(isParent);
}
#Test
public void checkHumanNotMarkedAsParentButWithChildIsAParent() {
Human humanWithChildren = new Human();
Human child = new Human();
humanWithChildren.addChild(child);
boolean isParent = sut.isParent(humanWithChildren);
assertTrue(isParent);
}
}
These tests completelly exercise all four scenarios. They are clearly much better than a version that uses mocking. Finally, note that Mockito's documentation (in the page on how to write good tests) also says that value objects (such as Human) should not be mocked.
As the title says....
I want to build a POJO with four field variables and at certain runtime events create an instance of this POJO with access to possibly maybe two or three of the fields.
public class Category implements Serializable {
private String name;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Lets say I create a new Category object but I only want to be able to have access to the name field during runtime. Is there a design pattern I can use to achieve this? I thought about the strategy pattern and looked at the builder but I am still confused if I can do this in java.
Basically the overall goal is to grab an object from a database and return it as a JSON response in jax rs. But sometimes I dont want a complete object returned but only lets say halve of the object to be accessible at during certain runtime events. My apologies if this seems like a dumb question but I know what I want to do but just don't know the best way.
I have the same problem with you, and my project was used springmvc,and the json tool is jackson.With the problem solved, I just use #JsonIgnore.For more details,just read jackson-how-to-prevent-field-serialization
So someone correct me if I am wrong or see a better option than this...with alot of objects this can be alot of extra code for serialization and deserialization...Jackson Provisions is what I need. I can use the annotation #JsonView(DummyClass.class) on the field variable. I will accept this a the best answer in a day or two unless someone else posts a better response.
// View definitions:
class Views {
static class Public { }
static class ExtendedPublic extends PublicView { }
static class Internal extends ExtendedPublicView { }
}
public class Bean {
// Name is public
#JsonView(Views.Public.class) String name;
// Address semi-public
#JsonView(Views.ExtendPublic.class) Address address;
// SSN only for internal usage
#JsonView(Views.Internal.class) SocialSecNumber ssn;
}
With such view definitions, serialization would be done like so:
// short-cut:
objectMapper.writeValueUsingView(out, beanInstance, ViewsPublic.class);
// or fully exploded:
objectMapper.getSerializationConfig().setSerializationView(Views.Public.class);
// (note: can also pre-construct config object with 'mapper.copySerializationConfig'; reuse)
objectMapper.writeValue(out, beanInstance); // will use active view set via Config
// or, starting with 1.5, more convenient (ObjectWriter is reusable too)
objectMapper.viewWriter(ViewsPublic.class).writeValue(out, beanInstance);
This information was pulled from http://wiki.fasterxml.com/JacksonJsonViews
with jackson 2.3, I can do this with JAX-RS
public class Resource {
#JsonView(Views.Public.class)
#GET
#Produces(MediaType.APPLICATION_JSON )
public List<Object> getElements() {
...
return someResultList;
}
}
We are working on a multi process projects which use RMI for RPCs.
The problem that we are facing is that the main object which must be passed between processes is very big (when serialized), and this dropped the performance of the code dramatically.
Since, none of the processes change the whole object and only alter small parts of it, we decided to just pass "the modifications" through RMI.
but I found no proper way to implement such concept. The first idea was to keep track of all changes of the main instance. But this seems not easy according to this.
I need a way which we can:
develop fast
performs fast
any suggestion?
Just make this 'main object' a remote object that implements a remote interface, and export it, instead of serializing it backwards and forwards.
I think the best way is to customize your serialization so you will be able to send only the changes. you can do it by implementing private method of
private void writeObject(java.io.ObjectOutputStream stream) and of course also readObject from the other side. well, what you should do in this functions?
I suggest you will manage a bitmap of all the members that were changed and only send them in the serialization, just change the unchanged members to null send the object in serialization and than return there values. in the other side read the bitmap and than you will know how to
First time you need to pass the whole object.
Use PropertyChangeListener on the object, this would generate an PropertyChangeEvent.
You can pass the PropertyChangeEvent around. It has the getSource(), by which you can identify the object. If this is not enough, if you need IOR or any other sort of reference, create a wrapper and sent it across..
-Maddy
Have a look to http://docs.oracle.com/javase/tutorial/uiswing/events/propertychangelistener.html
public class Test {
PropertyChangeSupport pcs = new PropertyChangeSupport(this);
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
String oldName = this.name;
this.name = name;
pcs.firePropertyChange("name", oldName, name);
}
public int getAge() {
return age;
}
public void setAge(int age) {
int oldAge = this.age;
this.age = age;
pcs.firePropertyChange("age", oldAge, age);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
pcs.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
pcs.removePropertyChangeListener(listener);
}
public Test(){
}
public static void main (String[] args){
Test myTestObject = new Test();
myTestObject.addPropertyChangeListener(new MyPropertyChangeListener());
myTestObject.setAge(12);
myTestObject.setName("Rick");
myTestObject.setName("Andrew");
}
private static class MyPropertyChangeListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent event) {
String clazz = event.getSource().getClass().getName();
System.out.println(clazz+"::"+event.getPropertyName()+" changed from "+event.getOldValue()+" to "+event.getNewValue());
}
}
}
This is a simple example but using this approach you can create different PropertyChangeListeners and provide different logic inside theirs method propertyChange.
Also is possible to fire only the changes over a small set of attributes and not over all of them (not storing the oldValue and not firing the firePropertyChange method of PropertyChangeSupport).
Of course that you can use AOP, but perhaps you are looking for a solution like presented above. I hope this helps.