对于测试,我使用:
以下测试代码应将某些实体保存到数据库中,但是不会发生:
@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映射器?
我将非常感谢您提供的信息。
感谢所有人。
答案 0 :(得分:1)
您尝试通过doAnswer
或doThrow
模拟方法调用,它们应该与 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());
}