Mockito junit testing not working- beans mocked by #mockBean are null - unit-testing

I am trying Mockito for mocking and unit testing.
Trying to mock an autowired bean using #MockBean. But the bean is null at run time.
Class under test.
#Service
public class UserServiceImpl {
#Autowired
GenericRestClient restClient;
#Autowired
RequestMapper requestMapper;
#Autowired
ResponseMapper responseMapper;
#Override
public List<User> findUsers(RRequest requestBody,
String index) throws HostException {
List<User> users=
requestMapper.mapRequest("test");
// ...doing something
return users;
}
The test class :
import static org.junit.Assert.assertNotNull;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.boot.test.mock.mockito.MockBean;
#RunWith(MockitoJUnitRunner.class)
public class UserServiceImplTest {
#MockBean
GenericRestClient restClient;
#MockBean
RequestMapper requestMapper;
#MockBean
ResponseMapper responseMapper;
#InjectMocks
UserServiceImpl userService;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
#Test
public void testFindUsers() {
List<Users> users = null;
Mockito.when(requestMapper.mapRequest("test"))
.thenReturn(users);
assertNull(users);
}
}
Error :
java.lang.NullPointerException
at test.my.code.UserServiceImplTest.testFindUsers(UserServiceImplTest.java:10)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
I have debugged, NullPointerException is because of requestMapper (mocked using MockBean as it is null.)
What is wrong with this code?

Unlike #abinmichael I don't suggest using Spring Runner to run this test. Your test is a unit test, and running Spring (creating an application context) is a very expensive operation, more suitable for integration testing.
I'm not a mockito expert, but I believe, you should refactor slightly the UserServiceImpl so that the dependencies will become visible:
#Service
public class UserServiceImpl {
private final GenericRestClient restClient;
private final RequestMapper requestMapper;
private final ResponseMapper responseMapper;
#Autowired // in recent spring version, this annotation can be omitted
public UserServiceImpl(GenericRestClient restClient, RequestMapper requestMapper, ResponseMapper responseMapper) {
this.restClient = restClient;
this.requestMapper = requestMapper;
this.responseMapper = responseMapper;
}
...
With such an approach there is no need in #InjectMocks anymore:
#RunWith(MockitoJUnitRunner.class)
public class UserServiceImplTest {
#Mock
GenericRestClient restClient;
#Mock
RequestMapper requestMapper;
#Mock
ResponseMapper responseMapper;
UserServiceImpl userService;
#Before
public void init() {
userService = new UserServiceImpl(restClient, requestMapper, responseMapper);
}
....
}
If you insist on using fields injection, read The accepted answer to get more information about how does #InjectMocks work. Maybe you don't have "private" access modifier, maybe you have some mix between Constructor injection and field injection and #InjectMocks doesn't not support both simultaneously

I suggest you can try this approach, using #InjectMocks for the test target and use #Mock for injected classes inside that service.
No need to use #Before since you used field injection.
#RunWith(SpringRunner.class)
#SpringBootTest(classes = YourMainClass.class)
public class UserServiceImplTest {
#Mock
GenericRestClient restClient;
#Mock
RequestMapper requestMapper;
#Mock
ResponseMapper responseMapper;
#InjectMocks
UserServiceImpl userService
#Test
public void testFindUsers() {
}
}

Can you try running the test after changing to
#RunWith(SpringRunner.class)
#SpringBootTest
public class UserServiceImplTest {
The javadoc https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/mock/mockito/MockBean.html
states
#Target(value={TYPE,FIELD})
#Retention(value=RUNTIME)
#Documented
#Repeatable(value=MockBeans.class)
public #interface MockBean
Annotation that can be used to add mocks to a Spring ApplicationContext. Can be used as a class level annotation or on fields in either #Configuration classes, or test classes that are #RunWith the SpringRunner.

Related

Unit Testing Service Layer in Spring Boot

I have a service layer (Code Below:)
#Service
public class EquityFeedsService {
#Autowired
private EquityFeedsRedisRepositoryImpl equityFeedsRedisRepositoryImpl;
public void save(EquityFeeds equityFeeds) {
logger.info("Inside the save method of EquityFeedsService.");
equityFeedsRedisRepositoryImpl.save(equityFeeds);
}
// other methods
}
Now I am trying to write a Unit Test case for the above method below:
#ExtendWith(SpringExtension.class)
#AutoConfigureMockMvc
public class EquityFeedsServiceTest {
private MockMvc mockMvc;
#InjectMocks
private EquityFeedsService equityFeedsService;
#Mock
private EquityFeedsRedisRepositoryImpl equityFeedsRedisRepositoryImpl;
#BeforeEach
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(equityFeedsService).build();
}
#Test
public void testSaveMethod() {
EquityFeeds equityFeeds = new EquityFeeds(423,"SAPEXTXN1", "GS");
when(equityFeedsRedisRepositoryImpl.save(any(EquityFeeds.class))).thenReturn(new EquityFeeds());
}
}
This code gives me the below Exception:
in line (any(EquityFeeds.class))
Required type:
EquityFeeds (This is my model class)
Provided:
Matcher <com.investmentbank.equityfeedsprocessingupdated.model.EquityFeeds> (This is the fully qualified path name of the mode class)
no instance(s) of type variable(s) T exist so that Matcher<T> conforms to EquityFeeds
and Exception :
Cannot resolve method 'thenReturn(com.investmentbank.equityfeedsprocessingupdated.model.EquityFeeds)'
What is wrong with my Unit Test Case? How do i solve this?

How to mock JmsTemplate with Mockito?

I try to test a class where i send a jms message but i can't mock the JmsTemplate
JmsProducer.class :
#Component
public class JmsProducer {
#Autowired
private JmsTemplate jmsTemplate;
#Value("${destination}")
private String destination;
public void send(String message){
jmsTemplate.convertAndSend(destination, message);
}
}
JmsProducerTest.Class :
#RunWith(SpringRunner.class)
public class JmsProducerTest {
private static final String DESTINATION= "example";
private static final String MESSAGE= "message";
#InjectMocks
private JmsProducer jmsProducer;
#MockBean
JmsTemplate jmsTemplate;
#Before
public void init(){
ReflectionTestUtils.setField(jmsProducer, "destinationQueue", DESTINATION);
}
#Test
public void testsend(){
jmsProducer.send(MESSAGE);
verify(jmsTemplate,times(1)).convertAndSend(DESTINATION, MESSAGE);
}
}
And when i run this test case it gives me : java.lang.IllegalArgumentException: object is not an instance of declaring class
Have you any idea for this issue ?
If you are using SpringRunner you should add to the init method MockitoAnnotations.initMocks(this);, because #InjectMocks will be work correct with MockitoJUnitRunner.
PS. ReflectionTestUtils.setField(jmsProducer, "destinationQueue", DESTINATION); - but your fields have another name - destination, not destinationQueue
I would also notice that it could not Mock JmsTemplate and ObjectMapper too with jdk 1.8.05 and when i change the JDK to 1.8.74 it works nice.
I referenced to the discussion

JUnit test case: java.lang.NullPointerException

I am trying to write test case for following controller code using JUnit and mockito. But I am getting null pointer Exception. I am new to JUnit testing. can any one please tell what I am doing wrong here?
DepartmentController
#RestController
#RequestMapping("/api.spacestudy.com/SpaceStudy")
public class DepartmentController {
#Autowired
DepartmentService depService;
#CrossOrigin(origins = "http://localhost:4200")
#GetMapping("/LoadDept")
public Department findDeptId() {
return depService.findDeptId();
}
}
DepaermentControllerTest
#WebMvcTest
public class DepartmentControllerTest {
#Autowired
private MockMvc mockMvc;
#Mock
public DepartmentService depService;
#InjectMocks
DepartmentController departmentController;
#Before
public void setup() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(departmentController).build();
}
#Test
public void findDeptIdTest() throws Exception
{
Department department = new Department();
department.setnDeptId(10);
Mockito.when(depService.findDeptId()).thenReturn(department);
mockMvc.perform(get("/api.spacestudy.com/SpaceStudy/LoadDept").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.nDeptId", Matchers.is(10)));
}
}
Test Result
java.lang.NullPointerException
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.detectHandlerMethods(AbstractHandlerMethodMapping.java:227)
at org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping.registerHandlers(StandaloneMockMvcBuilder.java:490)
at org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder.registerMvcSingletons(StandaloneMockMvcBuilder.java:356)
at org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder.initWebAppContext(StandaloneMockMvcBuilder.java:341)
at org.springframework.test.web.servlet.setup.AbstractMockMvcBuilder.build(AbstractMockMvcBuilder.java:139)
at com.spacestudy.DepartmentControllerTest.setup(DepartmentControllerTest.java:38)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
to solve that problem, you have to give an instance of DepartmentController class at standaloneSetup(). I had the same issue while working on some unit testing and after that, my problem disappeared. Try to do it:
#Before
public void setup() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(new DepartmentController()).build();
}

Integration test for authentication filter with Spring Boot

I would like to implement an integration test to test my authentication filter, implemented with Spring Security, with Spring Boot. But... I am lost...
First, here is my "production" implementation:
I have my web configurer adapter creating an authentication manager and declaring my filter:
#EnableWebSecurity
public class SecurityConfigurer extends WebSecurityConfigurerAdapter {
#Autowired
private IdentityService loginService;
#Autowired
private PersonService personService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(loginService).passwordEncoder(new BCryptPasswordEncoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers(PATH_LOGIN).permitAll();
http.authorizeRequests().antMatchers("/**").fullyAuthenticated();
http.addFilterBefore(new AuthenticationFilter(PATH_LOGIN, authenticationManager(), personService),
UsernamePasswordAuthenticationFilter.class);
}
Then, here is my filter implementation:
public class AuthenticationFilter extends AbstractAuthenticationProcessingFilter {
private ObjectMapper objectMapper = new ObjectMapper();
private PersonService personService;
protected AuthenticationFilter(String loginPath, AuthenticationManager authenticationManager,
PersonService personService) {
super(loginPath);
this.personService = personService;
setAuthenticationManager(authenticationManager);
}
#Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException, ServletException {
LoginInfo loginInfo = objectMapper.readValue(request.getInputStream(), LoginInfo.class);
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
loginInfo.getUsername(), loginInfo.getPassword());
Authentication authentication = getAuthenticationManager().authenticate(usernamePasswordAuthenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
return authentication;
}
#Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain,
Authentication authResult) throws IOException, ServletException {
Identity identity = (Identity) authResult.getPrincipal();
Person person = personService.getPersonByMail(identity.getUsername());
UserInfo userInfos = new UserInfo();
userInfos.setUser(person);
userInfos.setRoles(identity.getRoles());
objectMapper.writeValue(response.getWriter(), userInfos);
}
}
Now, I have implemented the two services (PersonService & IdentityService) which should be used as mock to prevent any database access:
#Profile("test")
#Service
public class PersonServiceMock implements PersonService {
private static final Map<String, Person> USER_DB;
static {
Person valerian = new Student();
valerian.setMail("valerian#savetheuniverse.com");
USER_DB = new HashMap<>();
USER_DB.put(valerian.getMail(), valerian);
}
#Override
public Person getPersonByMail(String mail) {
return USER_DB.get(mail);
}
}
-
#Profile("test")
#Service
public class IdentityServiceMock implements IdentityService {
private static final Map<String, Identity> USER_DB;
static {
Identity valerian = new Identity("valerian#savetheuniverse.com");
USER_DB = new HashMap<>();
USER_DB.put(valerian.getUsername(), valerian);
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
USER_DB.forEach((key, value) -> {
value.setEnabled(true);
value.setLocked(false);
value.setPassword(encoder.encode("pa$$w0rd"));
});
}
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserDetails ud = USER_DB.get(username);
return ud;
}
}
In the end, here is my "start of test" I wrote but that does not work because it seems it wants to retrieve the "production" implementation of the service instead of my fake one:
#ActiveProfiles("test")
#RunWith(SpringRunner.class)
#SpringBootTest
#WebAppConfiguration
public class AuthenticationTests {
#Autowired
private Filter filterChainProxy;
#Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
#Before
public void before() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(filterChainProxy).build();
}
#Test
public void login() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
LoginInfo loginInfo = new LoginInfo("valerian#savetheworld.com", "pa$$w0rd");
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/login")
.content(objectMapper.writeValueAsString(loginInfo));
Person person = new Student("valerian", "none", "valerian#savetheworld.com");
UserInfo expectedUserInfo = new UserInfo(person, null);
String expectedJSonContent = objectMapper.writeValueAsString(expectedUserInfo);
mockMvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().json(expectedJSonContent));
}
}
Did I misunderstood something? Can you help me, please?
OK. Never mind. It is just that I misunderstood some notion like mocking, faking & stubbing, even if mocking and stubbing are clearly linked in the unit/integration tests.
I modified my code to remove the different interfaces and the "mock" implementation of the services. This type of implementation is more like a "fake-behaviour" implementation than mocking.
In the end, I have this for my test class:
#RunWith(SpringRunner.class)
#SpringBootTest
#WebAppConfiguration
public class AuthenticationTests {
private static final String KNOWN_USER_MAIL = "valerian#mail.com";
private static final String KNOWN_USER_PASSWORD = "pa$$w0rd";
private static Person KNOWN_STUDENT = new Student("valerian", "none", KNOWN_USER_MAIL);
private static Identity KNWON_IDENTITY = new Identity(KNOWN_USER_MAIL);
static {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
KNWON_IDENTITY.setEnabled(true);
KNWON_IDENTITY.setLocked(false);
KNWON_IDENTITY.setPassword(encoder.encode(KNOWN_USER_PASSWORD));
}
#Autowired
// Attribute name very important
private Filter springSecurityFilterChain;
#Autowired
private WebApplicationContext context;
#MockBean // IdentityService automatically mocked when used
private IdentityService identityService;
#MockBean // PersonService automatically mocked when used
private PersonService personService;
private MockMvc mockMvc;
#Before
public void before() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();
// Stub to define the behaviour of the services when they are used
Mockito.when(identityService.loadUserByUsername(KNOWN_USER_MAIL)).thenReturn(KNWON_IDENTITY);
Mockito.when(personService.getPersonByMail(KNOWN_USER_MAIL)).thenReturn(KNOWN_STUDENT);
}
#Test
public void login_success() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
LoginInfo loginInfo = new LoginInfo(KNOWN_USER_MAIL, KNOWN_USER_PASSWORD);
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/login")
.content(objectMapper.writeValueAsString(loginInfo));
UserInfo expectedUserInfo = new UserInfo(KNOWN_STUDENT, KNWON_IDENTITY.getRoles());
String expectedJSonContent = objectMapper.writeValueAsString(expectedUserInfo);
mockMvc.perform(requestBuilder).andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().json(expectedJSonContent));
}
}
I am impressed by the magic of the annotation #MockBean and the stubs. :)

