Skip to content
This repository has been archived by the owner on Feb 26, 2021. It is now read-only.

invaluable/mockitobeans

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 

Repository files navigation

Overview

mockitobeans is a supercharged @InjectMocks that will allow you to have all your mocked beans autowire seamlessly by just using Spring's own @Autowire syntax.

History

mockitobeans started when I was looking for a way to use mockito to mock complex objects that had autowired dependencies which had additional autowired dependencies and so on...

Problems

  1. @InjectMocks only injects the dependencies of the class that has been annotated. It does not inject the dependencies of that
  • @Autowire by default sets it's annotation attribute "required" to "true". This is a huge pain especially when you only want to inject 2 out of the 12 dependencies for your tests

Solution

Add mocks as beans

@Configuration
@MockedBeans(mockClasses={PersonDao.class},
 	    spyClasses={PersonService.class},
 	    scope="my-custom-scope")
public class AppConfig {}

Reference mocks as beans

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=AppConfig.class)
public class MyTestCase {
	
	// Since the @MockedBeans adds PersonService as a spring bean
	// we can autowire it here
	@Autowired
	private PersonService personService;
	
	@Autowired
	private PersonDao personDao;
}

Stop default @Autowire require=true behavior

Traditionally, if you try to create a bean with the following:

public class PersonService {
	@Autowired
	private PersonDao personDao;

	@Autowired
	private AddressDao addressDao;
}

you will be forced to declare both personDao and addressDao. To circumvent this, but still retain the autowiring capabilities, you can add DisableAutowireRequireInitializer which will cause the AutowiredAnnotationBeanPostProcessor to not throw an error when a bean is not found for autowiring

@ContextConfiguration(initializers=DisableAutowireRequireInitializer.class)

Now, when you declare you application context and you're missing one of the dependencies, no errors will occur.

@Configuration
// You don't even have to declare ANY of your dependencies at all!
@MockedBeans(mockClasses={PersonService.class})
public class AppConfig {}

Reference

Props to knes1 for this blogpost http://knes1.github.io/blog/2014/2014-08-18-concise-integration-tests-that-contain-mocks-in-spring-framework.html which inspired this project

About

No description or website provided.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Java 100.0%