JavaMockito无法模拟方法的结果

sg2wtvxw  于 2021-07-22  发布在  Java
关注(0)|答案(2)|浏览(335)

我在测试(模拟方法的值)我的delete方法from controller时遇到问题。在普通模式下,它工作正常,但不是当我测试。
这是我的密码。
我的控制器

@RestController
@RequestMapping("/")
public class MainController {

    @DeleteMapping(value = "/deletePost/{id}")
public ResponseEntity<String> deletePost(@PathVariable int id) throws SQLException {
    boolean isRemoved = postsService.deletePost(connection, id);

    if (!isRemoved)
        return new ResponseEntity<>("Post with given id was not found", HttpStatus.NOT_FOUND);
    else {
        modifiedPostsService.insertModificationData(connection, new ModificationData(id, "deletion"));
        return new ResponseEntity<>("Post with given id has been deleted.", HttpStatus.OK);
    }
}
}

我的售后服务

public boolean deletePost(Connection connection, int id) throws SQLException {
    return postsDao.deletePost(connection, id);
}

我的邮政信箱

@Override
public boolean deletePost(Connection connection, int id) throws SQLException {
    boolean isPostExists = isPostExist(connection, id);
    PreparedStatement ps;
    ps = connection.prepareStatement("delete from POSTS where ID = " + id);
    ps.executeUpdate();
    return isPostExists;
}

最后是我的测试

@WebMvcTest(MainController.class)
class MainControllerTests {

@Autowired
private MockMvc mockMvc;

@MockBean
private Connection connection;

@MockBean
private PostsService mockPostsService;

@Test
void testIfDeletePostUrlIsOk() throws Exception {
    Mockito.when(mockPostsService.deletePost(connection, 1)).thenReturn(true);
    mockMvc.perform(MockMvcRequestBuilders
            .delete("/deletePost/1")
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk());
}

} testIfDeletePostUrlIsOk() 返回404而不是200(我猜模拟值-true不起作用,而是false)。为什么以及如何解决这个问题?

agyaoht7

agyaoht71#

使用时:

Mockito.mock(...)

如果要在本地作用域上创建模拟对象,则必须将其注入sut或使用:

@MockBean

mockbean将使您的对象可以被spring的applicationcontext访问,这样spring就可以选择您的mock。

6ju8rftf

6ju8rftf2#

@SpringBootTest
@AutoConfigureMockMvc
public class TestingWebApplicationTest {

 @Autowired
 private MockMvc mockMvc;

 @MockBean     
 Connection mockConnection;

 @MockBean
 PostsService mockPostsService;

 @Test
 void testIfDeletePostUrlIsOk() throws Exception {
 Mockito.when(mockPostsService.deletePost(any(), anyInt())).thenReturn(true);
 mockMvc.perform(MockMvcRequestBuilders
        .delete("/deletePost/1")
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk());
 }
}

您需要将mock注入控制器,注解@springboottest和@mockbean将完成这项工作

相关问题