Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用MVC进行java spring JUnit测试(配置中包括@EnableWebMvc)_Java_Spring_Spring Mvc_Testing_Model View Controller - Fatal编程技术网

使用MVC进行java spring JUnit测试(配置中包括@EnableWebMvc)

使用MVC进行java spring JUnit测试(配置中包括@EnableWebMvc),java,spring,spring-mvc,testing,model-view-controller,Java,Spring,Spring Mvc,Testing,Model View Controller,我在一个示例MVC应用程序中进行了配置。 我试着用Tomcat服务器运行它,它工作得非常好。 现在我想添加一些测试并接收“No ServletContext set”错误消息。使用@EnableWebMvc时,将执行所有EST 现在-它的配置: @Configuration @EnableAspectJAutoProxy @ComponentScan("com.packt.webstore") public class RootApplicationContextConfig { @B

我在一个示例MVC应用程序中进行了配置。 我试着用Tomcat服务器运行它,它工作得非常好。 现在我想添加一些测试并接收“No ServletContext set”错误消息。使用@EnableWebMvc时,将执行所有EST

现在-它的配置:

@Configuration
@EnableAspectJAutoProxy
@ComponentScan("com.packt.webstore")
public class RootApplicationContextConfig {

    @Bean
    public DataSource mysqlDataSource() {

        DriverManagerDataSource dataSource = null;
        try {
            dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName("org.postgresql.Driver");
            dataSource.setUrl("jdbc:postgresql://localhost:5432/springmvctest");
            dataSource.setUsername("postgres");
            dataSource.setPassword("12345");

            if (dataSource.getConnection().isClosed()) throw new Exception("Соединение закрыто");

        } catch (Throwable e) {

            final String msg = "Error" + ": " + EOS + e;    
            throw new RuntimeException(e);

        }

        return dataSource;

    } //END: mysqlDataSource()

    @Bean
    public NamedParameterJdbcTemplate getJdbcTemplate() {
            NamedParameterJdbcTemplate template = null;    
        try {    
            template = new NamedParameterJdbcTemplate(mysqlDataSource());    
        } catch (Exception e) {
            System.err.println("Error" + ": " + EOS + e);
        }

        return template;

    } //END: getJdbcTemplate()

} //END: class RootApplicationContextConfig
@Configuration
@EnableWebMvc
@ComponentScan("com.packt.webstore")
public class WebApplicationContextConfig implements WebMvcConfigurer {

    @Override
    public void configureDefaultServletHandling(
            DefaultServletHandlerConfigurer configurer
    ) {

        configurer.enable();

    } //END: configureDefaultServletHandling()

     @Bean
    public InternalResourceViewResolver getInternalResourceViewResolver() {

        InternalResourceViewResolver resolver = new InternalResourceViewResolver();

        resolver.setViewClass(JstlView.class);
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");

        return resolver;

    } //END: getInternalResourceViewResolver()

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {

        UrlPathHelper urlPathHelper = new UrlPathHelper();    
        urlPathHelper.setRemoveSemicolonContent(false);    
        configurer.setUrlPathHelper(urlPathHelper);

    } //END: configurePathMatch()
Web配置:

@Configuration
@EnableAspectJAutoProxy
@ComponentScan("com.packt.webstore")
public class RootApplicationContextConfig {

    @Bean
    public DataSource mysqlDataSource() {

        DriverManagerDataSource dataSource = null;
        try {
            dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName("org.postgresql.Driver");
            dataSource.setUrl("jdbc:postgresql://localhost:5432/springmvctest");
            dataSource.setUsername("postgres");
            dataSource.setPassword("12345");

            if (dataSource.getConnection().isClosed()) throw new Exception("Соединение закрыто");

        } catch (Throwable e) {

            final String msg = "Error" + ": " + EOS + e;    
            throw new RuntimeException(e);

        }

        return dataSource;

    } //END: mysqlDataSource()

    @Bean
    public NamedParameterJdbcTemplate getJdbcTemplate() {
            NamedParameterJdbcTemplate template = null;    
        try {    
            template = new NamedParameterJdbcTemplate(mysqlDataSource());    
        } catch (Exception e) {
            System.err.println("Error" + ": " + EOS + e);
        }

        return template;

    } //END: getJdbcTemplate()

} //END: class RootApplicationContextConfig
@Configuration
@EnableWebMvc
@ComponentScan("com.packt.webstore")
public class WebApplicationContextConfig implements WebMvcConfigurer {

    @Override
    public void configureDefaultServletHandling(
            DefaultServletHandlerConfigurer configurer
    ) {

        configurer.enable();

    } //END: configureDefaultServletHandling()

     @Bean
    public InternalResourceViewResolver getInternalResourceViewResolver() {

        InternalResourceViewResolver resolver = new InternalResourceViewResolver();

        resolver.setViewClass(JstlView.class);
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");

        return resolver;

    } //END: getInternalResourceViewResolver()

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {

        UrlPathHelper urlPathHelper = new UrlPathHelper();    
        urlPathHelper.setRemoveSemicolonContent(false);    
        configurer.setUrlPathHelper(urlPathHelper);

    } //END: configurePathMatch()
以及测试:

@Test
void ProductTest() throws Exception {

InMemoryProductRepository productRepository = null;
AnnotationConfigApplicationContext context;
context = new AnnotationConfigApplicationContext(RootApplicationContextConfig.class);
productRepository = context.getBean(InMemoryProductRepository.class);
Assertions.assertNotEquals(null, productRepository);
List<Product> list_of_products = productRepository.getAllProducts();
Assertions.assertNotEquals(null, list_of_products);
Assertions.assertNotEquals(0, list_of_products.size());
context.close();

} //END: ProductTest()
@测试
void ProductTest()引发异常{
InMemoryProductRepository productRepository=null;
注释ConfigApplicationContext上下文;
context=newannotationConfigApplicationContext(RootApplicationContextConfig.class);
productRepository=context.getBean(InMemoryProductRepository.class);
assertNotEquals(null,productRepository);
列出产品的列表=productRepository.getAllProducts();
assertNotEquals(null,产品列表);
assertNotEquals(0,产品列表.size());
context.close();
}//结束:ProductTest()
当@EnableWebMvc出现时,我收到的错误消息如下:

-------------------------------------------------------------------------------
Test set: dbtest
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.547 s <<< FAILURE! - in dbtest
dbtest.ProductTest  Time elapsed: 0.515 s  <<< ERROR!
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resourceHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
    at dbtest.ProductTest(dbtest.java:30)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'resourceHandlerMapping' threw exception; nested exception is java.lang.IllegalStateException: No ServletContext set
    at dbtest.ProductTest(dbtest.java:30)
Caused by: java.lang.IllegalStateException: No ServletContext set
    at dbtest.ProductTest(dbtest.java:30)
-------------------------------------------------------------------------------
测试集:dbtest
-------------------------------------------------------------------------------

测试运行:1,失败:0,错误:1,跳过:0,所用时间:0.547 s为什么在新项目中执行此操作而不是使用现代标准的Spring Boot?是的。我学的是没有springboot的spring,别这样。Spring Boot的发明就是为了避免这种情况的发生,它已经成为标准产品好几年了。这些错误通常来自于这样一个事实,即混合了来自不同Spring版本的罐子。检查您的依赖关系。另外,您的
@Configuration
注释类也有缺陷,不要捕获异常,而是让Spring处理它们(否则您的应用程序将处于非法状态),并且您正在数据源方法中泄漏连接(如果您执行
getConnection
您也应该关闭它),而且它也不会测试任何东西,所以请将其删除。