0

I confess I am a total newbie at the Java way of doing things and I am totally lost trying to get a simple unit test running.

I am building a data access library and want to unit test it. I am using Spring Data Neo4j 4.0.0.BUILD-SNAPSHOT because I need to connect to a remote Neo4j server in the real world.

After battling errors all day I am at the point where I have a test class:

@RunWith(SpringJUnit4ClassRunner.class)
@ComponentScan(basePackages = {"org.mystuff.data"})
@ContextConfiguration(classes={Neo4jTestConfiguration.class})
public class PersonRepositoryTest {
    @Autowired
    PersonRepository personRepository;
    protected GraphDatabaseService graphDb;

    @Before
    public void setUp() throws Exception {
        graphDb = new TestGraphDatabaseFactory().newImpermanentDatabase();
    }

    @After
    public void tearDown() {
        graphDb.shutdown();
    }

    @Test
    public void testCreatePerson() throws Exception {
        assertNotNull(personRepository);
        Person p = new Person("Test", "User");
        personRepository.save(p);
    }
}

Neo4jTestConfiguration.java

@Configuration
@EnableNeo4jRepositories(basePackages = "org.mystuff.data")
@EnableTransactionManagement
public class Neo4jTestConfiguration extends Neo4jConfiguration {
    @Bean
    public SessionFactory getSessionFactory() {
        return new SessionFactory("org.mystuff.data");
    }

    @Bean
    public Neo4jServer neo4jServer() {
        // What to return here? I want in-memory database
        return null;
    }

    @Bean
    @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public Session getSession() throws Exception {
        return super.getSession();
    }
}

When running tests the personRepository.save() throws and exception 'No Scope registered for scope "session"' I don't know if I need the configuration class but my test class won't work without it because Spring needs @ContextConfiguration and I want all the DI niceness Spring provides (amongst other things).

How can I get my tests to work with Spring?

Luanne
  • 19,145
  • 1
  • 39
  • 51
Robin Elvin
  • 1,207
  • 12
  • 28

1 Answers1

3

You can use an InProcessServer which is an in-memory database:

@Bean
public Neo4jServer neo4jServer() {
    return new InProcessServer();
}

Omit the session scope as your test isn't running in a web container. An example: https://github.com/neo4j-examples/sdn4-cineasts/blob/4.0-RC1/src/test/java/org/neo4j/cineasts/PersistenceContext.java

This will require dependencies as described in this question: Spring Data Neo4j 4.0.0.M1 Test Configuration

In your test class PersonRepositoryTest, you don't need to construct an instance of the database, your tests will run against the same InProcessServer. Here's an example: https://github.com/neo4j-examples/sdn4-cineasts/blob/4.0-RC1/src/test/java/org/neo4j/cineasts/domain/DomainTest.java

Community
  • 1
  • 1
Luanne
  • 19,145
  • 1
  • 39
  • 51