orien / bean-matchers Goto Github PK
View Code? Open in Web Editor NEWHamcrest matchers for testing Java beans
License: BSD 3-Clause "New" or "Revised" License
Hamcrest matchers for testing Java beans
License: BSD 3-Clause "New" or "Revised" License
Some properties can never be null and null checks are ignored in the equals method. But hasValidBeanEquals()
doesn't take that into account because it needs the Bean.class
as argument instead of a concrete object with these properties set. It therefore triggers a NullPointerException for those properties.
These properties could be excluded but that makes the test incomplete and is therefore not a recommended approach.
When you are referring to mutable classes in a bean, a good practice is to clone the value passed and returned in your getters and setters. The most easy to understand example is when dealing with the old "java.util.Date" class.
Actually, this highly used pattern is not supported by the library, as it fails with a message like this:
java.lang.AssertionError:
Expected: bean with valid setter and getter methods for all properties
but: bean of type "com.xxx.MyBean" had an invalid getter/setter for the property "timestampFinished"
I think I can post a unit test showing this problem if needed. For the fix, I'd prefer to get some feedback before going ahead
Hi, I was testing your library and found this weird behavior:
I have an Entity class User with this method:
@Transient
public String getFullName() {
return StringUtils.joinWith(StringUtils.SPACE, getFirstName(), getLastName());
}
and this matchers
allOf(
hasValidBeanConstructor(),
hasValidGettersAndSetters(),
hasValidBeanToString()
and even using the hasValidGettersAndSettersExcluding("fullName")
I´m getting this error:
com.google.code.beanmatchers.AccessorMissingException: missing setter for the property fullName
.
I tried to use the inverse method hasValidGettersAndSettersFor(includedFields)
, but I'm still getting the same error.
Hi,
the hasValidBeanToString() fails on a field named aStr (it seems it looks for AStr instead).
Java version: 1.8.0_112, vendor: Oracle Corporation
BeanMatchers: 0.10
Message is
java.lang.AssertionError:
Expected: (bean class with a valid no-args constructor and bean with valid setter and getter methods for all properties and bean with all properties influencing hashCode and bean with all properties compared in equals and bean with toString() describing class name and all properties)
but: bean with toString() describing class name and all properties bean of type "it.gualtierotesta.testsolutions.general.beans.LombokBean" had an invalid toString() method. It did not produce the property name "AStr", actual output "LombokBean(aStr=69cea64a-a26b-479c-87ca-f1626677bf54, anInt=0)"
Class code:
@Data
public class LombokBean implements Serializable {
String aStr;
int anInt;
}
Test class code:
@Test
public void testClassIsGoodBean() {
assertThat(LombokBean.class, allOf(
hasValidBeanConstructor(),
hasValidGettersAndSetters(),
hasValidBeanHashCode(),
hasValidBeanEquals(),
hasValidBeanToString() // Error is here !
));
}
Complete project can be found at https://github.com/gualtierotesta/test-solutions module general class LombokBean.
Note: I know there is no meaning to test Lombok generated toString() method but may be the problem will raise also on non Lombok generated toString methods.
Hi,
It comes out there is an issue if you are using Lombok annotation @Accessors(chain = true)
.
Tests couldn't pass and give the following error:
bean with valid setter and getter methods for all properties bean of type "..." had an invalid getter/setter for the property "..."
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class KeyValue {
private String key;
private String value;
}
If remove it - then everything works just fine.
But I hope there is possibility to add some extra options or settings, so it could also work with this annotation.
Thanks!
simple test itself
import static com.google.code.beanmatchers.BeanMatchers.*;
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.MatcherAssert.assertThat;
class KVTest {
@Test
void testBean() {
assertThat(KeyValue.class, allOf(
hasValidBeanConstructor(),
hasValidGettersAndSetters(),
hasValidBeanHashCode(),
hasValidBeanEquals(),
hasValidBeanToString()
));
}
}
PS.
only one assertion works so far... ((
@Test
void testBean() {
assertThat(KeyValue.class, allOf(
hasValidBeanConstructor()
// hasValidGettersAndSetters(),
// hasValidBeanHashCode(),
// hasValidBeanEquals(),
// hasValidBeanToString()
));
}
these three hasValidBeanHashCode(), hasValidBeanEquals(), hasValidBeanToString()
produce com.google.code.beanmatchers.AccessorMissingException: missing setter for the property key
Hi
very cool library. It would be great if it would support java8 datetime and Optional out of the box as ValueGenerators.
Kind regards,
Michael
`class Foo {
private String field1;
private String field2;
//Given no arg constructor & all setters are present except one setter which has the issue
public void setField1(String value) {
field1=value;
field2=value;
}
}`
If the above class is tested then library fails to identify this issue. Please correct me if I have missed something
Hi,
If a collection is used, eg. Set and in my getter I wrap the collection like
return new HashSet<>(this.set);
Then this produces an exception when assertThatIsProperBean
is called.
The underlying reason is that it uses Mockito to create a mock but later, when it iterates the set it uses set.iterator() which returns null and causes a NullPointerException.
It sounds like you need a ValueGenerator for collections.
This library is great! Great for testing Lombok-generated equals-and-hashcode, for instance. However, in our context we do not care much about actual JavaBeans, for instance many classes do not have a default constructor, instead a constructor for all arguments. Some are even immutable.
Unfortunately, these classes cannot be tested with bean-matchers, even testing for a valid hashcode results in “Bean does not have no-args constructor”. It would be nice to lift that requirement – perhaps by registering default instances or by alternatively using the all-args-constructor for setting the values.
A lot of beans are also Serializable.
Please consider a matcher for checking whether an explicit serialVersionUID has been set.
@Factory
public static Matcher<Class<?>> hasSerialVersionUIDField() {
return new HasSerialVersionUIDFieldMatcher();
}
public final class HasSerialVersionUIDFieldMatcher extends TypeSafeDiagnosingMatcher<Class<?>> {
@Override
protected boolean matchesSafely(Class<?> item, Description mismatchDescription) {
boolean hasExplicitSerialVersionUIDField = hasExplicitSerialVersionUIDField(item);
if (!hasExplicitSerialVersionUIDField) {
mismatchDescription
.appendText("bean of type ")
.appendValue(item.getName())
.appendText(" does not have a serialVersionUID field");
}
return hasExplicitSerialVersionUIDField;
}
@Override
public void describeTo(Description description) {
description.appendText("bean class has a serialVersionUID field");
}
private boolean hasExplicitSerialVersionUIDField(Class<?> item) {
try {
item.getDeclaredField("serialVersionUID");
} catch (NoSuchFieldException ignored) {
return false;
}
return true;
}
}
Hey, I found the following issue with IntelliJ (though it's not really an issue it's more like an inconvenience).
I had a class like this:
public class Test {
private Boolean isTest;
public Boolean getTest() {
return isTest;
}
public void setTest(Boolean test) {
isTest = test;
}
@Override
public String toString() {
return "Test{" +
"isTest=" + isTest +
'}';
}
}
Notice that the getters and setters are named as getTest
and setTest
. This is how they were automatically generated.
When tested like this:
assertThat(Test.class, allOf(
hasValidBeanToString()
));
It fails with an error in which the most important part is It did not produce the property name "test"
I guess that a solution would be naming those methods like getIsTest
and setIsTest
and that's what I'm doing (because I want to keep the name prefixed since it is a DAO to a database table that I can't change), but it reads a little bit weirdly.
So I just wanted to leave this here, so that you might consider adding a special case for boolean fields named with an "is" prefix.
Assuming I have the following DTO
class Foo {
private Map<Integer, String> map = new LinkedHashMap<>();
public Map<Integer, String> getMap() {
return Collections.unmodifiableMap(map);
}
public void setMap(Map<Integer, String> map) {
this.map = map != null ? Collections.unmodifiableMap(map) : Collections.emptyMap();
}
}
The setters store an unmodifiable hash map and the getters return an unmodifiable copy of the map.
The method beanDoesNotHaveValidGetterAndSetterForProperty
in AbstractBeanAccessorMatcher
generates a Mockito Map and calls the setter of the class and then the getter.
The check testValue.equals(result)
always evaluates to false.
migrated from google code issue 3
Trying to use the library with a bean with protected/private setters.
I would like that the library could work at least with protected setters instead of giving an "invalid setter for property" error.
0.9 Win7
Sometimes you do not want to give access to a set method to your class clients but if you are working with beans a set method is still necessary so it would be nice to be able to test it.
We find ourselves implementing a couple of ValueGenerator
s when testing a bean class. This leads to boilerplate code due to anonymous classes which could be avoided by passing a Supplier. Unless this test library needs to work with Java < 1.8, of course.
Status quo:
BeanMatchers.registerValueGenerator(new ValueGenerator<Instant>() {
public Instant generate() {
return Instant.now();
}
}, Instant.class);
Using Supplier:
BeanMatchers.registerValueGenerator(Instant::now, Instant.class)
Change the assertion description returned on fail for assertThat(BeanToTest.class, hasValidGettersAndSettersExcluding("dontTestPropertyWithThisName"))
to list the expected properties, not the already known (and yet provided) excluded properties list.
We use assertions of this kind very often, because of many read-only properties:
assertThat(BeanToTest.class, hasValidGettersAndSettersExcluding("dontTestPropertyWithThisName"))
The current behavior: if assertion matcher fail, it list the the already known (and yet provided) excluded properties list within the fail-description.
This information is redundant and does not really help to exactly point/describe the issue: one or more properties have no valid setters/getters, but which of the remaining at the class under test?
Expected behavior: it should instead list the properties that are found by the "magic" JavaBean (with the excluded properties subtracted). This information would really help test developers to track down to the point.
Given a simple bean that contains a List, hasValidBeanHashCode
and hasValidBeanEquals
reliably fail with com.google.code.beanmatchers.BeanMatchersException: Could not generate two distinct values after 128 attempts of type java.util.List
It would appear to me that ListGenerator
violates the ValueGenerator
interface by not returning random Lists.
This appears to be a regression from 0.11 to 0.12
public class SomeObject
{
private List<Integer> myList;
public List<Integer> getMyList()
{
return myList;
}
public void setMyList(List<Integer> myList)
{
this.myList = myList;
}
@Override
public String toString()
{
return "SomeObject{" +
"myList=" + myList +
'}';
}
@Override
public boolean equals(Object o)
{
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SomeObject that = (SomeObject) o;
return Objects.equals(myList, that.myList);
}
@Override
public int hashCode()
{
return Objects.hash(myList);
}
}
public class SomeObjectTest
{
@Test
public void allPropertiesShouldInfluenceHashCode()
{
assertThat(SomeObject.class, hasValidBeanHashCode());
}
@Test
public void allPropertiesShouldBeComparedDuringEquals()
{
assertThat(SomeObject.class, hasValidBeanEquals());
}
}
migrated from google code issue 1
AbstractBeanHashCodeMatcher.hashCodeIsInfluencedByProperties
does not check 1st property with null value. The test coverage is incomplete.
Create a java bean with at least two object properties. E.g.
package com.acme.dto;
public class Name {
private String firstName;
private String lastName;
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.firstName == null) ? 0 : this.firstName.hashCode());
result = prime * result + ((this.lastName == null) ? 0 : this.lastName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Name other = (Name) obj;
if (this.firstName == null) {
if (other.firstName != null) {
return false;
}
}
else if (!this.firstName.equals(other.firstName)) {
return false;
}
if (this.lastName == null) {
if (other.lastName != null) {
return false;
}
}
else if (!this.lastName.equals(other.lastName)) {
return false;
}
return true;
}
}
In eclipse, using the eclemma test coverage tool (or simply using the debugger in "Name" hashCode): run the following unit test:
@Test
public void testName() {
assertThat(Name.class, hasValidBeanHashCode());
assertThat(Name.class, hasValidGettersAndSetters());
assertThat(Name.class, hasValidBeanEquals());
}
Look at the covered lines and you will notice there is one branch missing coverage for the 1st property of the bean: this is because the value generator checks for two values for all beans but it does not start with a hashcode test without any value which means the case where all fields are null is not tested, hence the missed branch.
Now, add this test:
@Test
public void testNameHashcodeAllNulls() {
Name name = new Name();
int hashCode = name.hashCode();
assertNotEquals(0, hashCode);
}
Run again and the coverage is now 100%
bean-matchers 0.9
Of course, if the first property is a basic type such as an int, the coverage will ok. This is a workaround for some beans. The real issue happens when the bean only has objects like the "Name" example.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.