Getting null response while creating Mock Dao using Mockito - unit-testing

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, "", "");
}

Related

“Invalid use of argument matchers” but I use matchers only

I wish to test the following getRights method:
public GetProductRp getRights(String aaId, String bbId, String ccId) {
GetProductRp rp = (GetProductRp) webServiceTemplate.marshalSendAndReceive(createRq(aaId, bbId, ccId));
return rp;
}
private GetProductRq createRq(String aaId, String bbId, String ccId) {
GetProductRq rq = new GetProductRq();
GetProductRqBody body = new GetProductRqBody();
body.setaaId(aaId);
body.setbbId(bbId);
body.setccId(ccId);
rq.setBody(body);
return rq;
}
This is my test class:
#RunWith(SpringRunner.class)
#SpringBootTest()
public class ClassTest {
#Autowired
private Class rightClass;
#MockBean
private WebServiceTemplate webServiceTemplate;
#Test
public void getRightsTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
GetProductRp response = Helper.createProductRp("xx", "yy");
Method mCreateRq = rightClass.class.getDeclaredMethod("createRq", String.class, String.class, String.class);
mCreateRq.setAccessible(true);
GetProductRq request = (GetProductRq) mCreateRq.invoke(rightClass, "12345678", "12345678", "1111");
Mockito.when(webServiceTemplate.marshalSendAndReceive(request)).thenReturn(response);
Mockito.when(rightClass.getRights(Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(response);
Assert.assertNotNull(response);
}
I receive the error provided in the short description above altough I only use Matchers (Mockito.anyString())....
Any idea?
The issue here could be that you are putting #Autowired on private Class rightClass; and you are trying to mock the method of it. If you want to mock the method then you should put #MockBean annotation as :
#MockBean
private Class rightClass;

How can I execute first #After void after() from junit and then #ExpectedDatabase from db-unit?

I want to test a database view and I use db-unit to insert data into tables which are used by tested view and expected values form view is done by db-unit, but this view use some data form another view which I want to mock, I have done some a script which replace view with mock data, after finishing test method mock view is replaced with original view
But I find a problem, #ExpectedDatabase is invoked after #After void after() method, and test fails.
How can I execute first #After void after() from junit and then #ExpectedDatabase from db-unit?
Here is my code:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = ApplicationConfigTest.class)
#TestExecutionListeners({ DependencyInjectionTestExecutionListener. DirtiesContextTestExecutionListener.class })
public class ClassTest {
private static final String MOCK_REOURCE_PATH = "classpath:sql/mock_view.sql";
private static final String ORIGINAL_REOURCE_PATH = "classpath:sql/original_view.sql";
#Autowired
private ApplicationContext applicationContext;
#Before
public void init() {
ScriptUtils.executeSqlScript((DataSource) applicationContext.getBean("dataSource").getConnection(), applicationContext.getReource(MOCK_REOURCE_PATH ));
}
#Test
#DatabaseSetup("classpath:sample-data.xml")
#ExpectedDatabase(assertionMode = NON_STRICT, value = "classpath:expected-data.xml")
public void testView() {
}
#After
public void after() {
ScriptUtils.executeSqlScript((DataSource) applicationContext.getBean("dataSource").getConnection(), applicationContext.getReource(ORIGINAL_REOURCE_PATH ));
}
}
Your declaration for #TestExecutionListeners is broken: it doesn't compile "as is".
Make sure you register the TransactionalTestExecutionListener and the DbUnitTestExecutionListener via #TestExecutionListeners, and annotate your test class with Spring's #Transactional annotation, something similar to the following...
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = ApplicationConfigTest.class)
#TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class,
DbUnitTestExecutionListener.class })
#Transactional
public class ClassTest { /* ... */ }

JUnit Tests for Liferay MVCPortlet using PowerMock

