Arunava Paul
Arunava Paul

Reputation: 111

Unit Test class not running properly - Mocking Interfaces

I have a simple Controller class like below:-

 @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);
}

}

I have written a Junit class like below:-

 @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);

}

}

It's always going into the Service class and the when statement is not running. Can someone please advise what have I done wrong. Below error comes if I run Junit.

enter image description here

Upvotes: 0

Views: 17

Answers (2)

Benoit
Benoit

Reputation: 5394

You should declare crawlerService like this:

@Mock
private CrawlerServiceInterface crawlerService;

Upvotes: 2

curlyBraces
curlyBraces

Reputation: 1105

The declaration of crawlerService in the test class should be:

@Mock
private CrawlerServiceInterface crawlerService;

Upvotes: 1

Related Questions