Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Testing With Our Test Context

Armin Naderi
Armin Naderi
18,713 Points

Integration of @ContextConfiguration test with Mockito.

I am testing a TwitchService that also has access to a UserService as one of its autowired fields. The method shown in the video works when there are no other dependencies on the tested object, but does not seem to work when one exists since the Mockito configuration for the dependant objects can only be set once, within the static class marked with @Configuration. This is since Mockito does not have access to the dependencies within the parent class once they are autowired as beans.

I have worked around this by extracting the UserService to an outer service that has the TwitchService as one of its dependencies, which makes the TwitchService independent and more testable. I understand that this procedure is only needed for cases when the actual functionality of the services in question has to be tested.

Any help would be highly appreciated. Thank you.

1 Answer

Chris Ramacciotti
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Chris Ramacciotti
Treehouse Guest Teacher

Hi Armin - it would be helpful to have the relevant formatted code here for the services, tests, and test context. One approach you can try is by adding a @Bean to the test context:

@Bean
public UserService userService() {
  return new UserServiceImpl();
}

Of course, without seeing your code, I'm not sure how this might fit into the other details of what you already have in place.