Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何对基本上是对MyBatis映射器接口的1对1调用的服务方法进行单元测试_Java_Unit Testing_Junit_Mockito_Mybatis - Fatal编程技术网

Java 如何对基本上是对MyBatis映射器接口的1对1调用的服务方法进行单元测试

Java 如何对基本上是对MyBatis映射器接口的1对1调用的服务方法进行单元测试,java,unit-testing,junit,mockito,mybatis,Java,Unit Testing,Junit,Mockito,Mybatis,我不熟悉MyBatis和单元测试 我有一个CourseService类,它(目前)只有调用并返回MyBatis映射器的等效方法(CourseMapper)的方法 课程服务类 @Autowired private CourseMapper courseMapper; public Course getById(int id) { return courseMapper.getById(id); } ... CourseMapper接口 @Select("select from cour

我不熟悉MyBatis和单元测试

我有一个
CourseService
类,它(目前)只有调用并返回MyBatis映射器的等效方法(
CourseMapper
)的方法

课程服务类

@Autowired
private CourseMapper courseMapper;

public Course getById(int id) {
    return courseMapper.getById(id);
}
...
CourseMapper接口

@Select("select from courses where id = #{id}")
public Course getById(int id);
...
我是否应该进行单元测试
courseService.getById(id)
?是否适合模拟映射器并使用该映射器构造服务,并对
getById
进行模拟调用,返回一个id作为参数传递的课程

when(courseMapper.getCourseById(anyInt()))
    .thenAnswer(this::returnCourseWithSameIdThatInTheArgument); 
...

private Course CourseWithSameIdThatInTheArgument(InvocationOnMock i) {
    return new Course((int)i.getArguments()[0],true,1,"","",1);
}

提前谢谢。

理想情况下,您应该模拟
CourseMapper
,并验证是否使用预期的
id
调用
CourseMapper.getById(id)

像这样的

Mockito.verify(courseMapper,Mockito.times(1)).getById(id)


这样做的原因是-CourseMapper是一个不同的类,您可以假设它已经过很好的测试。您在这里所做的是删除不需要的
CourseMapper.getById()
的行为。

通常,有关验证的规则:

从模拟中预期某些行为,而不是从存根中。

由于存根也可能记录行为,因此很容易对其进行一些验证

您需要记住,它们的唯一目的是为以后的处理或命令调用(这是被测试类的实际特性)提供数据

查询不会改变世界,因此可以多次调用它们,包括不调用

另一方面,命令调用(在mock上调用)可能会产生副作用,并将改变目标对象之外的世界

您正在尝试测试违反该规则的存根。