Getting null response while creating Mock Dao using Mockito

I am trying to create a mock data for Dao class. Test case is running successfully but it is returning null data. I searched and implemented #Mock, #InjectMocks, Inititated MockitoAnnotation but still it is not working. The project is in spring. Context path is also correct. I have not used any other methods. First for running I am trying to just call a method and print. Please help me to solve this error.
RegionManager Class:
#Service("regionManager")
public class RegionManager implements RegionManagerIntf {
#Autowired
RegionDaoIntf regionInquiry;
private RegionDao regionDao;
#Override
public ListPojo retrieveData(String Id, String details, String code) {
return regionInquiry.retrievePData(Id, details, code);
}
public RegionDao getRegionDao() {
return regionDao;
}
public void setRegionDao(RegionDao regionDao) {
this.regionDao = regionDao;
}
}
Dao Class:
#Component
public class RegionProcessorFactory implements RegionProcessorIntf {
private static final Logger logger = Logger
.getLogger(RegionProcessorFactory.class);
#Override
public ListPojo retrieveData(String Id,
String details, String code) {
ListPojo listPojo = new ListPojo();
//Do some action
return listPojo;
}
}
ListPojo:
It contains getter setters.
Test Class:
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.test.context.ContextConfiguration;
import com.fasterxml.jackson.databind.ObjectMapper;
#RunWith(MockitoJUnitRunner.class)
#ContextConfiguration({"classpath*:spring/beanRefContext.xml"})
public class RegionManagerTest
{
private String Id = "12345";
private String Code = "123";
private String details = "12";
ObjectMapper mapper;
#Mock
private RegionProcessorFactory dao;
#Mock
private ListPojo listPojo;
#InjectMocks
private RegionManager service;
/**
* Before method will be called before executing every test case
*/
#Before
public void initialize() {
System.out.println("In initialize");
MockitoAnnotations.initMocks(this);
dao = mock(RegionProcessorFactory.class);
listPojo = mock(ListPojo.class);
service = new RegionManager();
service.setRegionDao(dao);
}
#Test
public void CreateDatabaseMock() throws Exception
{
System.out.println("dao result :: "+dao.retrieveData(Id, "", ""));
when(dao.retrieveData(Id, "", "")).thenReturn(listPojo);
verify(dao).retrieveData(Id, "", "");
}
/**
* After method will be called after executing every test case
*/
#After
public void TearDownClass() {
}
}
First: If you are using #RunWith(MockitoJUnitRunner.class) there is no need for MockitoAnnotations.initMocks(this); more on that here
Second: Everything with #Mock will be mocked and mockito will try to inject it into object annotated with #InjectMocks which mockito will instantiate(in old mockito versions you had to create the object yourself) so following lines are not needed:
dao = mock(RegionProcessorFactory.class);
listPojo = mock(ListPojo.class);
service = new RegionManager();
service.setRegionDao(dao);
Third: The actual execution should come after stubbing
#Test
public void CreateDatabaseMock() throws Exception{
when(dao.retrieveData(Id, "", "")).thenReturn(listPojo);
System.out.println("dao result :: "+dao.retrieveData(Id, "", ""));
verify(dao).retrieveData(Id, "", "");
}