账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    spring框架给service层单元测试的时候如何注入真实的mapper对象
    56
    0

    mybatis-plus 的crud接口中提供了这样的方法

    /**
     * <p>
     * 根据 entity 条件,查询全部记录
     * </p>
     *
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     * @return 实体集合
     */
    List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    通过使用wrapper对象,在service层调用的时候就可以更具需要去提供不同的查询条件,比如这样

    List<User> plainUsers3 = userMapper.selectList(new LambdaQueryWrapper<User>()
                    .nested(i -> i.eq(User::getRoleId, 2L).or().eq(User::getRoleId, 3L))
                    .and(i -> i.ge(User::getAge, 20)));

    那这个时候就出现了一个问题,如果这个传入的QueryWrapper对象本身的逻辑有问题的话,使用模拟的mapper对象就没有办法测试出问题。

    在给dao层写测试的时候会在测试类上加上如下注解

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = "classpath*:spring.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: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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
        <!-- Import Properties -->
        <context:property-placeholder location="classpath:config.properties"/>
    
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
              destroy-method="close">
            <property name="url" value="${jdbc.url}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
            <property name="filters" value="stat"/>
            <property name="initialSize" value="1"/>
            <property name="minIdle" value="1"/>
            <property name="maxActive" value="20"/>
            <property name="maxWait" value="60000"/>
            <property name="timeBetweenEvictionRunsMillis" value="60000"/>
            <property name="minEvictableIdleTimeMillis" value="300000"/>
            <property name="testWhileIdle" value="true"/>
            <property name="testOnBorrow" value="false"/>
            <property name="testOnReturn" value="false"/>
            <property name="poolPreparedStatements" value="true"/>
            <property name="maxOpenPreparedStatements" value="20"/>
            <property name="asyncInit" value="true"/>
        </bean>
    
        <bean id="sqlSessionFactory"
              class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="globalConfig" ref="globalConfig"/>
            <property name="mapperLocations" value="classpath*:mybatis/mapper/*.xml"/>
            <property name="configLocation" value="classpath:mybatis-config.xml">
    
            </property>
    
            <property name="plugins">
                <array>
                    <bean class="com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor"/>
                </array>
            </property>
        </bean>
    
        <bean id="globalConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig">
            <property name="dbConfig" ref="dbConfig"/>
        </bean>
    
        <bean id="dbConfig" class="com.baomidou.mybatisplus.core.config.GlobalConfig.DbConfig">
            <property name="idType" value="AUTO"/>
        </bean>
    
        <!-- MyBatis Mapper Scan Config  -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage"
                      value="com.example.demo.mapper"/>
        </bean>
    
    </beans>

    并通过配置文件来注入依赖并运行测试。

    那么,该如何修改这个配置文件才能在运行service层的单元测试的时候给service注入真实的mapper对象?

    0
    打赏
    收藏
    点击回答
        全部回答
    • 共 0 条
    • 赤魂杀戮 普通会员 1楼

      在Spring框架中,Service层的单元测试可以通过以下方式注入真实的Mapper对象:

      1. 使用@Autowired注解:在Service层的某个方法上添加@Autowired注解,这样Spring会自动为这个方法注入所需的Mapper对象。以下是一个简单的例子:

      ```java @Service public class MyService {

      private final MyMapper mapper;
      
      @Autowired
      public MyService(MyMapper mapper) {
          this.mapper = mapper;
      }
      
      // 使用Mapper对象的方法
      public String doSomething(String id) {
          return mapper.doSomething(id);
      }
      

      } ```

      在这个例子中,MyService类中有一个MyMapper接口和一个MyMapper的实现类。在Spring配置文件中,需要将MyMapper接口和实现类的引用注入到MyService类的@Autowired注解中:

      xml <bean id="myService" class="com.example.service.MyService"> <property name="mapper" ref="myMapper"/> </bean>

      在测试类中,我们可以使用@Autowired注解来注入MyMapper对象:

      ```java import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit.jupiter.api.TestContext; import org.springframework.test.context.junit.jupiter.api.TestMethod; import org.springframework.test.context.junit.jupiter.api.extension.ExtendWith; import org.springframework.test.context.junit.jupiter.api.extension.TestContextCustomizer; import org.springframework.test.context.junit.jupiter.api.extension.TestExecutionEnvironment; import org.springframework.test.context.junit.jupiter.api.extension.junit.jupiter.SpringExtension;

      import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock;

      @ExtendWith(SpringExtension.class) @TestContextCustomizer public class MyServiceTest { private MyService myService;

      @Autowired
      public MyService(@Autowired MyMapper mapper) {
          this.myService = mapper;
      }
      
      @Test
      public void testDoSomething() {
          String result = myService.doSomething("123");
          assertEquals("Hello, 123!", result);
      }
      

      } ```

      在这个测试中,我们首先创建了一个MyService对象,并使用@Autowired注解将MyMapper对象注入到MyService对象中。然后,我们使用@Autowired注解来测试doSomething方法,该方法依赖于MyMapper对象。在doSomething方法中,我们使用mapper对象的方法并设置期望的结果,然后通过assertEquals方法来验证方法的返回值是否等于预期的结果。

      注意,如果你使用的是Mockito或其他mockito库,你可能需要在测试方法中使用mock对象代替@Autowired注解的注入。以下是一个使用mockito的例子:

      ```java import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.junit.jupiter.api.extension.TestContextCustomizer; import org.springframework.test.context.junit.jupiter.api.extension.TestExecutionEnvironment; import org.springframework.test.context.junit.jupiter.api.extension.junit.jupiter.SpringExtension;

      import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock;

      public class MyServiceTest { private MyService myService;

      @Autowired
      public MyService(@Autowired MyMapper mapper) {
          this.myService = mapper;
      }
      
      @Test
      public void testDoSomething() {
          MyMock mockMapper = mock(MyMapper.class);
          when(mockMapper.doSomething("123")).thenReturn("Hello, 123!");
          String result = myService.doSomething(mockMapper);
          assertEquals("Hello, 123!", result);
      }
      

      } ```

      在这个测试中,我们首先创建了一个MyService对象,并使用@Autowired注解将MyMapper对象注入到MyService对象中。然后,我们使用@Autowired注解来测试doSomething方法,该方法依赖于MyMapper对象。在doSomething方法中,我们创建了一个MyMock对象,并使用when方法来模拟MyMapper对象的方法。在doSomething方法中,我们设置期望的结果为"Hello, 123!",然后通过assertEquals方法来验证方法的返回值是否等于预期的结果。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部