Polly wants a cracker, I think I should get off her first, I think she wants some water, To put out the blow torch (Polly - Nirvana)
martes, septiembre 19, 2017
Testing code that uses Java System Properties
Etiquetas: java, junit testing java
martes, marzo 19, 2013
Testing Spring Data Neo4j Applications with NoSQLUnit
Spring Data Neo4j
type in graph nodes and relationships which stores the fully qualified classname of that entity.type property at node/relationship level, we also need to create one index for nodes and one index for relationships. In case of nodes, types index name is required, meanwhile rel_types is required for relationships. In both cases we must set key value to className and value to full qualified classname.Type mappingIndexingNodeTypeRepresentationStrategy and IndexingRelationshipTypeRepresentationStrategy are used as default type mapping implementation, but you can also use SubReferenceNodeTypeRepresentationStrategy which stores entity types in a tree in the graph representing the type and interface hierarchy, or you can customize even more by implementing NodeTypeRepresentationStrategy interface. |
Hands on Work
Application
Member class
@NodeEntity public class Member { private static final String COMMANDS = "COMMANDS"; @GraphId Long nodeId; private String name; private Starship assignedStarship; public Member() { super(); } public Member(String name) { this.name = name; } @Fetch @RelatedTo(type=COMMANDS, direction=Direction.OUTGOING) private Set<Member> commands; public void command(Member member) { this.commands.add(member); } public Set<Member> commands() { return this.commands; } public Starship getAssignedStarship() { return assignedStarship; } public String getName() { return name; } public void assignedIn(Starship starship) { this.assignedStarship = starship; } //Equals and Hash methods } |
@NodeEntity public class Starship { private static final String ASSIGNED = "assignedStarship"; @GraphId Long nodeId; private String starship; public Starship() { super(); } public Starship(String starship) { this.starship = starship; } @RelatedTo(type = ASSIGNED, direction=Direction.INCOMING) private Set<Member> crew; public String getStarship() { return starship; } public void setStarship(String starship) { this.starship = starship; } //Equals and Hash methods } |
xml file. Spring Data Neo4j uses Spring Data Commons infrastructure allowing us to create interface based compositions of repositories, providing default implementations for certain operations.MemberRepository class
public interface MemberRepository extends GraphRepository<Member>, RelationshipOperationsRepository<Member> { Member findByName(String name); } |
GrapRepository interface like save, findAll, findById, … we are defining one query method too called findByName. Spring Data Neo4j repositories (and most of Spring Data projects) provide a mechanism to define queries using the known Ruby on Rails approach for defining finder queries.StarshipRepository class
public interface StarshipRepository extends GraphRepository<Starship>, RelationshipOperationsRepository<Starship> { } |
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:neo4j="http://www.springframework.org/schema/data/neo4j" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/data/neo4j http://www.springframework.org/schema/data/neo4j/spring-neo4j.xsd"> <context:component-scan base-package="com.lordofthejars.nosqlunit.springdata.neo4j"/> <context:annotation-config/> <neo4j:repositories base-package="com.lordofthejars.nosqlunit.springdata.repository"/> </beans> |
Testing
Unit Testing
findByName method by seeding Neo4j database.star-trek-TNG-dataset.xml file
<?xml version="1.0" ?> <graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd"> <key id="name" for="node" attr.name="name" attr.type="string"></key> <key id="__type__" for="node" attr.name="__type__" attr.type="string"></key> <key id="starship" for="node" attr.name="starship" attr.type="string"></key> <graph id="G" edgedefault="directed"> <node id="3"> <data key="__type__">com.lordofthejars.nosqlunit.springdata.neo4j.Member</data> <data key="name">Jean-Luc Picard</data> <index name="__types__" key="className">com.lordofthejars.nosqlunit.springdata.neo4j.Member</index> </node> <node id="1"> <data key="__type__">com.lordofthejars.nosqlunit.springdata.neo4j.Member</data> <data key="name">William Riker</data> <index name="__types__" key="className">com.lordofthejars.nosqlunit.springdata.neo4j.Member</index> </node> <node id="4"> <data key="__type__">com.lordofthejars.nosqlunit.springdata.neo4j.Starship</data> <data key="starship">NCC-1701-E</data> <index name="__types__" key="className">com.lordofthejars.nosqlunit.springdata.neo4j.Starship</index> </node> <edge id="11" source="3" target="4" label="assignedStarship"></edge> <edge id="12" source="1" target="4" label="assignedStarship"></edge> <edge id="13" source="3" target="1" label="COMMANDS"></edge> </graph> </graphml> |
type property with full qualified classname and an index with name types, key className and full qualified classname as value.application-context-embedded-neo4j.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:neo4j="http://www.springframework.org/schema/data/neo4j" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/data/neo4j http://www.springframework.org/schema/data/neo4j/spring-neo4j.xsd"> <import resource="classpath:com/lordofthejars/nosqlunit/springdata/neo4j/application-context.xml"/> <neo4j:config storeDirectory="target/config-test"/> </beans> |
WhenInformationAboutAMemberIsRequired
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("application-context-embedded-neo4j.xml") public class WhenInformationAboutAMemberIsRequired { @Autowired private MemberRepository memberRepository; @Autowired private StarshipRepository starshipRepository; @Autowired private ApplicationContext applicationContext; @Rule public Neo4jRule neo4jRule = newNeo4jRule() .defaultSpringGraphDatabaseServiceNeo4j(); @Test @UsingDataSet(locations = "star-trek-TNG-dataset.xml", loadStrategy = LoadStrategyEnum.CLEAN_INSERT) public void information_about_starship_where_serves_and_members_under_his_service_should_be_retrieved() { Member jeanLuc = memberRepository.findByName("Jean-Luc Picard"); assertThat(jeanLuc, is(createMember("Jean-Luc Picard"))); assertThat(jeanLuc.commands(), containsInAnyOrder(createMember("William Riker")));
Starship starship = starshipRepository.findOne(jeanLuc.getAssignedStarship().nodeId);
assertThat(starship, is(createStarship("NCC-1701-E")));
}
private Object createStarship(String starship) {
return new Starship(starship);
}
private static Member createMember(String memberName) {
return new Member(memberName);
}
}
|
-
Recall that we need to use Spring
ApplicationContextobject to retrieve embedded Neo4j instance defined into Spring application context. -
Since lifecycle of database is managed by Spring Data container, there is no need to define any NoSQLUnit lifecycle manager.
Integration Test
SpringRestGraphDatabase class. You need to write tests to validate that your application still works when you integrate your code with a remote server, and this tests are typically known as integration tests.SpringRestGraphDatabase and allow NoSQLUnit to control the lifecycle of Neo4j database..application-context-managed-neo4j.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/data/neo4j
http://www.springframework.org/schema/data/neo4j/spring-neo4j.xsd">
<import resource="classpath:com/lordofthejars/nosqlunit/springdata/neo4j/application-context.xml"/>
<bean id="graphDatabaseService" class="org.springframework.data.neo4j.rest.SpringRestGraphDatabase">
<constructor-arg index="0" value="http://localhost:7474/db/data"></constructor-arg>
</bean>
<neo4j:config graphDatabaseService="graphDatabaseService"/>
</beans>
|
SpringRestGraphDatabase class to connect to localhost server. And let’s implement an integration test which verifies that all starships can be retrieved from Neo4j server.WhenInformationAboutAMemberIsRequired
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("application-context-managed-neo4j.xml") public class WhenInformationAboutStarshipsAreRequired { @ClassRule public static ManagedNeoServer managedNeoServer = newManagedNeo4jServerRule() .neo4jPath( "/Users/alexsotobueno/Applications/neo4j-community-1.7.2") .build(); @Autowired private StarshipRepository starshipRepository; @Autowired private ApplicationContext applicationContext; @Rule public Neo4jRule neo4jRule = newNeo4jRule() .defaultSpringGraphDatabaseServiceNeo4j(); @Test @UsingDataSet(locations = "star-trek-TNG-dataset.xml", loadStrategy = LoadStrategyEnum.CLEAN_INSERT) public void information_about_starship_where_serves_and_members_under_his_service_should_be_retrieved() { EndResult<Starship> allStarship = starshipRepository.findAll(); assertThat(allStarship, containsInAnyOrder(createStarship("NCC-1701-E"))); } private Object createStarship(String starship) { return new Starship(starship); } } |
defaultSpringGraphDatabaseServiceNeo4j method returns a GraphDatabaseService instance defined into application context, in our case it will return the defined SpringRestGraphDatabase instance.Conclusions
type property and create required indexes.Download Code
We keep learning,
Alex.
Gonna rise up, Burning black holes in dark memories, Gonna rise up, Turning mistakes into gold (Rise - Eddie Vedder)
Music: http://www.youtube.com/watch?v=uuVf4xiRsJQ
Etiquetas: continuous integration, integration tests, junit, junit testing java, nosql, nosqlunit, unit testing
miércoles, marzo 06, 2013
NoSQLUnit 0.7.5 Released
- Adding indexes in MongoDB (https://github.com/lordofthejars/nosql-unit#dataset-format)
- Support for Elasticsearch. (https://github.com/lordofthejars/nosql-unit#elasticsearch-engine)
- Fixed issue #53 (https://github.com/lordofthejars/nosql-unit/issues/53) to avoid conflicts with @Inject annotations with Spring Framework and Arquillian by using @ConnectionManager.
- Fixed documentation errors. Thank you so much to Krossnine.
- Added support for testing Spring Data Neo4j applications (https://github.com/lordofthejars/nosql-unit#spring-connection). Full example will be provided soon. Thanks Michael for resolving my questions about Spring Data Neo4j.
- Added support for testing Spring Data MongoDB + Fongo applications (https://github.com/lordofthejars/nosql-unit#configuring-mongodb-connection). Full example will be provided soon.
Alex.
Cuando la pena cae sobre mi, el mundo deja de existir, miro hacia atrás, y busco entre mis recuerdos (Entre Mis Recuerdos - Luz Casal)
Music: http://www.youtube.com/watch?v=zUnOWCURe2M
Etiquetas: acceptance test, elasticsearch, integration tests, junit testing java, nosql, nosqlunit, test automation
lunes, enero 07, 2013
NoSQLUnit 0.7.3 Released
NoSQLUnit is a JUnit extension to make writing unit and integration tests of systems that use NoSQL backend easier. Visit official page for more information.
In 0.7.3 release, next changes has been added:
- Support for Infinispan.
- Adding the possibility to add custom insertion and comparison methods for each engine. Thanks to Bob Tiernay for the idea. https://github.com/lordofthejars/nosql-unit/issues/45
- Adding the possibility to avoid NoSQLUnit injects fields annotated by @Inject by using @ByContainer annotation. Very useful for Spring Framework Tests, Arquillian Tests or Needle Tests.
- Removed JMockMongo as embedded Mongo implementation for Fongo project. Users should not notice any difference from the point of view of NoSQLUnit. Thank to Bob Tiernay for providing this valuable information about Fongo.
- Updated mongo-java-driver to 2.10.1.
- Updated neo4j to 1.8.
- Fixed bug #46 thanks to MrKeyholder for discovering and attaching the solution code.
Fiery mountain beneath the moon, The words unspoken, we'll be there soon, For home a song that echoes on, And all who find us will know the tune. (The Lonely Mountain - Neil Finn)
Etiquetas: infinispan, integration tests, junit, junit testing java, mongodb, neo4j, persistence layer tests
jueves, diciembre 20, 2012
NoSQLUnit 0.7.1 Released
- One new NoSQL system is supported and is CouchDB.
- JUnit version has been upgraded to 4.11. Now using @Inject does not require to pass this reference.
- Business objects do not contain any dependency to JUnit classes. This is the first step to integration to Arquillian Framework.
- Now we can test sharding and master/slave replication of Redis servers.
- Bug fixing.
Como una sonrisa, eres tú, eres tú.
Así, así, eres tú. (Eres Tú - Mocedades)
Etiquetas: couchDB, integration tests, junit testing java, nosql, nosqlunit, persistence layer tests, unit testing
jueves, noviembre 01, 2012
NoSQLUnit 0.6.0 Released
- Embedded: com.lordofthejars.nosqlunit.hbase.EmbeddedHBase
- Managed: com.lordofthejars.nosqlunit.hbase.ManagedHBase
- NoSQLUnit Management: com.lordofthejars.nosqlunit.hbase.HBaseRule
We de ze zu bu, We de sooo a ru, Un va-a pesh a lay, Un vi-I bee (Now We Are Free - Lisa Gerrard)Music: http://www.youtube.com/watch?v=ObGYFInWrU0
Etiquetas: hbase, junit testing java, nosql, nosqlunit, test, unit testing
domingo, octubre 14, 2012
NoSQLUnit 0.5.0 released
@ClassRule
public static EmbeddedRedis embeddedRedis = newEmbeddedRedisRule().build();
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/data/neo4j
http://www.springframework.org/schema/data/neo4j/spring-neo4j-2.0.xsd">
<context:annotation-config/>
<neo4j:config storeDirectory="target/config-test"/>
</beans>
@Autowired
private ApplicationContext applicationContext;
...
@ClassRule
SpringEmbeddedNeo4j springEmbeddedGds = newSpringEmbeddedNeo4jRule().beanFactory(applicationContext).build();
@Rule
public RedisRule redisRule = new RedisRule(newShardedRedisConfiguration()
.shard(host("127.0.0.1"), port(ManagedRedis.DEFAULT_PORT))
.password("a")
.timeout(1000)
.weight(1000)
.shard(host("127.0.0.1"), port(ManagedRedis.DEFAULT_PORT + 1))
.password("b")
.timeout(3000)
.weight(3000)
.build());
And that's all for current version.
Next release 0.6.0 will contain support for HBase. Moreover there are an open poll to vote which engine would you like to see in next releases:
Well, these boots are made for walking, and that's just what they'll do, One of these days these boots are gonna walk all over you. (These Boots Are Made For Walkin' - Nancy Sinatra)Music: http://www.youtube.com/watch?v=SbyAZQ45uww
Etiquetas: Cassandra, embedded in-memory Redis, integration tests, junit, junit testing java, neo4j, nosql, nosqlunit, redis, unit testing
miércoles, septiembre 05, 2012
NoSQLUnit 0.4.1 Released
Yo no soy marinero, Yo no soy marinero, soy capitan, Soy capitan, soy capitan, Bamba, bamba (La Bamba - Ritchie Valens)
- Currently Redis does not support embedded lifecycle. For this reason I am developing an embedded in-memory Redis mock. It is based in Jedis library, and will be released in next version. Issue #22.
- Managed: com.lordofthejars.nosqlunit.redis.ManagedRedis
- NoSQLUnit Management: com.lordofthejars.nosqlunit.redis.RedisRule
Stay in touch with the project and of course I am opened to any ideas that you think that could make NoSQLUnit better.
Music: http://www.youtube.com/watch?v=Jp6j5HJ-Cok
Etiquetas: integration tests, junit, junit testing java, nosql, nosqlunit, redis, unit testing
jueves, julio 26, 2012
Answering with Mockito
Overwhelmed by industry, Searching for a modern day savior from another place, Inclined toward charity (The Answer - Bad Religion)
Now we can write assertions in peace without worrying about returned instance.
Hope you have found this post useful.
We keep learning
Alex.
Music: http://www.youtube.com/watch?v=S2a3q0nIsoM
Etiquetas: answer, junit testing java, mockito, unit testing
martes, junio 19, 2012
NoSQLUnit 0.3.0 Released
Se você me olhar vou querer te pegar, E depois namorar curtição, Que hoje vai rolar... (Balada Boa - Gustavo Lima)
Introduction
NoSQLUnit
- The first one (in case it is possible) it is the in-memory mode. This mode takes care of starting and stopping database system in "in-memory" mode. This mode will be typically used during unit testing execution.
- The second one is the managed mode. This mode is in charge of starting NoSQL server but as remote process (in local machine) and stopping it. This will typically used during integration testing execution.
For this example we are going to use managed approach using ManagedMongoDb Rule) but note that in-memory MongoDb management is also supported (see documentation how).
Next step is configuring Mongodb rule in charge of maintaining MongoDb database into known state by inserting and deleting defined datasets. You must register MongoDbRule JUnit rule class, which requires a configuration parameter with information like host, port or database name.
To make developer's life easier and code more readable, a fluent interface can be used to create these configuration objects.
Let's see the code:
First thing is a simple POJO class that will be used as model class:
And now it is time for testing. In next test we are going to validate that a book is inserted correctly into database.
This Rule will be executed when test is loaded and will start a MongoDb instance. Also will shutdown the server when all tests have been executed.
Next Rule is executed before any test method, and is responsible of maintaining database into known state. Note that we are only configuring working database, in this case the test one.
And finally we annotate method test with @UsingDataSet indicating where to find data to be inserted before execution of each test, and @ShouldMatchDataSet locating expected dataset.
Final Notes
Although NoSQLUnit is at early stages, the part of MongoDb is almost finished, in next releases new features and of course new databases will be supported. Next NoSQL supported engines will be Neo4J, Cassandra, HBase and CouchDb.
Also read the documentation where you will find an full explanation of each feature explained here.
And finally any suggestion you have, any recommendation, or any advice will be welcomed.
Stay In Touch
Email: asotobu at gmail.com
Blog: Lord Of The Jars
Twitter: @alexsotob
Github: NoSQLUnit Github
Keep Learning,
Alex
Full Code
Music: http://www.youtube.com/watch?v=8y5CbeHY7X0
Etiquetas: dbunit, integration tests, junit testing java, mongodb, nosql, nosqlunit, unit testing
jueves, mayo 24, 2012
I'm guided by this birthmark on my skin, I'm guided by the beauty of our weapons, First we take Manhattan, then we take Berlin (First We Take Manhattan - Leonard Cohen)
Presentation abstract was:
Javascript Unit Testing with JS Test Driver
NoSQL Unit Testing with NoSQLUnit
Integration Tests with Arquillian
Acceptance Tests with Thucydides
For any question do not hesitate to write them in comments section or sending me an email.
I would like to say thank you to linuxtag folks for treating me so well and all people who came to presentation, for all of them a big thank you.
Music: http://www.youtube.com/watch?v=JTTC_fD598A&ob=av2e
Etiquetas: arquillian, arquillina, hamcrest, jenkins, js testdriver, junit testing java, maven, mockito, nosqlunit, thucydides
domingo, noviembre 14, 2010
What Colour is God? Why Can't You Tell Me.
Usually one tend to think about testing as a residual part of development. Nothing further from reality. Testing, so JUnit classes, needs to be treated as "business code". Must follow naming conventions, code must be sectioned, and of course must be readable. For this reason, John Ferguson Smart has its own rules that I would like to summarize and comment:
As John Ferguson Smart told in his entries, there are 5 rules that all JUnit classes must follows, that rules are:
I. Don't say "test", say "should".
JUnit test should pass, but "should pass", maybe there is something wrong in classes that makes test fail, for this reason we are writing off tests. Also, test cases must be validated with requirements, because a requirement is specified as should/shall not with test, same nomenclature is used. Thanks of this improvement, it is easy validating requirements using tests.
Also as Neal Ford suggests each word of your test method name must be separated with '_' character. I find this suggestion so useful because you don't need to use your mind for parsing camel case methods. Of course this only applies to JUnit methods (Yes the only exception between delivery classes and test classes). With this small change your test department will be thankful how fast can validate requirements.
For example the method: testTransfer must be changed to transferShouldDeductSumFromSourceAccountBalance as John Smart suggests, but another change is better, and is changing to: transfer_Should_Deduct_Sum_From_Source_Account_Balance and that's more readable.
II. Don't test classes, test their behavior.
Of course because test cases are related to use cases, tests must validate behavior. This also affects on avoiding testing your classes for the only porpouse of reaching 100% of coverage. 100% of coverage is important, but guarantees nothing, if you don't keep in mind that you must test behavior.
III. Test class names are important too.
Of course when you want to locate where some behavior is tested, it helps the name of your test. Class names must answer the question: When is this behavior applicable? as method names should answer the question: What behavior are we testing?.
What you think is better test class name: TransactionTest or WhenMoneyTransactionIsCommited. Both test names are valid but second one is descriptive about what behavior are you testing.
IV. Structure your tests well.
Test classes are also business classes and for that reason they also have the right to be refactored, kept clean and readable. For that reason is so important to write tests consistently. A really good suggestion is divide each test in three main sections, Given-When-Then. Only with tabs and CR can work perfectly, but you can also use frameworks like JBehave or Easyb.
V. Test are deliverables too.
Tests must be treated as commercial code, not because your client does not see test classes, you can ignore them from static analysis.
Etiquetas: John Ferguson Smart, junit, JUnit Kung Fu, junit testing java






