How to perform #mock in abstract class (not Inject Mock) - java

When I am trying to MOC the dependent classes (instance variables), it is not getting mocked for abstract class. But it is working for all other classes. Any idea how to resolve this issue. I know, I could cover this code from child classes. But I want to know whether it is possible to cover via abstract class or not. Also, I want to use Mockito to resolve it.
Currently, I am getting a NULL point exception on the following line because the mamApiDao is null & not getting mocked
OvpStatusResponse ovpStatusResponse = mamApiDao.updateOvpMetadataInMam(null, callbackMessage.getMediaId(), ovpStatus, publishMessage);
Abstract class
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qvc.qq.mamapimodel.model.mamapi.OvpStatus;
import com.qvc.qq.mamapimodel.model.mamapi.response.OvpStatusResponse;
import com.qvc.qq.mammessageprocessor.config.settings.MqMessageSettings;
import com.qvc.qq.mammessageprocessor.dao.MamApiDao;
import com.qvc.qq.mammessageprocessor.manager.ErrorMessageManager;
import com.qvc.qq.mammessageprocessor.model.CdnCallbackMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.server.ResponseStatusException;
public abstract class CallbackManager {
private final MamApiDao mamApiDao;
public CallbackManager( MamApiDao mamApiDao) {
this.mamApiDao = mamApiDao;
}
public void processCallback(CdnCallbackMessage callbackMessage, int retries, OvpStatus ovpStatus, String publishMessage) {
// some code
//mamApiDao is NULL, it is not getting mocked
OvpStatusResponse ovpStatusResponse = mamApiDao.updateOvpMetadataInMam(null, callbackMessage.getMediaId(), ovpStatus, publishMessage);
// some code
}
}
Test Class
import com.qvc.qq.mamapimodel.model.mamapi.OvpStatus;
import com.qvc.qq.mamapimodel.model.mamapi.response.OvpStatusResponse;
import com.qvc.qq.mammessageprocessor.config.settings.MqMessageSettings;
import com.qvc.qq.mammessageprocessor.dao.MamApiDao;
import com.qvc.qq.mammessageprocessor.dao.MqMessagingDao;
import com.qvc.qq.mammessageprocessor.model.CdnCallbackMessage;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.isNull;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class CallbackManagerTest {
#InjectMocks
CallbackManager callbackManager = Mockito.mock(CallbackManager.class, Mockito.CALLS_REAL_METHODS);
#Mock
MamApiDao mamApiDao;
#BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
}
#Test
public void processCallbackTest() {
when(mamApiDao.updateOvpMetadataInMam(any(), anyString(), any(), anyString())).thenReturn(new OvpStatusResponse());
callbackManager.processCallback(cdnCallbackMessage, 1, OvpStatus.ACTIVE, "published");
verify(mamApiDao, times(1)).updateOvpMetadataInMam(any(), anyString(), any(), anyString());
}
}
Enum Class
public enum OvpStatus {
SUBMITTED("SUBMITTED"),
ACTIVE("ACTIVE"),
INACTIVE("INACTIVE"),
ERROR("ERROR"),
NONE("NONE");
private String value;
private OvpStatus(String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
}
Dao class
import com.qvc.qq.mamapimodel.model.mamapi.OvpStatus;
import com.qvc.qq.mamapimodel.model.mamapi.response.OvpStatusResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
#Slf4j
#Component
public class MamApiDao {
public OvpStatusResponse updateOvpMetadataInMam(String mamId, String ovpId, OvpStatus status, String publishMessage) {
OvpStatusResponse ovpStatusResponse = new OvpStatusResponse();
ovpStatusResponse.setId(1);
ovpStatusResponse.setStatus("");
return ovpStatusResponse;
}
}
Test Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>

can you try like the below one?
public class CallbackManagerTest {
#InjectMocks
CallbackManager callbackManager = Mockito.mock(CallbackManager.class, Mockito.CALLS_REAL_METHODS);
#MockBean
private MamApiDao mamApiDao;
#BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
}
//do something

Related

How to test java class having initialisation in constructor

I have a java class whose constructor looks like this
private SomeManager someManager;
public MyService() {
this.someManager = ManagerHandler.getDefault();
}
The issue is that while testing ManagerHandler is not initialised so I am not able to create new object of this class to test its method. I am using mockito for testing. I am not able to understand How to mock a parameter which I am not passing in the constructor.
Is there anyway I can mock someManager using PowerMock?
You can use InjectMocks annotation. See below example:
MyService class:
public class MyService {
ManagerHandler someManager;
public MyService() {
this.someManager = ManagerHandler.getDefault();
}
// other methods
public String greetUser(String user) {
return someManager.sayHello(user) + ", Good Morning!";
}
}
ManagerHandler class:
public class ManagerHandler {
public static ManagerHandler getDefault() {
return new ManagerHandler();
}
public String sayHello(String userName) {
return "Hello " + userName;
}
}
TestClass:
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
#RunWith(MockitoJUnitRunner.class)
public class TestClass {
#Mock
ManagerHandler someManager;
#InjectMocks
MyService myService = new MyService();
#Test
public void test() {
//mock methods of ManagerHandler
Mockito.when(someManager.sayHello("Alice")).thenReturn("Hello Alice");
assertEquals("Hello Alice, Good Morning!", myService.greetUser("Alice"));
}
}

I'm trying to mock a list of strings but it's not working. I'm not able to figure out the problem

This is the class and the corresponding test I have written for it. Can someone please help me understand why System.out.println(a.size()) prints 0 , when it should print 1000?
WorkingwithLists.java
import java.util.ArrayList;
import java.util.List;
public class WorkingwithLists
{
public static void main(String[] args) {
}
public void ListFunctions()
{
List<String > a=new ArrayList<>();
System.out.println(a.size());
}
}
WorkingwithListsTest.java
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.List;
import static org.mockito.Mockito.when;
import static org.testng.Assert.*;
public class WorkingwithListsTest
{
#Mock
private List<String> a;
private WorkingwithLists workingwithLists;
#BeforeMethod
public void setup()
{
MockitoAnnotations.openMocks(this);
workingwithLists=new WorkingwithLists();
}
#Test
public void testListFunctions() throws Exception
{
when(a.size()).thenReturn(1000);
workingwithLists.ListFunctions();
}
}
I am not sure why you want that, but to achieve that you have to move the "List a" to class level in order to "Mock" and return whatever you want.
I have below example working, Hope this helps :
import java.util.ArrayList;
import java.util.List;
public class WorkingwithLists{
List<String > a=new ArrayList<>();
public static void main(String[] args) {
}
public void ListFunctions(){
System.out.println(a.size());
}
}
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.List;
#RunWith(MockitoJUnitRunner.class)
public class WorkingwithListsTest{
#InjectMocks
WorkingwithLists workingwithLists;
#Mock
private List<String> a;
#Before
public void setup(){
Mockito.when(a.size()).thenReturn(1000);
}
#Test
public void testListFunctions() throws Exception{
workingwithLists.ListFunctions();
Assert.assertTrue(true);
}
}
Output :

Error with import of org.junit.Assert

I'm having a little problem with a unit-test my professor gave me. Upon compilation, I recieve the following errors:
cannot find symbol import org.junit.Assert.assertArrayEquals;
cannot find symbol import org.junit.Assert.assertEquals;
import org.junit.Assert.assertFalse;
import org.junit.Assert.assertTrue;
I have downloaded JUnit and I can compile a similar file, so why am I having problems with this?
The code is:
import java.util.Comparator;
import org.junit.Assert.assertArrayEquals;
import org.junit.Assert.assertEquals;
import org.junit.Assert.assertFalse;
import org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
public class SortingTests {
class IntegerComparator implements Comparator<Integer> {
#Override
public int compare(Integer i1, Integer i2) {
return i1.compareTo(i2);
}
}
private Integer i1,i2,i3;
private OrderedArray<Integer> orderedArray;
#Before
public void createOrderedArray(){
i1 = -12;
i2 = 0;
i3 = 4;
orderedArray = new OrderedArray<>(new IntegerComparator());
}
#Test
public void testIsEmpty_zeroEl(){
assertTrue(orderedArray.isEmpty());
}
#Test
public void testIsEmpty_oneEl() throws Exception{
orderedArray.add(i1);
assertFalse(orderedArray.isEmpty());
}
#Test
public void testSize_zeroEl() throws Exception{
assertEquals(0,orderedArray.size());
}
}
What you are looking for is a Static import
The line import org.junit.Assert.assertArrayEquals; is referencing the method assertArrayEquals from the class org.junit.Assert
Importing a static method so that it is callable like assertEquals(0,orderedArray.size()); is done with a static import line. Try out the following:
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
Alternatively you can:
import static org.junit.Assert.*;
, or you could:
import org.junit.Assert;
and reference the methods like
Assert.assertEquals(0,orderedArray.size());
Assuming that you have the JUnit dependency in the classpath, use import static for the assert methods:
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
Or simply use:
import static org.junit.Assert.*;
You should add the keyword static to import it. An example:
import static org.junit.Assert.assertFalse;
If you are using junit version 5 and above then use org.junit.jupiter.api.assertions .
Path has been moved in junit 5

The constructor UiDevice() is not visible

I am getting the error message for the following code
import java.util.ArrayList;
import com.android.uiautomator.core.UiDevice;
import com.android.uiautomator.testrunner.UiAutomatorTestCase;
public class TestTarget extends UiDevice {
TestTarget() {
super();
}
public ArrayList<TestTargetView> testTargetViews;
}

JSF Backing Bean Unit Test

I have a backing bean called e.g. PeopleListBean. Purpose is simple: return a list of people from a repository.
public class PeopleListBean {
#Autowired
private PersonRepository personRepository;
private List<Person> people;
#PostConstruct
private void initializeBean() {
this.people = loadPeople();
}
public List<User> getPeople() {
return this.people;
}
private List<Person> loadPeople() {
return personRepository.getPeople();
}
}
I want to create a unit test for this bean, using Junit and Mockito.
Example test class below:
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.example.PersonRepository;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:/test-application-context.xml" })
public class PeopleListBeanTest {
#Autowired
private PeopleListBean peopleListBean;
#Autowired
private PersonRepository mockPersonRepository;
#Before
public void init() {
reset(mockPersonRepository);
}
#Test
public void canListPeople() {
List<Person> people = getDummyList();
when(mockPersonRepository.getPeople().thenReturn(people);
assertTrue(peopleListBean.getPeople().size() == people.size());
}
}
My issue is, when/how to mock the repository since the loading takes place in the initializeBean method (#PostConstruct). So after the class is constructed, the "getPeople" method is called before I can actually mock the method resulting in an assertion mismatch.
I'd really appreciate some help/guidance!
Use JUnit's #BeforeClass annotation
Your code would therefore look as follows:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:/test-application-context.xml" })
public class PeopleListBeanTest {
#Autowired
private PeopleListBean peopleListBean;
#Autowired
private PersonRepository mockPersonRepository;
#BeforeClass
public static void initialise() {
}
// .
// .
// .
}

Categories