以下测试代码应将某些实体保存到数据库中,但不会发生这种情况:
@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映射器?