Как выполнить автоматическое подключение службы с помощью тестов JUnit

Как автоматически подключить Сервис в тестовом классе, используя только аннотации Spring

при попытке я получил эту ошибку ниже, тогда как аннотация @Service, используемая в классе UserServiceImp

2014-12-20 15:35:52 ОШИБКА TestContextManager: 334 - Обнаружено исключение при разрешении TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@5af97850] для подготовки экземпляра теста [com.amsb.bariz.base.test. UserTest @ 4520ebad] org.springframework.beans.factory.BeanCreationException: ошибка создания bean-компонента с именем com.amsb.bariz.base.test.UserTest: не удалось ввести автоматически подключенные зависимости; вложенное исключение - org.springframework.beans.factory.BeanCreationException: не удалось автоматизировать поле: общедоступный com.amsb.bariz.base.service.UserService com.amsb.bariz.base.test.UserTest.userService; вложенное исключение - org.springframework.beans.factory.NoSuchBeanDefinitionException: не найдено подходящего bean-компонента типа [com.amsb.bariz.base.service.UserService] для зависимости: ожидается как минимум 1 bean-компонент, который квалифицируется как кандидат autowire для этой зависимости. Аннотации зависимостей: {@ org.springframework.beans.factory.annotation.Autowired (required = true)}

мой класс обслуживания

package com.amsb.bariz.base.service.imp;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.amsb.bariz.base.dao.UserDao;
import com.amsb.bariz.base.dao.UserRoleDao;
import com.amsb.bariz.base.entity.User;
import com.amsb.bariz.base.entity.UserRole;
import com.amsb.bariz.base.service.UserService;


@Service("userService")
public class UserServiceImp implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserRoleDao userRoleDao;

    public void register(User user) {

        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

        user.setPassword(passwordEncoder.encode(user.getPassword()));
        Calendar calendar = Calendar.getInstance();
        java.util.Date now = calendar.getTime();

        Date dateNow = new Date(20070266);
        Timestamp dn = new Timestamp(now.getTime());
        user.setStatus("P");
        user.setCreated_on(dn);
        user.setEnabled(false);

        UserRole ur = new UserRole(user,"USER_ROLE");


        System.out.println("XDXDX ::" + user.toString());
        userDao.create(user);
        userRoleDao.create(ur);

    }

}

мой тестовый класс:

package com.amsb.bariz.base.test;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;

import com.amsb.bariz.base.dao.UserDao;
import com.amsb.bariz.base.entity.User;
import com.amsb.bariz.base.entity.UserRole;
import com.amsb.bariz.base.service.UserService;
import com.github.springtestdbunit.DbUnitTestExecutionListener;

import junit.framework.TestCase;
import junit.framework.TestSuite;


@Configuration
@ComponentScan(basePackages={"com.amsb.bariz.base.service"})
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/spring-main.xml"})
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class,
        DirtiesContextTestExecutionListener.class,
        TransactionalTestExecutionListener.class,
        DbUnitTestExecutionListener.class})
public class UserTest {


    @Autowired
    public UserService userService;



    @Test
    public void userAdd() {
        User user = new User();

        Calendar calendar = Calendar.getInstance();
        java.util.Date now = calendar.getTime();
        Timestamp doo = new Timestamp(now.getTime());



        Date a = new Date(0);


        user.setPassword("oman");
        user.setName("oman new ");
        user.setStatus("N");
        user.setCreated_on(doo);
        user.setUpdated_on(doo);
        user.setDob(new Date(20140522));
        user.setUsername("[email protected]");


        userService.register(user);
    }



}

person Ahmed Al-battashi    schedule 20.12.2014    source источник


Ответы (1)


Вы пытаетесь использовать сам тест как часть конфигурации Spring? Это не сработает. Что вам нужно сделать, это: - удалить аннотации @Configuration и @ComponentScan из самого теста - создать простой класс TestConfiguration:

@Configuration
@ComponentScan(basePackages={"com.amsb.bariz.base.service"})
@ImportResource("classpath:spring/spring-main.xml")
public class TestConfiguration{ }

И просто укажите это в своем тесте:

@ContextConfiguration(classes = { TestConfiguration.class }, loader = AnnotationConfigContextLoader.class)
public class UserTest {

И у вас должно получиться нормально внедрить свой сервис.

Надеюсь, это поможет.

person Eugen    schedule 20.12.2014