【问题标题】:Method when() from Mockito do not work correctly来自 Mockito 的方法 when() 无法正常工作
【发布时间】:2017-10-04 17:37:44
【问题描述】:

我对 mockito 方法有疑问:when(...)。当我测试时:

afterThrowExceptionShouldReturnCorrectHttpStatus()

先跑,再测试:

controllerShouldReturnListOfAnns()

它总是失败,因为它抛出 NotFoundException。当我删除第一个测试或首先运行第二个测试时,一切都是正确的。这看起来像第一个测试中的方法 when() 覆盖方法 when() 形成第二个测试有测试代码和测试配置。

@ActiveProfiles("dev")
@RunWith(SpringRunner.class)
@SpringBootTest
public class AnnTestController {

@Autowired
private AnnounService annSrv;
@Autowired
private AnnounRepo annRepo;
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;

@Before
public void contextLoads() {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}


@Test
public void afterThrowExceptionShouldReturnCorrectHttpStatus() throws Exception {
    when(this.annRepo.getAnnounList()).thenThrow(NotFoundAnnounException.class);
    this.mockMvc.perform(get("/ann/list")).andExpect(status().isNotFound());
}


@Test
public void controllerShouldReturnListOfAnns() throws Exception {
    List<Announcement> lst = new ArrayList<>();
    lst.add(new Announcement(1, "test", "test"));
    when(annRepo.getAnnounList()).thenReturn(lst);
  this.mockMvc.perform(get("/ann/list"))
 .andExpect(status().isOk())
 .andExpect(jsonPath("$[0].id", is(1)));
}}

配置:

@Profile("dev")
@Configuration
public class BeanConfig {


@Bean
public CommentsRepo commentsRepo() {
    return mock(CommentsRepo.class);
}}

【问题讨论】:

    标签: spring testing model-view-controller junit mockito


    【解决方案1】:

    你可以试试这样的:

     @After public void reset_mocks() {
        Mockito.reset(this.annRepo);
     }
    

    【讨论】:

    • 这行得通!谢谢!顺便提一句。为什么会出现这个问题?总是添加这个方法(@After)是否正常?
    • Spring 测试的生命周期由 Spring Runner 控制。 Spring runner 不处理 Mockito 生命周期。所以你必须自己管理它
    猜你喜欢
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    • 2021-02-23
    • 2015-04-27
    • 2023-02-06
    • 1970-01-01
    • 2018-11-26
    • 2015-01-28
    相关资源
    最近更新 更多