【发布时间】:2019-11-18 22:14:23
【问题描述】:
我正在尝试独立于 spring 应用程序上下文来测试我的控制器。
这是我的控制器
@RestController
public class AddressesController {
@Autowired
service service;
@GetMapping("/addresses/{id}")
public Address getAddress( @PathVariable Integer id ) {
return service.getAddressById(id);
}
}
我的服务接口
public interface service {
Address getAddressById(Integer id);
}
这是我的测试课
@ExtendWith(SpringExtension.class)
@WebMvcTest
public class AddressControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
service myService;
@Test
public void getAddressTest() throws Exception {
Mockito.doReturn(new Address()).when(myService).getAddressById(1);
mockMvc.perform(MockMvcRequestBuilders.get("/addresses/1"))
.andExpect(status().isOk());
}
}
这是我得到的例外:
org.mockito.exceptions.misusing.NullInsteadOfMockException:参数 传递给 when() 为空!正确的存根示例: doThrow(new RuntimeException()).when(mock).someMethod();另外,如果你使用 @Mock 注解,不要错过 initMocks()
就像从未创建服务一样。我该如何解决这个问题?
我们可以通过使用@RunWith(SpringRunner.class) 代替@ExtendWith(SpringExtension.class) 来解决这个问题。有人可以解释为什么它确实有效吗?通常第一个注释是针对 junit4 的,后面是针对 junit5 的。
【问题讨论】:
-
@MockBean不是 Mockito 注释。改用@Mock -
没有任何变化。
标签: java spring-mvc mockito spring-test-mvc