我是Mockito和Junit的新手,我编写了用于测试我的rest服务的单元测试用例,并使用Mockito注入mock。代码如下:
BillControllerTest.java:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public class BillControllerTest{
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@InjectMocks
private BillController billController;
@Mock
private BillService mockBillService;
@Before
public void setupController() {
MockitoAnnotations.initMocks(this);
this.mockMvc = webAppContextSetup(webApplicationContext).build();
}
@Test
public void testBills() throws Exception {
// some fake data
final List<Bill> fakeBillList = new ArrayList<>();
fakeBillList.add(CpsFake.bill("1234"));
when(mockBillService.getBills(BILL_UID))
.thenReturn(fakeBillList.stream());
mockMvc.perform(get("/bills/" + BILL_UID ))
.andExpect(content().contentType(MediaTypes.HAL_JSON))
// expect particular uid
.andExpect(content().string(containsString(""uid":"1234"")))
ApplicationTest.java:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public class ApplicationTest {
@Test
public void contextLoads() {
}
}
BillController.java:
@RestController
@RequestMapping(value = "/trials/{billUid}", produces = "application/hal+json")
public class BillController extends BaseController {
@Autowired
private BillService billService;
@Autowired
public BillController(BillService billService) {
this.billService = billService;
}
@RequestMapping(method = RequestMethod.GET, value = "")
public ResponseEntity<Resources<Resource<Bill>>> getBills(@PathVariable String billUid) {
return resourceListResponseEntity(
() -> billService.getBills(billUid),
bill-> createResource(bill),
resources -> resources.add(linkTo(methodOn(BillController.class)
.getBills(billUid)).withSelfRel()));
}
当我运行测试(BillControllerTest)时,mockBillService没有被调用,而是调用实际的billService。请帮我解决这个问题。提前谢谢。
我认为问题在于将mockito与spring一起使用。两者都使用代理。
看看getBills
的代码,它不依赖于spring应用程序上下文。因此,跳过所有春季设置代码(mockMvc
和webApplicationContext
),只使用Mockito。如果仍然不可见的代码依赖于ApplicationContext——模拟应用程序上下文,而不是设置一个真实的应用程序上下文。
该测试将是:
- 更简单
- 独立于容器
- 更快
如果需要,可以将initMocks
替换为Annotation RunWith(MockitoJUnitRunner.class)
。