单元测试类无法正常运行-模拟接口

时间:2018-10-15 13:26:26

标签: junit mockito

我有一个简单的Controller类,如下所示:-

 @RestController
 public class CrawlerAppController {

private static final Logger LOGGER = LoggerFactory.getLogger(CrawlerAppController.class);

@Autowired
private CrawlerServiceInterface crawlerService;

/* The response time of the crawling operation is directly proportional to the no of pages
 * we want to crawl. Keeping a default value of 10 so we can view the results quicker.
 * author: Arunava Paul
 */
@RequestMapping(value = "/crawl", method = { RequestMethod.GET })
public Object crawlUrl(@RequestParam(value = "URL") String URL,
        @RequestParam(value = "max", defaultValue = "10") int maxPages) throws Exception {


    if(!URL.startsWith("https://"))
        URL="https://"+URL;

    LOGGER.info("Request Received. Domain "+URL+" Pages to be Crawled "+maxPages);

    return crawlerService.crawlService(URL, maxPages);
}

}

我写了一个Junit类,如下所示:-

 @RunWith(PowerMockRunner.class)
 public class CrawlerAppControllerTest {

Object obj=new Object();

@Spy
@InjectMocks
private CrawlerServiceInterface crawlerService = Mockito.any(CrawlerService.class);

@InjectMocks
CrawlerAppController appController = new CrawlerAppController();

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
}


@Test
public void testController() throws Exception {

    when(crawlerService.crawlService("https://vogella.com", 20)).thenReturn(obj);

    assertEquals(appController.crawlUrl("vogella.com",20), obj);

}

}

它总是进入Service类,而when语句未运行。 有人可以告诉我我做错了什么吗?如果我运行Junit,则会出现以下错误。

enter image description here

2 个答案:

答案 0 :(得分:2)

您应该像这样声明crawlerService:

@Mock
private CrawlerServiceInterface crawlerService;

答案 1 :(得分:1)

测试类中的crawlerService声明应为:

@Mock
private CrawlerServiceInterface crawlerService;