无法注入模拟对象

时间:2015-04-07 17:49:16

标签: unit-testing junit mockito

我是Mockito和Junit,我已经编写了测试我的休息服务的单元测试用例,并利用Mockito注入模拟。代码如下:

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。请帮我解决这个问题。先感谢您。

1 个答案:

答案 0 :(得分:1)

我认为问题在于你和spring一起使用mockito。两者都使用代理。

查看getBills的代码 - 它不依赖于spring应用程序上下文。因此,请跳过所有弹出设置代码(mockMvcwebApplicationContext)并仅使用Mockito。如果尚不可见的代码依赖于ApplicationContext - 模拟应用程序上下文而不是设置真实的。

这个测试将是:

  • 简单
  • 容器独立
  • 更快

如果需要,您可以使用注释initMocks替换RunWith(MockitoJUnitRunner.class)