Im trying to make JUnit Test using PowerMock, but I have one problem. Here is my code:
public class MyGreeting extends MVCPortlet {
public static final String GREETING="greeting";
private static final String DEFAULT_GREETING="MY DEFAULT GREETING MESSAGE";
private static final Log _log = LogFactoryUtil.getLog(MyGreeting.class.getName());
#Override
public void render(RenderRequest req,RenderResponse res)
throws IOException, PortletException {
PortletPreferences prefs = req.getPreferences();
req.setAttribute(GREETING, prefs.getValue(GREETING, DEFAULT_GREETING));
super.render(req,res);
}
And I need to make JUnit test. I created another test package, new MyGreetingTest.java file, and come up to this code:
public class MyGreetingTest extends Mockito{
#BeforeClass
public static void setUpBeforeClass() throws Exception {
}
#AfterClass
public static void tearDownAfterClass() throws Exception {
}
private MyGreeting portlet;
#Before
public void setUp() throws Exception {
portlet = new MyGreeting();
}
#After
public void tearDown() throws Exception {
}
#Mock
public RenderRequest request = mock(RenderRequest.class);
#Mock
PortletPreferences preferences = mock(PortletPreferences.class);
#Test
public final void renderTest() throws IOException, PortletException {
when(request.getPreferences()).thenReturn(preferences);
when(preferences.getValue(MyGreeting.GREETING, null)).thenReturn(value);
portlet.render(request, null);
String result = request.getAttribute(MyGreeting.GREETING).toString();
assertEquals(result, value);
}
But I have NullPointerException, because we can't apply getAttribute method to mock-request. Could you please tell me how to solve this problem? How can I test method with getAttribute method using Mockito?
I think you need to mock your method
Stock stock = mock(Stock.class);
when(stock.getPrice()).thenReturn(100.00); // Mock implementation
when(stock.getValue()).thenCallRealMethod(); // Real implementation

Testing Katharsis JsonApi with MockMvc and Mockito

I would like to test the behaviour configured by my Katharsis ResourceRepository (katharsis-spring 2.1.7):
import io.katharsis.queryParams.QueryParams;
import io.katharsis.repository.ResourceRepository;
import org.springframework.stereotype.Component;
#Component
public class UserResourceRepository implements ResourceRepository<UserDTO, String> {
#Autowired
private UserRepository databaseRepository;
#Override
public UserDTO findOne(String email, QueryParams queryParams) {
return null;
}
#Override
public Iterable<UserDTO> findAll(QueryParams queryParams) {
return null;
}
#Override
public Iterable<UserDTO> findAll(Iterable<String> iterable, QueryParams queryParams) {
return null;
}
#Override
public void delete(String email) {
}
#Override
public UserDTO save(UserDTO s) {
return null;
}
}
I would like to test it in a similar way as I do it with normal, Spring Controllers, using Mockito to mock database repository and using MockMvc:
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.Optional;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#RunWith(MockitoJUnitRunner.class)
public class UserJsonApiTest {
#InjectMocks
private UserResourceRepository resourceRepository;
#Mock
private UserRepository databaseRepository;
private MockMvc mockMvc;
#Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(resourceRepository).build();
}
#Test
public void first() throws Exception {
Optional<UserEntity> user = Optional.of(new UserEntity().
id(1).
email("test#test").
firstName("test first name").
lastName("test last name").
pass("test pass"));
when(
databaseRepository.
findOneByEmail(user.get().getEmail())).
thenReturn(user);
mockMvc.perform(
get("/users/" + user.get().email())).
andExpect(status().isOk())
;
}
}
Obviously, this code doesn't work because my Katharsis UserResourceRepository is not really a Controller. So far I have learned (from logs) that it is actually using some filters mappings and class named io.katharsis.spring.KatharsisFilterV2.
Is there any way to use MockMvc for such test? If not - is there any other way I could test it without starting the whole server (with mocking)?
You could use an embedded Server - like UndertowJaxrsServer - and inject the KatharsisFeature:
Create a class (MyApp) which extends Application public static class MyApp extends Application { and deploy it to the embedded server server.deploy(MyApp.class);
in this Class, overwrite getClasses and add a second class (KatharsisFeatureTest) which implements Feature KatharsisFeatureTest implements Feature
in KatharsisFeatureTest you can then register a KatharsisFeature and there you can overwrite JsonServiceLocator and inject the mock.
Sound a little bit complicated, but works like charm :)
Have a look at my implementation.
.
#RunWith(MockitoJUnitRunner.class)
public class EndpointResourceTest {
#Mock
private EndpointService endpointService;
#InjectMocks
private final static EndpointResourceV1 endpointRessource = new EndpointResourceV1();
private static UndertowJaxrsServer server;
#BeforeClass
public static void beforeClass() throws Exception {
server = new UndertowJaxrsServer();
server.deploy(MyApp.class);
server.start();
}
#Test
public void testGetEndpoint() throws URISyntaxException {
Mockito.when(endpointService.getEndpoint("SUBMIT")).thenReturn(new EndpointDTO("SUBMIT", "a", "b"));
Client client = ClientBuilder.newClient();
Response response = client.target(TestPortProvider.generateURL("/api/endpoints/SUBMIT"))
.request(JsonApiMediaType.APPLICATION_JSON_API)
.get();
Assert.assertEquals(200, response.getStatus());
String json = response.readEntity(String.class);
Assert.assertTrue(json.contains("SUBMIT"));
Assert.assertTrue(json.contains("a"));
Assert.assertTrue(json.contains("b"));
Mockito.verify(endpointService, Mockito.times(1)).getEndpoint("SUBMIT");
}
#AfterClass
public static void afterClass() throws Exception {
server.stop();
}
#ApplicationPath("/api")
public static class MyApp extends Application {
#Override
public Set<Class<?>> getClasses() {
HashSet<Class<?>> classes = new HashSet<Class<?>>();
classes.add(KatharsisFeatureTest.class);
return classes;
}
}
public static class KatharsisFeatureTest implements Feature {
#Override
public boolean configure(FeatureContext featureContext) {
featureContext
.property(KatharsisProperties.RESOURCE_SEARCH_PACKAGE, "...")
.register(new io.katharsis.rs.KatharsisFeature(
new ObjectMapper(), new QueryParamsBuilder(new DefaultQueryParamsParser()), new SampleJsonServiceLocator() {
#Override
public <T> T getInstance(Class<T> clazz) {
try {
if (clazz.equals(EndpointResourceV1.class)) {
return (T) endpointRessource;
}
return clazz.newInstance();
}
catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}));
return true;
}
}
}

Can an abstract class be mocked using mockito?

In a class under test, if its constructor takes in an abstract class parameter can we mock it using mockito?
Ex
public abstract AbstractClass{
}
//Class under test
public class SourceClass{
SourceClass(AbstractClass abstractClass){}
}
#RunWith(MockitoJUnitRunner.class
public SourceClassTest{
#Mock
AbstractClass abstractClass;
}
whenever I do this i get this error
java.lang.ExceptionInInitializerError
Ther version of mockito I am using i 1.8.5
Well, this code below works fine, just tell me if I need to add some comments to explain what I wrote, ok? (hey, I am using Mockito 1.10.8):
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
abstract class AbstractClassToTest {
public abstract String doSomething();
}
class ConcreteClass {
private String something;
public ConcreteClass(AbstractClassToTest aClass){
this.something = aClass.doSomething();
}
public String getSomething(){
return this.something;
}
}
#RunWith(MockitoJUnitRunner.class)
public class TempTest {
#Mock
private AbstractClassToTest myClass;
#Test
public void canAbstractClassToTestBeMocked() {
String expectedResult = "hello world!";
Mockito
.when(myClass.doSomething())
.thenReturn(expectedResult);
String actualResult = myClass.doSomething();
Assert.assertEquals(expectedResult, actualResult);
}
#Test
public void canConcreteClassBeInstantiatedWithMock() {
String expectedResult = "hello world!";
Mockito
.when(myClass.doSomething())
.thenReturn(expectedResult);
ConcreteClass concrete = new ConcreteClass(myClass);
String actualResult = concrete.getSomething();
Assert.assertEquals(expectedResult, actualResult);
}
}
You cannot mock abstract classes, you have to mock a concrete one and pass that along. Just as regular code can't instantiate abstract classes.