当前位置: 首页 > 知识库问答 >
问题:

如何使用jUnit在使用java配置类且没有XML的Spring mvc中测试DAO实现方法

桑睿识
2023-03-14

我正在使用NetBeans在Spring MVC项目中工作,我创建了一个NetBeans Maven Web项目,并将其配置为具有Java类配置和NO-XML的Spring MVC项目,我正在尝试对插入DAO实现方法进行单元测试,我的自动连线DAO变量始终为空

我一直在关注这个教程http://spring . io/blog/2011/06/21/spring-3-1-m2-testing-with-configuration-classes-and-profiles

这是我的 MvcConfig 类

@Configuration
@ComponentScan("controller")
@EnableWebMvc  
public class MvcConfig extends WebMvcConfigurerAdapter {  




    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
       registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
       configurer.enable();
    }

    //JDBCTEMPLATE
    @Bean
    public DataSource getDataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
        dataSource.setUrl("jdbc:oracle:thin:@127.0.0.1:1521:XE");
        dataSource.setUsername("myPC");
        dataSource.setPassword("fakePassword");

        return dataSource;
    }

    //CREATE DAO BEAN 
    @Bean
    public UserDAO getUserDAO() {
        return new UserDAOImplementation( getDataSource() );
    }
}

这是我的用户DAO

public interface UserDAO{

    public void insertUser(User user);

}

和我的UserDAOImplementation

public class UserDAOImplementation implements UserDAO{

    private JdbcTemplate jdbcTemplate;

    public UserDAOImplementation () {}

    public UserDAOImplementation (DataSource datasource) {
        this.jdbcTemplate  =  new JdbcTemplate(datasource);
    }

    @Override
    public void insertUser(User user) {

        String sql = "INSERT INTO User"
                   + "(field1, field2, field3, field4, field5, field6)"
                   + " VALUES (SEQ_user.nextval, ?, ?, ?, ?, ?)";

        jdbcTemplate.update(html" target="_blank">sql, user.getField1(), 
                                 user.getField2(), 
                                 user.getField3(), 
                                 user.getField4(), 
                                 user.getField5() );
    }
}

这是我的测试类,我评论了“@RunWith(SpringJUnit4ClassRunner.class)”,因为它给了我这个错误

org/junit/runners/model/MultipleFailureException
java.lang.NoClassDefFoundError
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.withAfterClasses(SpringJUnit4ClassRunner.java:187)
    at org.junit.runners.ParentRunner.classBlock(ParentRunner.java:145)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:235)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:162)
    at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
    at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
    at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: java.lang.ClassNotFoundException: org.junit.runners.model.MultipleFailureException
    at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 16 more

这是我的实验班

// this is commented because it gives me errors @RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes=MvcConfig .class, loader=AnnotationConfigContextLoader.class)
public class UserTest{

    User user;

    @Autowired
    private UserDAO userDAO;

@Before
    public void setUp() {
        System.out.println("@Before - setUp");


        user  =  new User();

       user.setField1("a"); 
       user.setField2("a"); 
       user.setField3("a"); 
       user.setField4("a"); 
       user.setField5("a");
    }

 @Test
public void insertUser () {

    userDAO.insertUser(user);
}

自动连线用户DAO变量始终为空

我通过右键单击它并选择run file来运行测试,这是我正在使用的导入

import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;

我正在使用netbean 8.0.2,我的想法是,问题是因为我没有使用这个@Runwith(SpringJUnit4ClassRunner.class)因为它给了我之前提到的错误,但我不知道也许我错过了一些东西,这个插入方法在测试之外工作得很好,我只是想测试它来测试将来的一些新方法,我想学习如何使用java配置测试方法

编辑

我查看了我的文件夹 Test Depencies,在我的软件包 org.junit.runners.model 中没有 MultipleFailureException 我不知道这是否可能是错误

编辑2我将我的jUnit版本从jUnit 4.7更新到jUnit 4.12,并且知道我有这个错误ERROR:未能加载Application ationContext

