Question

My application has this structure: there's a RepositoryFacade (that is a Singleton) that uses many other ObjectRepository that are Singleton (UserRepository, etc).

Now I'd like to test it, mocking the [Objetct]Repositiries. To do that I made the [Objetct]Repositiry implements an interface, and then i tried to:

final IUserRepository mockIUserRepository= context.mock(IUserRepository.class);
RepositoryFacade.getInstance().setUserRepository(mockIUserRepository);
final User testUser = new User("username");

// expectations
context.checking(new Expectations() {{
    oneOf (mockIUserRepository).save(testUser);
}});
// execute
RepositoryFacade.getInstance().save(testUser);

And in RepositoryFacade I added:

public IUserRepository userRepository = UserRepository.getInstance();

But if I try to run the test, I obtain:

java.lang.SecurityException: class "org.hamcrest.TypeSafeMatcher"'s signer 
information does not match signer information of other classes in the same 
package

p.s. Originally my RepositoryFacade had not a IUserRepository variable, I used it asking always UserRepository.getInstance().what_i_want(). I introduced it to try to use JMock, so if not needed I'll be glad to remove that bad use of Singleton.

Thanks, Andrea

Was it helpful?

Solution

The error you're getting suggests that you have a classloading issue with the org.hamcrest package rather than any issue with your singletons. See this question for more on this exception and this one for the particular problem with hamcrest and potential solutions.

Check your classpath to make sure you're not including conflicting hamcrest code from multiple jars. If you find hamcrest in multiple jars, this may be corrected by something as simple as changing their order in your classpath.

Junit itself comes in two versions - one may include an old version of hamcrest. Switching to the one not including hamcrest may also fix your problem.

If you can find a way to do it, it would be better in the long run to get rid of the singletons altogether and instead do dependency injection using something like Spring or Guice.

But what you're doing should work, once you deal with the classloading, and it's a reasonable approach to dealing with singletons in a testing context.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top