Failed to create bean - spring

I tried to run the following test code:
package guru.springframework.test.external.props;
import guru.springframework.test.jms.FakeJmsBroker;
import guru.test.config.external.props.ExternalPropsEnvironment;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.assertEquals;
/**
* Created by jt on 5/7/16.
*/
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = ExternalPropsEnvironment.class)
public class PropertySourceEnvTest {
#Autowired
FakeJmsBroker fakeJmsBroker;
#Test
public void testPropsSet() throws Exception {
assertEquals("10.10.10.123", fakeJmsBroker.getUrl());
assertEquals(3330, fakeJmsBroker.getPort().intValue());
assertEquals("Ron", fakeJmsBroker.getUser());
assertEquals("Burgundy", fakeJmsBroker.getPassword());
}
}
Not sure why I am getting this error:
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: guru.springframework.test.jms.FakeJmsBroker guru.springframework.test.external.props.PropertySourceEnvTest.fakeJmsBroker; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [guru.springframework.test.jms.FakeJmsBroker] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
FakeJmsBroker.java:
package guru.springframework.test.jms;
/**
* Created by jt on 5/7/16.
*/
public class FakeJmsBroker {
private String url;
private Integer port;
private String user;
private String password;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

In this instance, FakeJmsBroker is just a POJO. Unless you either annotate it as #Component, #Service, etc, then Spring knows nothing about it.
You can also return a new instance of this as a #Bean in a #Configuration class. However, looking at this class, unless it's holding properties, it doesn't make sense as a component as it doesn't contain any behavior. Here's an example of making it a bean from a configuration.
#Configuration
public class MyConfig {
// This will create an instance of FakeJmsBroker that will be in the Spring context
#Bean
public FakeJmsBroker createFakeBroker() {
return new FakeJmsBroker();
}
}
Either that class/method, or using the annotation-driven approach will make this bean eligible for autowiring.

Related

No qualifying bean of type 'testgroup.private_clinic.dao.PatientDAO' available in SpringBoot Application

I'm developing crud application, and experiencing difficulties with springboot, which fails on startup. This is what i got:
20764 WARNING [main] --- org.springframework.context.annotation.AnnotationConfigApplicationContext: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'patientServiceImpl': Unsatisfied dependency expressed through method 'setPatientDAO' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'testgroup.private_clinic.dao.PatientDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Screenshot of project structure:
Model:
package testgroup.private_clinic.model;
import javax.persistence.*;
#Entity
#Table(name="Patients")
public class Patient {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
int id;
#Column(name="patient_name")
String name;
#Column(name = "patient_surname")
String surname;
#Column(name = "patient_patronimic")
String patronimic;
#Column(name="adress")
String adress;
#Column(name = "status")
String status;
#Column(name="diagnosis")
String diagnosis;
//+getters and setters
Controller:
package testgroup.private_clinic.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import testgroup.private_clinic.model.Patient;
import testgroup.private_clinic.service.PatientService;
import java.util.List;
#RestController
public class PatientController {
PatientService patientService;
#Autowired
public void setPatientService(PatientService patientService){
this.patientService = patientService;
}
#RequestMapping(method = RequestMethod.GET)
public ModelAndView allPatients(){
List<Patient> patients = patientService.allPatients();
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("patients");
modelAndView.addObject("patientList", patients);
return modelAndView;
}
#RequestMapping(value= "/edit{id}", method = RequestMethod.GET)
public ModelAndView editPage(#PathVariable("id") int id){
Patient patient = patientService.getByID(id);
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("editPage");
modelAndView.addObject("patient", patient);
return modelAndView;
}
#RequestMapping(value="/edit", method = RequestMethod.POST)
public ModelAndView editPatient(#ModelAttribute("patient") Patient patient){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("redirect:/");
patientService.edit(patient);
return modelAndView;
}
}
Repository:
package testgroup.private_clinic.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import testgroup.private_clinic.model.Patient;
import javax.transaction.Transactional;
import java.util.*;
#Repository
public class PatientDAOImpl implements PatientDAO {
SessionFactory sessionFactory;
#Autowired
public void setSessionFactory(SessionFactory sessionFactory){
this.sessionFactory = sessionFactory;
}
#Override
#Transactional
public List<Patient> allPatients() {
Session session = sessionFactory.getCurrentSession();
return session.createQuery("from Patient").list();
}
#Override
#Transactional
public void add(Patient patient) {
Session session = sessionFactory.getCurrentSession();
session.persist(patient);
}
#Override
#Transactional
public void delete(Patient patient) {
Session session = sessionFactory.getCurrentSession();
session.delete(patient);
}
#Override
#Transactional
public void edit(Patient patient) {
Session session = sessionFactory.getCurrentSession();
session.update(patient);
}
#Override
#Transactional
public Patient getByID(int id) {
Session session = sessionFactory.getCurrentSession();
return session.get(Patient.class, id);
}
}
Service:
package testgroup.private_clinic.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import testgroup.private_clinic.model.Patient;
import testgroup.private_clinic.dao.PatientDAO;
import javax.transaction.Transactional;
import java.util.List;
#Service
public class PatientServiceImpl implements PatientService{
PatientDAO patientDAO;
#Autowired
public void setPatientDAO(PatientDAO patientDAO){
this.patientDAO = patientDAO;
}
#Transactional
#Override
public List<Patient> allPatients() {
return patientDAO.allPatients();
}
#Transactional
#Override
public void add(Patient patient) {
patientDAO.add(patient);
}
#Transactional
#Override
public void delete(Patient patient) {
patientDAO.delete(patient);
}
#Transactional
#Override
public void edit(Patient patient) {
patientDAO.edit(patient);
}
#Transactional
#Override
public Patient getByID(int id) {
return patientDAO.getByID(id);
}
}
Main class:
package testgroup.private_clinic.service;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringBootClass {
public static void main(String[] args){
SpringApplication.run(testgroup.private_clinic.service.SpringBootClass.class, args);
}
}
Spring Boot uses classpath component scanning meaning, your entry-point class which is SpringBootClass will scan for all beans within its class path unless you configure it not to.
Looking into your project structure, SpringBootClass is under the testgroup.private_clinic.service package thus Spring Boot will only scan this package for beans and it only found the PatientServiceImpl however, before it injects this to the application context, it will need to inject first its dependency PatientDAO which is not part of the testgroup.private_clinic.service package thus, explains your error.
You have two options to fix this:
Move your SpringBootClass to the base package testgroup.private_clinic - this will make Spring Boot scan on all you components under this package and its sub-packages (e.g., service, dao)
Use #ComponentScan on your SpringBootClass and define there the base package you want to scan for beans.
#ComponentScan(basePackages = "testgroup.private_clinic")
Thanks and cheers!

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type

2020-09-23T15:28:00.3483912Z java.lang.IllegalStateException: Failed to load ApplicationContext
2020-09-23T15:28:00.3489821Z Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'salecChannelEventProcessor' defined in file [/home/runner/work/calculation-service/calculation-service/target/classes/com/demo/calculation/saleschannel/SalecChannelEventProcessor.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'de.demo.json.schema.JsonValidator' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations:
import de.demo.json.schema.JsonValidator;
#Configuration
#ComponentScan( basePackages = {
"com.demo",
"de.demo" },
excludeFilters = {
#ComponentScan.Filter( Configuration.class )
} )
#ImportResource("classpath:/spring-context.xml")
#Import({SwaggerConfig.class, SalesChannelSqsConfig.class})
public class SpringMvcConfig extends WebMvcConfigurationSupport {
#Autowired private ApplicationContext applicationContext;
#Bean( name = "objectMapper" )
public ObjectMapper getObjectMapper( JacksonService jacksonService ) {
return jacksonService.getObjectMapper();
}
#Bean(name = "jsonValidator")
public JsonValidator jsonValidator() {
return new JsonValidator();
}
}
#Component
#Slf4j
#RequiredArgsConstructor
public class SalesChannelUpdateListerner {
#NonNull
private final SalesChannelService salesChannelService;
#NonNull
private final SalecChannelEventProcessor salecChannelEventProcessor;
#SqsListener(value = "${sales.channel.update.queue.name}", deletionPolicy = ON_SUCCESS)
#SneakyThrows
public void receiveSalesChannelUpdateEvent(
#NotificationMessage EnvelopedMessage envelopedMessage) {
log.debug("Received message from sales channel update event queue : {}"
}
#Component
#Slf4j
#RequiredArgsConstructor
public class SalecChannelEventProcessor {
private static final String MESSAGE_TYPE = "sales_channel_update";
#NonNull
private final ObjectMapper objectMapper;
#NonNull
private final JsonValidator jsonValidator;
#SneakyThrows(JsonProcessingException.class)
public boolean isValid(EnvelopedMessage envelopedMessage) {
if (!MESSAGE_TYPE.equals(envelopedMessage.getType())) {
return false;
}
return jsonValidator.validate(envelopedMessage);
}
You need to create the JsonValidator bean. You need to change yor SalecChannelEventProcessor to be:
#Component
#Slf4j
#RequiredArgsConstructor
public class SalecChannelEventProcessor {
private static final String MESSAGE_TYPE = "sales_channel_update";
#NonNull
private final ObjectMapper objectMapper;
#Bean
public JsonValidator jsonValidator(){
return new JsonValidator();
}
#SneakyThrows(JsonProcessingException.class)
public boolean isValid(EnvelopedMessage envelopedMessage) {
if (!MESSAGE_TYPE.equals(envelopedMessage.getType())) {
return false;
}
return jsonValidator().validate(envelopedMessage);
}
}

Vaadin BeanCreationException: during trying to call save method of my service class

Hi I have a little Vaadin project. In there, I've a UserUtils.class which has a createNewUser method which looks like this:
LoginView:
import com.vaadin.flow.component.html.H1;
import com.vaadin.flow.component.login.LoginForm;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.BeforeEnterEvent;
import com.vaadin.flow.router.BeforeEnterObserver;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.util.Collections;
import static com.packagename.utils.UserUtils.createNewUser;
#Route("login")
#PageTitle("Login - packagename")
public class LoginView extends VerticalLayout implements BeforeEnterObserver {
private LoginForm login = new LoginForm();
private PasswordEncoder passwordEncoder;
public LoginView(){
createNewUser("daniel.tran", "cAWFCMaa22", true, "ADMIN");
addClassName("login-view");
setSizeFull();
setAlignItems(Alignment.CENTER);
setJustifyContentMode(JustifyContentMode.CENTER);
login.setAction("login");
add(
new H1("Willkommen!"),
login
);
}
#Override
public void beforeEnter(BeforeEnterEvent event) {
// Inform the user about an authentication error
if (!event.getLocation()
.getQueryParameters()
.getParameters()
.getOrDefault("error", Collections.emptyList())
.isEmpty()) {
login.setError(true);
}
}
}
UserUtils.class:
import com.packagename.backend.entity.UserEntity;
import com.packagename.backend.service.UserService;
import com.packagename.security.SecurityConfiguration;
import com.packagename.ui.views.login.LoginView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
public class UserUtils {
#Autowired
private LoginView loginView;
private static UserService userService;
private PasswordEncoder passwordEncoder;
public static void createNewUser(String pUsername, String pPassword, boolean pStatus, String pRole) {
if (!UserUtils.userExists(pUsername)) {
userService = new UserService();
PasswordEncoder passwordEncoder = SecurityConfiguration.passwordEncoder();
String encodedPassword = passwordEncoder.encode(pPassword);
UserEntity user = new UserEntity();
user.setUserName(pUsername);
user.setPassword(encodedPassword);
user.setStatus(pStatus);
user.setRoles(pRole);
userService.save(user);
}
}
private static boolean userExists(String pUsername) {
userService = new UserService();
UserEntity user = new UserEntity();
user.setUserName(pUsername);
boolean exists = userService.exists(user);
return exists;
}
}
UserService.class:
import com.packagename.backend.entity.UserEntity;
import com.packagename.backend.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
#Service
public class UserService {
private UserRepository userRepository;
private Logger LOGGER;
#Autowired
public UserService(UserRepository pUserRepository) {
this.userRepository = pUserRepository;
}
public UserService() {}
public List<UserEntity> findAll() {
return userRepository.findAll();
}
public long count() {
return userRepository.count();
}
public void delete(UserEntity user) {
userRepository.delete(user);
}
public void save(UserEntity user) {
if (user == null) {
LOGGER.log(Level.SEVERE, "Contact is null. Are you sure you have connected your form to the application?");
return;
}
userRepository.save(user);
}
public boolean exists(UserEntity user) {
Example<UserEntity> example = Example.of(user);
boolean exists = userRepository.exists(example);
return exists;
}
}
UserEntity.class:
import javax.persistence.*;
#Entity
#Table(name = "PSYS_USERS")
public class UserEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int userid;
private String userName;
private String password;
private boolean status;
private String roles;
public UserEntity(){}
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public String getRoles() {
return roles;
}
public void setRoles(String roles) {
this.roles = roles;
}
}
UserRepository.class
import com.packagename.backend.entity.UserEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface UserRepository extends JpaRepository<UserEntity, Integer> {
Optional<UserEntity> findByUserName(String userName);
}
And always when it comes to the situtation, trying to call the userService methods, then it throws the following exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.packagename.ui.views.login.LoginView': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.packagename.ui.views.login.LoginView]: Constructor threw exception; nested exception is java.lang.NullPointerException
I tried to create a default constructor, at the entity and also at the service class but nothing want help.
So far,
Daniel
new UserService(); - this is the problem.
you cannot instantiate spring components on your own, you have to let spring inject/autowire them.
Places where you can inject Spring components are spring components themselves, and with Vaadin, you can inject in your views that have a #Route annotation. LoginView is such a view. So there you inject the UserService, and pass it along to the createNewUser method.
// LoginView constructor
// userService is injected/autowired this way
public LoginView(UserService userService){
createNewUser("daniel.tran", "cAWFCMaa22", true, "ADMIN", userService);
addClassName("login-view");
setSizeFull();
setAlignItems(Alignment.CENTER);
setJustifyContentMode(JustifyContentMode.CENTER);
login.setAction("login");
add(
new H1("Willkommen!"),
login
);
}
// UserUtils
public static void createNewUser(String pUsername, String pPassword, boolean pStatus, String pRole, UserService userService) {
if (!UserUtils.userExists(pUsername, userService)) {
PasswordEncoder passwordEncoder = SecurityConfiguration.passwordEncoder();
String encodedPassword = passwordEncoder.encode(pPassword);
UserEntity user = new UserEntity();
user.setUserName(pUsername);
user.setPassword(encodedPassword);
user.setStatus(pStatus);
user.setRoles(pRole);
userService.save(user);
}
}
private static boolean userExists(String pUsername, UserService userService) {
UserEntity user = new UserEntity();
user.setUserName(pUsername);
boolean exists = userService.exists(user);
return exists;
}
By the way, UserUtils is not a Spring Component so you cant autowire the loginView there either - good thing it's not used anyway

java.lang.IllegalArgumentException: Not a managed type: class while initiating repository bean

Hi I am trying to load some database values at start time of spring boot application. I have autowired service, and in service i have autowired Dao. Below is the error.
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'validationExpressionService': Unsatisfied dependency expressed through field 'validationExpressionDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IValidationExpressionDao': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.ril.nfg.dao.bean.ValidationExpression
I have added #EnitityScan #EnableJPARepository
FYI, Primary key in the case in String, hope that is ok.
Entity
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* The Class ValidationExpression.
*/
package com.ril.nfg.dao.bean;
#Entity
#Table(name = "VALIDATION_EXPRESSION")
public class ValidationExpression implements Serializable {
private static final long serialVersionUID = 9096950800262493651L;
private String validationId;
private String expression;
private String createdBy;
private Date createdOn;
private String description;
private String responseCode;
#Id
#Column(name = "VALIDATION_ID", nullable = false, length = 100)
public String getValidationId() {
return validationId;
}
public void setValidationId(String validationId) {
this.validationId = validationId;
}
#Column(name = "EXPRESSION", nullable = false, length = 200)
public String getExpression() {
return expression;
}
public void setExpression(String expression) {
this.expression = expression;
}
//remaining getters and setters
}
Repository
package com.ril.nfg.dao.repos;
import com.ril.nfg.dao.bean.ValidationExpression;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* The Interface IValidationExpressionDao.
*/
#Repository
public interface IValidationExpressionDao extends JpaRepository<ValidationExpression, String> {
}
Service
import java.util.List;
#Service
public class ValidationExpressionService {
#Autowired
IValidationExpressionDao validationExpressionDao;
public List<ValidationExpression> getAll() {
return validationExpressionDao.findAll();
}
}
Class with #Autwired Service
public class CacheModuleParam implements ApplicationContextAware{
private static List<ValidationExpression> validationExpressionList = null;
#Autowired
ValidationExpressionService validationExpressionService;
#Override
public void setApplicationContext(final ApplicationContext appContext) throws BeansException {
validationExpressionList = validationExpressionService.getAll();
}
}
Application Class
#ComponentScan(basePackages = {"com.ril.nfg"})
#EnableWebMvc
#EnableAutoConfiguration
#SpringBootApplication//(exclude={DataSourceAutoConfiguration.class})
#EnableJpaRepositories(basePackages="com.ril.nfg.dao.repos",entityManagerFactoryRef="oracleEntityManagerFactory")
//#EntityScan(basePackages = "com.ril.nfg.dao.bean")
public class NFGApplication {
public static void main(String[] args) {
SpringApplication.run(NFGApplication.class, args);
}
}
All solutions on internet focuses on #EntityScan. Please help me understand what is wrong with this code. Thanks in advance
Why do you have all this configuration? Simply put our application in the package tree one level above all the other classes and you can go with a class like this:
#SpringBootApplication
public class NFGApplication {
public static void main(String[] args) {
SpringApplication.run(NFGApplication.class, args);
}
}
Packages:
com.ril.nfg <- here you put NFGApplication
And all other classes in subpackages of com.ril.nfg
And then everything will work!

How to create a mocked (by jmockit) spring bean?

I am new to jmockit and would like to mock a bean inside my Java based Spring Application Configuration. I thought (better hoped) it would go like this:
#Configuration
public class MyApplicationConfig {
#Bean // this bean should be a mock
SomeService getSomeService() {
return new MockUp<SomeService>() {#Mock String someMethod() { return ""; }}.getMockInstance();
}
#Bean // some other bean that depends on the mocked service bean
MyApplication getMyApplication(SomeService someService) {
....
}
}
But unfortunatly this fails with "Invalid place to apply a mock-up".
I wonder if I can generate jmockit mocks inside Spring Configuration classes at all. I need the bean because it is referenced by other beans and the whole Spring Context initialization fails if I do not provide the mock as a Spring bean.
Thanks for any help.
Just use your regular Spring configuration. In a test class, declare the type to be mocked with #Capturing. It will mock whatever the implementation class that Spring used.
Edit: added full example code below.
import javax.inject.*;
public final class MyApplication {
private final String name;
#Inject private SomeService someService;
public MyApplication(String name) { this.name = name; }
public String doSomething() {
String something = someService.doSomething();
return name + ' ' + something;
}
}
public final class SomeService {
public String getName() { return null; }
public String doSomething() { throw new RuntimeException(); }
}
import org.springframework.context.annotation.*;
#Configuration
public class MyRealApplicationConfig {
#Bean
SomeService getSomeService() { return new SomeService(); }
#Bean
MyApplication getMyApplication(SomeService someService) {
String someName = someService.getName();
return new MyApplication(someName);
}
}
import javax.inject.*;
import org.junit.*;
import org.junit.runner.*;
import static org.junit.Assert.*;
import mockit.*;
import org.springframework.test.context.*;
import org.springframework.test.context.junit4.*;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = MyRealApplicationConfig.class)
public final class MyApplicationSpringTest {
#Inject MyApplication myApplication;
#Mocked SomeService mockService;
#BeforeClass // runs before Spring configuration
public static void setUpMocksForSpringConfiguration() {
new MockUp<SomeService>() {
#Mock String getName() { return "one"; }
};
}
#Test
public void doSomethingUsingMockedService() {
new Expectations() {{ mockService.doSomething(); result = "two"; }};
String result = myApplication.doSomething();
assertEquals("one two", result);
}
}
import org.junit.*;
import static org.junit.Assert.*;
import mockit.*;
// A simpler version of the test; no Spring.
public final class MyApplicationTest {
#Tested MyApplication myApplication;
#Injectable String name = "one";
#Injectable SomeService mockService;
#Test
public void doSomethingUsingMockedService() {
new Expectations() {{ mockService.doSomething(); result = "two"; }};
String result = myApplication.doSomething();
assertEquals("one two", result);
}
}
Spring-ReInject is designed to replace beans with mocks.

Resources