    Failed to load ApplicationContext
java.lang.IllegalStateException
    at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:91)
    at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:74)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:116)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:82)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:212)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:199)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:251)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:253)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:216)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:82)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:60)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:67)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:162)
    at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
    at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
    at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultServletHandlerMapping' defined in class org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.web.servlet.HandlerMapping org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping()] threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:597)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1095)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:990)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:706)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:125)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
    at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:63)
    at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:83)
    ... 33 more
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.web.servlet.HandlerMapping org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping()] threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:586)
    ... 48 more
Caused by: java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
    at org.springframework.util.Assert.notNull(Assert.java:112)
    at org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer.<init>(DefaultServletHandlerConfigurer.java:54)
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping(WebMvcConfigurationSupport.java:358)
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$ae1586a5.CGLIB$defaultServletHandlerMapping$16(<generated>)
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$ae1586a5$$FastClassBySpringCGLIB$$38361e62.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:311)
    at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$ae1586a5.defaultServletHandlerMapping(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
    ... 49 more

共有1个答案

燕刚捷
2023-03-14

我找到了解决方案,因为我的MvcConfig类有一个@EnableWebMvc注释,如下所示:

@Configuration
@ComponentScan("controller")
@EnableWebMvc  
public class MvcConfig extends WebMvcConfigurerAdapter {  

我需要将此注释添加到我的测试类@WebAppConfiguration并将加载器值从 AnnotationConfigContextLoader 更改为此 AnnotationConfigWebContextLoader,如下所示:

loader=AnnotationConfigWebContextLoader.class

所以最后我修改了我的测试类,如下所示:

@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=MvcConfiguracion.class, loader=AnnotationConfigWebContextLoader.class)
public class UserTest{
 类似资料:
  • 问题内容: 我是第一次使用JUnit进行Java测试。我必须使用Java,并且想使用单元测试。 我的问题是:我有一个带有一些抽象方法的抽象类。但是有些方法不是抽象的。如何使用JUnit测试此类?示例代码(非常简单): 我要测试并运行。 在“JUnit常见问题解答”部分中,我找到了此链接,但我不理解作者想在此示例中说些什么。这行代码是什么意思? 问题答案: 如果您没有该类的具体实现,并且方法不是测试

  • 问题内容: 我已经开始发现Mockito库,并且有一个我没有找到正确答案的问题。 例如,如果我的UserDAO类中有将用户保存到数据库中的此类方法: 我应该如何测试? 如果我想测试一个DAO类,那么我需要创建一个模拟,模拟,模拟等吗?如此不测试数据库本身? 但是,如果我还想测试dao和数据库的行为怎么办? 您能否提供一些代码示例,可能有用的链接,并显示实现此目的的最佳方法? 问题答案: 这是使用M

  • 我已经创建了一个应用程序使用Springboot和Hibernate,我想配置它的单元测试。 首先,这是DAO接口。 这是DAO接口的实现 然后我创建了一个测试类,如下所示 我已经将application.properties文件放在test和src目录的资源中。 我尝试运行此单元测试用例,但由于以下错误而失败: 那么我可以知道为DAO层配置单元测试的最佳方法吗?

  • 下面是一个最小的例子: project/build.scala src/test/scala/helpers.scala 然后,在sbt中,“test”起作用: 但是“it:test”不能编译:

  • 我想问一下你的知识。一个Spring启动应用程序包含各种映射器。这些应该进行测试。要测试映射器,应该读取一个JSON文件。这个JSON文件加载在每个测试文件中。到目前为止,该功能已在每个测试类中实现,我想将功能外包给一个助手类。我尝试如下: 在测试类中,我调用助手如下: 很遗憾,我收到以下错误消息: 组织。springframework。豆。工厂UnsatifiedDependencyExcept

  • DAO类的相关方面如下 我的src/test/resources/application.properties文件如下所示 在Eclipse中作为JUnit测试运行的跟踪 应用程序结构 -SRC ----application.java ----COM ----Hitstpa ----application.properties --测试 ---爪哇