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

How to use MyBatis mappers in Spring's JUnit tests?

我使用的测试:

下面的测试代码应该将一些实体保存到数据库中,但是,这并没有发生:

@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);
    }

    ...
}

因为是模拟实现,方法调用被拦截在classorg.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 映射器?

您是否尝试通过 doAnswerdoThrow 模拟方法调用,它们应该与 void 方法一起使用。例如:

@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());
}