Как автоматически связать поле при запуске теста Spring4JUnitRunner? - PullRequest
0 голосов
/ 09 марта 2012

Я использую Spring 3.1.0.RELEASE. У меня проблемы с автоматическим подключением закрытой переменной из класса Spring4JUnitRunner. Мой класс JUnit ...

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "file:src/main/webapp/WEB-INF/dispatcher-servlet.xml" })
public class RegistrationControllerTest {

@Autowired
private ApplicationContext applicationContext;

private MockHttpServletRequest request;
private MockHttpServletResponse response;
private HandlerAdapter handlerAdapter;
private RegistrationController controller;

@Before
public void setUp() {
    request = new MockHttpServletRequest();
    response = new MockHttpServletResponse();
    handlerAdapter = applicationContext.getBean(HandlerAdapter.class);
    // I could get the controller from the context here
    controller = new RegistrationController();
    final RegistrationValidation registrationValidation = new RegistrationValidation();
    controller.setRegistrationValidation(registrationValidation);
}

Не уверен, что это уместно, но вот мой файл dispathcer-servlet.xml ...

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<!-- Enable annotation driven controllers, validation etc... -->
<mvc:annotation-driven />

<context:component-scan base-package="com.myco.eventmaven" />

<bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/WEB-INF/views/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

<bean id="messageSource"
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="/messages" />
</bean>

</beans>

Вот мой контроллер. Поле «usersDao» во время теста имеет значение null, вызывая NullPointerExceptions (работает нормально, когда я запускаю его как обычный веб-приложение в JBoss) ...

@Controller
@RequestMapping("/registrationform.jsp")
public class RegistrationController {

private static Logger LOG = Logger.getLogger(RegistrationController.class);

@Autowired
private RegistrationValidation registrationValidation;

@Autowired
private UsersDao usersDao;

public void setRegistrationValidation(
        RegistrationValidation registrationValidation) {
    this.registrationValidation = registrationValidation;
}

// Display the form on the get request
@RequestMapping(method = RequestMethod.GET)
public String showRegistration(Map model) {
    LOG.debug("called GET method.");
    final Registration registration = new Registration();
    model.put("registration", registration);
    return "user/registrationform";
}

// Process the form.
@RequestMapping(method = RequestMethod.POST)
public String processRegistration(Registration registration, BindingResult result) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    String nextPage = "user/registrationform";

    // set custom Validation by user
    registrationValidation.validate(registration, result);
    if (result.hasErrors()) {
        return nextPage;
    } else {
        // Save the user to the database.
        if (usersDao.saveUser(registration)) { 
            nextPage = "user/registrationsuccess";
        }   // if
    } // if
    return nextPage;
}

Класс поля-члена usersDao аннотируется аннотацией @Component ...

@Component("usersDao")
public class UsersDaoImpl implements UsersDao {

Какую дополнительную конфигурацию мне нужно добавить для правильного автоматического подключения объекта dao в моем классе JUnit? Спасибо, -

1 Ответ

4 голосов
/ 09 марта 2012

Вы получаете ноль, потому что вы сами создаете RegistrationController, а не получаете боб из Spring. Вы сами это почти поняли:

// I could get the controller from the context here
controller = new RegistrationController();

Ты мог бы и должен. Удалите эти две строки и используйте следующее для обозначения поля:

@Autowired 
private RegistrationController controller;
...