@PostMapping("/addCourse") @ResponseBody public AjaxResult addCourse(Course course){ AjaxResult ajaxResult = new AjaxResult(); try { int count = courseService.addCourse(course); if(count > 0){ ajaxResult.setSuccess(true); ajaxResult.setMessage("添加成功"); }else{ ajaxResult.setSuccess(false); ajaxResult.setMessage("添加失败"); } }catch (Exception e){ e.printStackTrace(); ajaxResult.setSuccess(false); ajaxResult.setMessage("添加失败"); } return ajaxResult; } 对他写Junit单元测试
时间: 2023-06-15 08:07:44 浏览: 235
可以使用JUnit和Mockito来编写单元测试。首先,需要在pom.xml文件中添加JUnit和Mockito的依赖:
```
<!-- JUnit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- Mockito -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.9.0</version>
<scope>test</scope>
</dependency>
```
然后,编写单元测试代码:
```
@RunWith(MockitoJUnitRunner.class)
public class CourseControllerTest {
@InjectMocks
private CourseController courseController;
@Mock
private CourseService courseService;
@Test
public void testAddCourse() {
Course course = new Course();
// 设置course的属性
when(courseService.addCourse(course)).thenReturn(1);
AjaxResult ajaxResult = courseController.addCourse(course);
assertTrue(ajaxResult.isSuccess());
assertEquals("添加成功", ajaxResult.getMessage());
}
}
```
在这个测试中,使用Mockito来模拟CourseService的addCourse方法的返回值,然后调用CourseController的addCourse方法,并验证返回的AjaxResult对象的属性是否符合预期。
阅读全文