代码之家  ›  专栏  ›  技术社区  ›  Aleksey Bykov

如何在Spring的JUnit测试中使用MyBatis映射器?

  •  1
  • Aleksey Bykov  · 技术社区  · 8 年前

    • 初中4.12
    • 莫基托1.10.19

    以下测试代码应将某些实体保存到数据库中,但不会发生这种情况:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = {ControllerTestConfig.class})
    public class ControllerTest {
    
        @Autowired
        SomeMapper someMapper;
    
        @Test
        public void shouldCreateSomeEntity() {
            SomeEntity someEntity = new SomeEntity();
            someEntity.setSomeProperty("property");
            ...
    
            someMapper.createSomeEntity(someEntity);
        }
    
        ...
    }   
    

    我使用映射器的模拟实现:

    @Configuration
    public class ControllerTestConfig {
    
        @Bean
        public SomeMapper SomeMapper() {
            return Mockito.mock(SomeMapper.class);
        }
    
        ...
    }
    

    org.mockito.internal.creation.cglib.MethodInterceptorFilter .

    映射器是一个接口:

    public interface SomeMapper {
    
        @Insert("Insert into some_table (id, some_entity_id, type, full_name) values (#{id}, #{someEntityId}, #{type}, #{fullName})")
        @SelectKey(statement="select nextval('seqid_static_data');", keyProperty="id", before=true, resultType=long.class)
        void createSomeEntity(SomeEntity someEntity);
    
        ...
    }
    

    @Bean
    public SomeMapper SomeMapper() {
        return new SomeMapper();
    }
    
    ...
    

    如何在Spring的JUnit测试中使用MyBatis映射器?

    1 回复  |  直到 6 年前
        1
  •  0
  •   borino    8 年前

    您是否尝试通过调用来模拟方法 doAnswer 或 doThrow ,他们应该与 无效 方法。例如:

    @Test
    public void shouldCreateSomeEntity() {
        SomeEntity someEntity = new SomeEntity();
        someEntity.setSomeProperty("property");       
    
        Mockito.doAnswer(invocation -> {
               invocation.getArgument(0).setSomeProperty("changed_property")
            }).when(someMapper).createSomeEntity(Mockito.eq(someEntity));
    
        someMapper.createSomeEntity(someEntity);
        Assert.assertEquals("changed_property", someEntity.getSomeProperty());
    }