Unable to mock a method - junit

I am new to JUNITS and have been trying to use Mockito and PowerMockito for writing some test cases for my code but have been facing an issue.
Class Code:
public class Example implements Callable<Void> {
int startIndex;
int endIndex;
ConnectionPool connPool;
Properties properties;
public Example(int start, int end,
ConnectionPool connPool, Properties properties) {
this.startIndex = start;
this.endIndex = end;
this.connPool= connPool;
this.properties = properties;
}
#Override
public Void call() throws Exception {
long startTime = System.currentTimeMillis();
try {
List<String> listInput = new ArrayList<>();
Service service = new Service(
dbConnPool, properties, startIndex, endIndex);
service.getMethod(listInput);
.
.
.
JUNIT Code:
#RunWith(PowerMockRunner.class)
#PrepareForTest()
public class ExampleTest {
#Mock
private ConnectionPool connectionPool;
#Mock
private Properties properties;
#Mock
private Service service = new Service(
connectionPool, properties, 1, 1);
#Mock
private Connection connection;
#Mock
private Statement statement;
#Mock
private ResultSet resultSet;
#InjectMocks
private Example example = new Example(
1, 1, connectionPool, properties);
#Test
public void testCall() throws Exception {
List<String> listInput= new ArrayList<>();
listInput.add("data1");
when(service.getMethod(listInput)).thenReturn(listInput);
example.call();
}
Question: How to mock Service class and its method, getMethod, call ?
Explanation: The Service class has method getMethod, which is interacting with the DB. So, as I am not able to mock this method, the code goes through and then I have to mock all the objects in the getMethod as connection, resultset etc. else it throws NullPointerException.
Please help me understand what I am doing wrong and if possible provide your guidance on the way I should approach the JUNITS for this kind of method call.

Mockito won't help you to mock an object if you have calling of new Service inside of your method.
Instead you need to use PowerMock.expectNew
Service mockService = PowerMock.createMock(Service.class);
PowerMock.expectNew(Service.class, connectionPool, properties, 1, 1)
.andReturn(mockService);
PowerMock.replay(mockService);
For PowerMockito there is an equivalent:
PowerMockito.whenNew(Service.class)
.withArguments(connectionPool, properties, 1, 1)
.thenReturn(mockService);
Please check this article.

Related

How to make mock JdbcTemplate.queryForObject() method

I am new for Junit and Mockito and i am not understand how to write test case for below JdbcTemplate and i tried but getting exception ,Can some one help me please
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
Code
#Repository
public class BaaisnEvcIdMSRepository {
#Autowired
private JdbcTemplate jdbcTemplate;
#Transactional
public RowMapperServerResponse getQueryEvcidRepository(BaaisnEvcIdRequest baaisnEvcIdRequest) {
RowMapperServerResponse rowMapperServerResponse = jdbcTemplate.queryForObject(
"select * from Master_Circuit WHERE master_ckt_id = ( select max(master_ckt_id) from master_circuit WHERE product = ? AND id_type = ?)",
new Object[]{baaisnEvcIdRequest.getProduct_type(),baaisnEvcIdRequest.getLata()}, new BaaisnRowMapper());
return rowMapperServerResponse;
}
}
test class
public class BaaisnEvcIdMSRepositoryTest {
#InjectMocks
BaaisnEvcIdMSRepository baaisnEvcIdMSRepository;
#Mock
JdbcTemplate jdbcTemplate;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
#Test
public void getQueryEvcidRepositoryTest() {
when(jdbcTemplate.queryForObject(eq(ArgumentMatchers.anyString()), refEq(new Object[]{ArgumentMatchers.anyInt()}), eq(String.class))).thenReturn("data");
verify(jdbcTemplate, times(1)).queryForObject(eq(ArgumentMatchers.anyString()), refEq(new Object[]{ArgumentMatchers.anyInt()}), eq(String.class));
}
}
The InvalidUseOfMatchersException is coming from your use of eq(ArgumentMatchers.anyString()) and refEq(new Object[]{ArgumentMatchers.anyInt()}). You are not supposed to wrap ArgumentMatchers inside anything else.
You also seem to aim at the wrong queryForObject method. It should be this one instead.
As mentioned before you need to call the method under test before doing the verification.
#Test
public void getQueryEvcidRepositoryTest() {
// use a real `BaaisnEvcIdRequest` object if you can
BaaisnEvcIdRequest req = Mockito.mock(BaaisnEvcIdRequest.class);
Mockito.when(req.getProduct_type()).thenReturn(1);
Mockito.when(req.getLata()).thenReturn(new Object());
Object[] array = new Object[]{req.getProduct_type(),req.getLata()};
Mockito.when(jdbcTemplate.queryForObject(Mockito.anyString(), Mockito.eq(array), Mockito.any(RowMapper.class)))
.thenReturn("data");
baaisnEvcIdMSRepository.getQueryEvcidRepository(req);
Mockito.verify(jdbcTemplate, Mockito.times(1))
.queryForObject(Mockito.anyString(), Mockito.eq(array), Mockito.any(RowMapper.class));
}

How to mock ObjectMapper.readValue() using mockito

I'm testing a service layer and not sure how to mock ObjectMapper().readValue in that class. I'm fairly new to mockito and could figure out how to do it.
The following is my code,
service.java
private configDetail fetchConfigDetail(String configId) throws IOException {
final String response = restTemplate.getForObject(config.getUrl(), String.class);
return new ObjectMapper().readValue(response, ConfigDetail.class);
}
ServiceTest.java
#Test
public void testgetConfigDetailReturnsNull() throws Exception {
restTemplate = Mockito.mock(restTemplate.class);
Service service = new Service();
Config config = Mockito.mock(Config.class);
ObjectMapper objMapper = Mockito.mock(ObjectMapper.class);
Mockito.doReturn("").when(restTemplate).getForObject(anyString(), eq(String.class));
Mockito.doReturn(configDetail).when(objMapper).readValue(anyString(),eq(ConfigDetail.class));
assertEquals(configDetail, service.getConfigDetail("1234"));
}
I get the following results when I run this test,
com.fasterxml.jackson.databind.exc.MismatchedInputException: No content to map due to end-of-input
at [Source: (String)""; line: 1, column: 0]
Posting ServiceTest.Java here
#RunWith(MockitoJUnitRunner.class)
public class ConfigServiceTest {
#Mock
private ConfigPersistenceService persistenceService;
#InjectMocks
private ConfigService configService;
#Mock
ConfigDetail configDetail;
#Mock
private RestTemplate restTemplate;
#Mock
private ObjectMapper objMapper;
#Mock
private Config config;
#Test
public void testgetConfigDetailReturnsNull() throws Exception {
ObjectMapper objMapper = Mockito.mock(ObjectMapper.class);
Mockito.doReturn(ucpConfig).when(persistenceService).findById("1234");
Mockito.doReturn("").when(restTemplate).getForObject(anyString(), eq(String.class));
Mockito.when((objMapper).readValue(“”,ConfigDetail.class)).thenReturn(configDetail);
assertEquals(ConfigDetail, ConfigService.getConfigDetail("1234"));
}
}
With your current Service class it would be difficult to mock ObjectMapper, ObjectMapper is tightly coupled to fetchConfigDetail method.
You have to change your service class as follows to mock ObjectMapper.
#Service
public class MyServiceImpl {
#Autowired
private ObjectMapper objectMapper;
private configDetail fetchConfigDetail(String configId) throws IOException {
final String response = restTemplate.getForObject(config.getUrl(), String.class);
return objectMapper.readValue(response, ConfigDetail.class);
}
}
Here what I did is instead of creating objectMapper inside the method I am injecting that from outside (objectMapper will be created by Spring in this case)
Once you change your service class, you can mock the objectMapper as follows.
ObjectMapper mockObjectMapper = Mockito.mock(ObjectMapper.class);
Mockito.when(mockObjectMapper.readValue(anyString(), any(ConfigDetail.class)).thenReturn(configDetail);
Problem is with the this line where you are mocking the call to objectmapper.
Mockito.when((objMapper).readValue(“”,ConfigDetail.class)).thenReturn(configDetail);
Correct syntax is
Mockito.when(objMapper.readValue(“”,ConfigDetail.class)).thenReturn(configDetail);
Notice the bracket position. When using Spy or Verify, the bracket position is diff. then when using when-then syntax.
Mocking objects created in a SUT is IMO the single biggest limitation of mockito. Use jmockit or powerMock or checkout the offical mockito way of handling this. https://github.com/mockito/mockito/wiki/Mocking-Object-Creation

mockito when method returns null in junit

I have been writing the test cases using the mockito. the below is my code in the test cases.
#RunWith(SpringRunner.class)
public class LoginControllerTest {
private MockMvc mockMvc;
#InjectMocks
private LoginService loginService;
#Mock
private LoginController loginController;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
// Setup Spring test in standalone mode
mockMvc = MockMvcBuilders.standaloneSetup(loginController).build();
}
#Test
public final void test() throws Exception {
// Assign
when(loginService.test()).thenReturn("hello");
// act
mockMvc.perform(get("/hello"))
// Assertion
.andExpect(status().isOk())
.andExpect(content().string("Message from service: hello"));
verify(loginService).test();
}
#Test
public final void usernameInvalidAndPassword() throws Exception {
User userData = new User();
userData.setUserName("akhila.s#cloudium.io");
userData.setPassword("Passw0rd");
User userDataNew = new User();
userDataNew.setUserName("akhila.s#cloudium.io");
userDataNew.setPassword("Passw0rd");
JSONObject requestBody = new JSONObject();
requestBody.put("userName", "akhila.s#cloudium.io");
requestBody.put("password", "Passw0rd");
JSONObject responseBody = new JSONObject();
responseBody.put("status_code", "200");
responseBody.put("message", "ok");
// Assign
when(loginService.saveUser(userData)).thenReturn(userDataNew);
// act
mockMvc.perform(get("/login")
.param("userName", "akhila.s#cloudium.io")
.param("password", "Passw0rd"))
// Assertion
.andExpect(status().isOk()).andExpect(content().json(responseBody.toString())).andDo(print());
}
For the first test case its working fine but for the second test it is returning null always. Can anyone please help? Thanks in advance
You have the annotations the wrong way round on your LoginController and LoginService. You are testing the controller so you don't want to mock it, and you are stubbing methods on your service so this needs to be a mock:
#Mock
private LoginService loginService;
#InjectMocks
private LoginController loginController;
In my opinion you have to either:
1) Introduce equals method based on username and password as the User object created inside the method under test is a different instance than the one you create and use in the test.
2) Use a wildcard in your set-up:
when(loginService.saveUser(Mockito.any(User.class))).thenReturn(userDataNew);

How to use mockito for testing Database connection

I am using Junit to test my jersey api. I want to test DAO without a database. I tried using Mockito but still not able to use mock object to test the DAO which contains Hibernate calls to DB. I want to write Junit for my Helper class which calls the DAO.Can anyone provide a solution with some sample code to mock the DB Connections in DAO.
EDIT :
Status.java
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getDBValue() throws SQLException {
DatabaseConnectionDAO dbConnectiondao = new DatabaseConnectionDAO();
String dbValue = dbConnectiondao.dbConnection();
return dbValue;
}
DatabaseConnectionDAO.java
private Connection con;
private Statement stmt;
private ResultSet rs;
private String username;
public String dbConnection() throws SQLException{
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "root");
stmt = con.createStatement();
rs =stmt.executeQuery("select * from test");
while(rs.next()){
username = rs.getString(1);
}
}catch(Exception e){
e.printStackTrace();
}finally{
con.close();
}
return username;
}
TestDatabase.java
#Test
public void testMockDB() throws SQLException{
DatabaseConnectionDAO mockdbDAO = mock(DatabaseConnectionDAO.class);
Connection con = mock(Connection.class);
Statement stmt = mock(Statement.class);
ResultSet rs = mock(ResultSet.class);
Client client = Client.create();
WebResource webResource = client.resource("myurl");
ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).get(ClientResponse.class);
verify(mockdbDAO).dbConnection();
//when(rs.next()).thenReturn(true);
when(rs.getString(1)).thenReturn(value);
actualResult = response.getEntity(String.class);
assertEquals(expectedResult,actualResult );
}
I think you may be missing the idea of how the DAO should be mocked. You shouldn't have to worry about any connections. Generally, you just want to mock what happens, when its methods are called, say a findXxx method. For instance, say you have this DAO interface
public interface CustomerDAO {
public Customer findCustomerById(long id);
}
You could mock it like
CustomerDAO customerDao = Mockito.mock(CustomerDAO.class);
Mockito.when(customerDao.findCustomerById(Mockito.anyLong()))
.thenReturn(new Customer(1, "stackoverflow"));
You would then have to "inject" that mocked instance into the class that depends on it. For example, if a resource class needs it, you could inject it via the constructor
#Path("/customers")
public class CustomerResource {
CustomerDAO customerDao;
public CustomerResource() {}
public CustomerResource(CustomerDAO customerDao) {
this.customerDao = customerDao;
}
#GET
#Path("/{id}")
#Produces(MediaType.APPLICATION_JSON)
public Response findCustomer(#PathParam("id") long id) {
Customer customer = customerDao.findCustomerById(id);
if (customer == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
return Response.ok(customer).build();
}
}
...
new CustomerResource(customerDao)
No when you hit the findCustomer method, the DAO will always return the Customer in the mocked DAO.
Here's a complete test, using the Jersey Test Framework
public class CustomerResourceTest extends JerseyTest {
private static final String RESOURCE_PKG = "jersey1.stackoverflow.standalone.resource";
public static class AppResourceConfig extends PackagesResourceConfig {
public AppResourceConfig() {
super(RESOURCE_PKG);
CustomerDAO customerDao = Mockito.mock(CustomerDAO.class);
Mockito.when(customerDao.findCustomerById(Mockito.anyLong()))
.thenReturn(new Customer(1, "stackoverflow"));
getSingletons().add(new CustomerResource(customerDao));
}
}
#Override
public WebAppDescriptor configure() {
return new WebAppDescriptor.Builder()
.initParam(WebComponent.RESOURCE_CONFIG_CLASS,
AppResourceConfig.class.getName()).build();
}
#Override
public TestContainerFactory getTestContainerFactory() {
return new GrizzlyWebTestContainerFactory();
}
#Test
public void testMockedDAO() {
WebResource resource = resource().path("customers").path("1");
String json = resource.get(String.class);
System.out.println(json);
}
}
The Customer class is simple a POJO with a long id, and String name. The dependency for The Jersey Test Framework is
<dependency>
<groupId>com.sun.jersey.jersey-test-framework</groupId>
<artifactId>jersey-test-framework-grizzly2</artifactId>
<version>1.19</version>
<scope>test</scope>
</dependency>
UPDATE
The above example uses Jersey 1, as I saw that the OP is using Jersey 1. For a complete example using Jersey 2 (with annotation injection), see this post
Short answer just don't !
The code that need to be unit tested is the client of the DAO, hence what need to be mocked are the DAOs. DAOs are the component that will integrate the app with an external system (here a database) so they have to be tested as integration tests (i.e. with a real database).

ClientResponse Failure in mockito test cases

Iam working on mockito testcases positive test methods are getting executed but comming to Exception Test methods its failing with the Exception
java.lang.Exception: Unexpected exception, expected<com.apple.ist.retail.xcard.common.exception.InvalidArgumentException> but was<org.jboss.resteasy.client.ClientResponseFailure>
at
Below is the test method which is failing and its parent class containing client object
package com.apple.ist.retail.xcard.ws.exception;
public class TestActivatePrepaidCard extends CertificateResourceTestCase {
public TestActivatePrepaidCard(String aMediaType) {
super(aMediaType);
}
#Before
public void setUp() {
super.setUp();
}
#Test(expected = InvalidArgumentException.class)
public void testActivatePrepaidCard_InvalidArgumentException()
throws DuplicateCertificateIDException, InvalidArgumentException,
DupTxnRefException, AmountException, SystemException,
XCardException {
when(
server.activatePrepaidCard(any(DiagnosticContext.class),
any(String.class), any(Number.class),
any(Amount.class), any(String.class), any(int.class),
any(HashMap.class), any(String.class),
any(SalesOrg.class), any(TxnRef.class))).thenThrow(
new InvalidArgumentException("Invalid Argument ",
INVALID_ARGUMENT));
client.activatePrepaidCard(certificateRequest);
}
Its failing near client.activatePrepaidCard(certificateRequest); with ClientResponseFailure Exception
Parent test case is
package com.apple.ist.retail.xcard.ws.exception;
#RunWith(value = Parameterized.class)
public abstract class CertificateResourceTestCase extends Assert {
protected CertificateResource client;
protected XCardServiceServer server;
protected CertificateResource resource;
protected CertificateRequest certificateRequest;
// protected Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
private String mediaType;
public CertificateResourceTestCase(String aMediaType) {
this.mediaType = aMediaType;
server = mock(XCardServiceServer.class);
CertificateResourceImpl xcardServiceRs = new CertificateResourceImpl();
xcardServiceRs.setService(server);
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getRegistry().addSingletonResource(xcardServiceRs);
dispatcher.getProviderFactory().addExceptionMapper(
XCardExceptionMapper.class);
dispatcher.getProviderFactory().addExceptionMapper(
BusinessExceptionMapper.class);
dispatcher.getProviderFactory().addExceptionMapper(
RuntimeExceptionMapper.class);
dispatcher.getProviderFactory().addExceptionMapper(
BusinessExceptionMapper.class);
dispatcher.getProviderFactory().addExceptionMapper(
RuntimeExceptionMapper.class);
dispatcher.getProviderFactory()
.getServerMessageBodyWriterInterceptorRegistry()
.register(new XCardTxnWriterInterceptor());
dispatcher.getProviderFactory().getContextDataMap()
.put(HttpServletRequest.class, new MockHttpServletRequest());
client = ProxyFactory.create(CertificateResource.class, "/", new InMemoryClientExecutor(dispatcher));
diagnosticContext.setReportingRecommended(false);
}
#After
public void tearDown() throws Exception {
Mockito.reset(server);
}
Please let me know whats wrong in my code,I am pasting complete code so that I will not miss any detail
Your code is throwing an ClientResponseFailure. Debug your test and find out why. Use an exception breakpoint.