How to write JUnit test cases with ignoring database activities - java

The following is my test class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration("/ds-context.xml")
#WebAppConfiguration
public class PaidListTest {
#Autowired
PaymentService paymentService;
#Test
public void getPaidList() {
List<PaymentGetServiceDO> response = null;
try {
response = paymentService.setPaidStatusList();
if(response != null && response.size() > 0){
for(int i = 0; i < response.size(); i++){
assertNotNull(response.get(i).getAgentcode());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
In the DAO layer of the service call paymentService.setPaidStatusList() have some operations with database activities of save and update, like em.merge(renewalPoliciesDO); But I don't want to execute them while calling the test method, they needs to get called only when actual business logic is called. How can I restrict or rollback the database transactions here?
The service and DAO methods are tedious here. However, I have simplified them for your reference. Service method
if(!updateList.isEmpty()){
HashMap<String,String> recordset = new HashMap<String,String>();
recordset = paymentDAO.setRenewalStatus(updateList);
}DAO implementation
if(paymentUpdateResDO.getPaymentstatus().equalsIgnoreCase("MANUAL") &&
!responseUpdateStatus.getPolicystatusid().equals(renewedStatusId)){
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Integer> payQuery = criteriaBuilder.createQuery(Integer.class);
Root<PaymentStatusDO> payRoot = payQuery.from(PaymentStatusDO.class);
payQuery.multiselect(payRoot.get("paymentstatusid"));
payQuery.where(criteriaBuilder.equal(payRoot.get("paymentstatusdescription"), "Manual"));
Integer paymentStatusId = em.createQuery(payQuery).getSingleResult();
insertOldPolicy(responseUpdateStatus);
responseUpdateStatus.setNewpolicyno(paymentUpdateResDO.getNewpolicyno());
responseUpdateStatus.setPreviousstatusid(responseUpdateStatus.getPolicystatusid());
responseUpdateStatus.setPolicystatusid(renewedStatusId);
Timestamp modifiedDate = new Timestamp(System.currentTimeMillis());
responseUpdateStatus.setModifieddatetime(modifiedDate);
responseUpdateStatus.setModifiedby("RPA");
responseUpdateStatus.setPaymentstatusid(paymentStatusId);
responseUpdateStatus.setActiveindicator("Y");
em.merge(responseUpdateStatus);
successRecords++;
}
In my case, I need the result arraylists, but the em.merge and em.persist activities need to be ignored.
When I try with MockitoJUnitRunner as #GauravRai1512 preferred, I get my testcase executed but the program is terminated so that I am unable to get the result ArrayLists.
Refer this image

You should follow below approach as suggested by Pooja Aggarwal.
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
#RunWith(MockitoJUnitRunner.class)
public class PaidListTest {
#Mock
PaymentService paymentService;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mapperObj = new ObjectMapper();
List<PaymentGetServiceDO> response = new ArrayList<PaymentGetServiceDO>();
}
#Test
public void getPaidList() {
List<PaymentGetServiceDO> response = null;
try {
response = paymentService.setPaidStatusList();
if(response != null && response.size() > 0){
for(int i = 0; i < response.size(); i++){
assertNotNull(response.get(i).getAgentcode());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This code will not execute your save and update operation.

You can use mocking of the database calls. You can write test cases using Jmockit where you can mock the call of database which will prevent save or update operation in the database.
You can learn writing jmockit test cases from http://jmockit.github.io/tutorial/Introduction.html
Or
https://winterbe.com/posts/2009/08/18/introducing-jmockit/

Like others have said, you can either:
Mock the PaymentService so that you can define exactly what to do on each of the calls to it. In this case, you would simply return a hard-coded List<PaymentGetServiceDO> response, and your test could do something with that. The downside of this is that you're not really testing PaymentService in that case. You're simply looking at hard-coded data, and doing something with it. In my view, that's not a valid test.
Or, you can instantiate a PaymentService object with either an in-memory database, only for use with tests, or with a mock DB object, where you can then define exactly how to respond to each of the merge, save, update and similar operations. If the PaymentService object doesn't allow this, then it should be redesigned so it accepts as a parameter a Database/Connection, which would be the normal #Autowired injected parameter when running in production, but which you can instantiate manually when testing. This would be a proper test, since you'd be validating the rest of the logic inside setPaidStatusList, but you're not actually hitting a database to achieve that.

Related

Right way of testing method that depends on other method calls

Hi have read a lot about this but can't come to a conclusion about the best way to test a method that is dependent on other method call results to perform its actions.
Some of the questions I've read include:
Testing methods that depend on each other
Unit testing a method that calls other methods
Unit testing a method that calls another method
Some of the answers sugest that we should only test the methods that perform only one action and then test the method that call this methods for conditional behaviuour (for example, verifying if a given method was called or not) and that's fine, I get it, but I'm struggling with other scenario.
I have a service with a REST api.
The controller has a create method that receives a DTO and calls the Service class create method with this argument (DTO).
I'm trying to practice TDD and for this I use this project I'm building without a database.
The code is as follows:
#Service
public class EntityService implements FilteringInterface {
private MemoryDatabase db = MemoryDatabase.getInstance();
//Create method called from controller: receives DTO to create a new
//Entity after validating that it's name and code parameters are unique
public EntityDTO create(EntityDTO dto) throws Exception {
validateUniqueFields(dto);
Entity entity = Entity.toEntity(dto, "id1"); //maps DTO to Entity object
db.add(entity);
return new EntityDTO.Builder(entity);//maps entity to DTO
}
public void validateUniqueFields(EntityDTO dto) throws Exception {
Set<Entity> foundEntities = filterEntityByNameOrCode(dto.getName(),
dto.getCode(), db.getEntities());
if (!foundEntities.isEmpty()) {
throw new Exception("Already exists");
}
}
}
This is the interface with methods reused by other service classes:
public interface FilteringInterface {
default Set<Entity> filterEntityByNameOrCode(String name, String code, Set<Entity> list) {
return list.stream().filter(e -> e.getSiteId().equals(siteId)
&& (e.getName().equals(name)
|| e.getCode().equals(code))).collect(Collectors.toSet());
}
default Optional<Entity> filterEntityById(String id, Set<Entity> list) {
return list.stream().filter(e -> e.getId().equals(id)).findAny();
};
}
So, I'm testing this service class and I need to test the create() method because it can have different behaviors:
If the received DTO has a name that already exists on the list of entities -> throws Exception
If the received DTO has a code that already exists on the list of entities -> throws Exception
If the received DTO has a name and a code that already exists on the list of entities -> throws Exception
If name and code are different, than everything is ok, and creates the entity -> adds the entity to the existing list - > converts the entity to DTO and retrieves it.
Problem:
To test any of the scenarios, suppose, scenario 1: I need to make the filterEntityByNameOrCode() method return a list with an Entity that has the same name as the Entity I'm trying to create. This method is called inside validateUniqueFields() method.
Problem is: I can't call mockito when() for any of this methods because, for that, I would have to mock the service class, which is the class that I'm testing and, thus, it's wrong approach.
I've also read that using Spy for this is also wrong approach.
So, where thus that leaves me?
Also: if this code is not the correct aprocah, and thats why
it can't be correctly tested, than, whats should the correct approach be?
This service will have other methods (delete, update, etc.). All of this methods will make use of the FilteringInterface as well, so I will have the same problems.
What is the correct way of testing a service class?
I would apply an DI pattern in your service, in order to mock and control the db variable.
#Service
public class EntityService implements FilteringInterface {
private Persistence db;
public EntityService(Persistence db) {
this.db = db;
}
}
After that, you will be able to add entities to Set accordingly to your scenarios
#ExtendWith(MockitoExtension.class)
class EntityServiceTest {
#Mock
private Persistence persistence;
#InjectMocks
private EntityService entityService;
#BeforeEach
void before() {
final Set<Entity> existentEntity = Set.of(new Entity(1L,1L, "name", "code"));
when(persistence.getEntities()).thenReturn(existentEntity);
}
#Test
void shouldThrowWhenNameAlreadyExists() {
final EntityDTO dto = new EntityDTO(1L, "name", "anything");
assertThrows(RuntimeException.class, () -> entityService.create(dto));
}
#Test
void shouldThrowWhenCodeAlreadyExists() {
final EntityDTO dto = new EntityDTO(1L, "anything", "code");
assertThrows(RuntimeException.class, () -> entityService.create(dto));
}
#Test
void shouldThrowWhenNameAndCodeAlreadyExists() {
final EntityDTO dto = new EntityDTO(1L, "name", "code");
assertThrows(RuntimeException.class, () -> entityService.create(dto));
}
#Test
void shouldNotThrowWhenUnique() {
final EntityDTO dto = new EntityDTO(1L, "diff", "diff");
final EntityDTO entityDTO = entityService.create(dto);
assertNotNull(entityDTO);
}
}

Unit testing constructor initialization and public logic

Suppose you have the following class:
public class RepositoryImpl implements Repository {
private static final Object DEFAULT_OBJECT = new Object();
private final Persistence persistence;
private volatile Object cachedObject; // maybe ignore that this is volatile and non-final
public RepositoryImpl(Persistence persistence) {
this.persistence = persistence;
this.cachedObject = getInitialCachedObject();
}
private Object getInitialCachedObject() {
try {
return persistence.get();
} catch (ObjectNotFoundException e) {
persistence.persist(DEFAULT_OBJECT);
return DEFAULT_OBJECT;
}
}
public Object update() { /*some logic*/ }
public Object get() { /*some logic*/ }
public Object delete() { /*some logic*/ }
}
Then I want to unit test the Repository class and I mock out the persistence.
I want to have probably 2 tests that test the initialization logic (happy path and exception) and 3 more tests for the public methods.
The question is how should I approach the testing of this?
The possible options that I managed to think of are:
Consider calling the initialization from outside through a public method after ctor
breaks the immutability (in my particular case this is already broken as cachedObject needs to be volatile and not final, but in the general case.. yeah)
Create the RepositoryImpl in each test case instead of using #InjectMocks or #Before
Create two nested test classes - one for the init logic and one for the core logic
Somehow use #InjectMocks but re-initialize only in one test, not sure if possible
Some lazy approach in get(), but also breaks immutability in the general case
To me option 3 seems clean, but maybe there is a better approach or further refactoring is needed idk. Any suggestions are highly appreciated.
Note that I cannot just use #Cachable in the Persistence because this is not a Spring project.
Create the RepositoryImpl in each test case instead of using #InjectMocks or #Before
Create two nested test classes - one for the init logic and one for the core logic
I think that the options above are viable solutions, but you made a good point here:
Somehow use #InjectMocks but re-initialize only in one test, not sure if possible
To achieve that you can simply ignore the instance stored in the test class field annotated with #InjectMocks and create a separate one, just in this test (as described in your second proposed approach).
#ExtendWith(MockitoExtension.class)
class RepositoryTest {
#Mock
Persistence persistence;
#InjectMocks
RepositoryImpl repository;
#Test
void oneOfMultipleTests() {
// here you're defining the persistence field mock behavior
// and using the repository field
}
#Test
void objectNotFound() {
var emptyPersistence = mock(Persistence.class);
when(emptyPersistence.get()).thenThrow(...);
var emptyBasedRepository = new RepositoryImpl(emptyPersistence);
assertNotNull(emptyBasedRepository);
verify(emptyPersistence).persist(argThat(...));
// assert something else if you want
}
}

Mockito failing inside internal call for mocked method

I'm trying to mock the return value for a method using the when call from mockito. However, I'm new to this and I may perhaps be misunderstanding how mockito works, since the call is failing inside the method mocked when that calls another method. I thought regardless of how that method is implemented, I should be getting the return value I'm asking for? Or do I need to mock also the internals for that method? I feel that shouldn't be it.
public boolean verifyState(HttpServletRequest request, String s) {
String stateToken = getCookieByName(request, STATE_TOKEN);
String authToken = getCookieByName(request, AUTHN);
boolean isValidState = true;
if (isValidState) {
try {
log.info(getEdUserId(stateToken, authToken));
return true;
} catch (Exception e) {
ExceptionLogger.logDetailedError("CookieSessionUtils.verifyState", e);
return false;
}
} else {
return false;
}
}
public String getEdUserId(String stateToken, String authToken) throws Exception {
String edUserId;
Map<String, Object> jwtClaims;
jwtClaims = StateUtils.checkJWT(stateToken, this.stateSharedSecret); // Failing here not generating a proper jwt token
log.info("State Claims: " + jwtClaims);
edUserId = sifAuthorizationService.getEdUserIdFromAuthJWT(authToken);
return edUserId;
}
My test:
#ActiveProfiles(resolver = MyActiveProfileResolver.class)
#WebMvcTest(value = CookieSessionUtils.class, includeFilters = {
#ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {ApiOriginFilter.class, ValidationFilter.class})})
class CookieSessionUtilsTest {
#Autowired
private CookieSessionUtils cookieSessionUtils; // Service class
#Mock
private CookieSessionUtils cookieSessionUtilsMocked; // Both the method under test and the one mocked are under the same class, so trying these two annotations together.
#Mock
private HttpServletRequest request;
#BeforeEach
public void setUp() {
MockitoAnnotations.initMocks(this);
}
#Test
public void testVerifyState1() throws Exception {
//...Some mocks for getCookieName
UUID uuid = UUID.randomUUID();
when(cookieSessionUtils.getEdUserId(anyString(), anyString()).thenReturn(eq(String.valueOf(uuid))); // When this line runs it fails on verifyState method
assertTrue(cookieSessionUtils.verifyState(request, ""));
}
UPDATE
Attempt using anyString() instead of eq().
Thank you.
Your test is broken in a few places.
Setting expectations on a real object
You should call Mockito.when on mocks and spies, not on System under test. Mockito normally reports it with a clear error message, but you throw a NPE from getEdUserId, so this is reported instead. The NPE stems from the fact that both eq and anyString return null, which is passed to the real method.
Invalid use of matchers
As #StefanD explained in his answer eq("anyString()") is not matching any string. It matches only one string "anyString()"
Returning a mather instead of real object
thenReturn(eq(String.valueOf(uuid)))
This is illegal position for a matcher.
Mixing Mockito and Spring annotations in a WebMvcTest
This is a common error. Mockito does not inject beans to the spring context.
From the code provided it is unclear what CookieSessionUtils is (Controller? ControllerAdvice?) and what is the correct way to test it.
Update
It seems that you are trying to replace some methods under test. A way to do it is to use a Spy.
See https://towardsdatascience.com/mocking-a-method-in-the-same-test-class-using-mockito-b8f997916109
The test written in this style:
#ExtendWith(MockitoExtension.class)
class CookieSessionUtilsTest {
#Mock
private HttpServletRequest request;
#Mock
private SifAuthorizationService sifAuthorizationService;
#Spy
#InjectMocks
private CookieSessionUtils cookieSessionUtils;
#Test
public void testVerifyState1() throws Exception {
Cookie cookie1 = new Cookie("stateToken", "stateToken");
Cookie cookie2 = new Cookie("Authn", "Authn");
when(request.getCookies()).thenReturn(new Cookie[]{cookie1, cookie2});
UUID uuid = UUID.randomUUID();
doReturn(String.valueOf(uuid)).when(cookieSessionUtils).getEdUserId(anyString(), anyString());
assertTrue(cookieSessionUtils.verifyState(request, ""));
}
}
An alternative way is to call the real method, but to mock all collaborators: StateUtils and sifAuthorizationService. I would probably go with this one, if you want to test public getEdUserId.
Test written when mocking collaborators:
#ExtendWith(MockitoExtension.class)
class CookieSessionUtilsTest {
#Mock
private HttpServletRequest request;
#Mock
private SifAuthorizationService sifAuthorizationService;
#InjectMocks
private CookieSessionUtils cookieSessionUtils;
#Test
public void testVerifyState1() throws Exception {
Cookie cookie1 = new Cookie("stateToken", "stateToken");
Cookie cookie2 = new Cookie("Authn", "Authn");
when(request.getCookies()).thenReturn(new Cookie[]{cookie1, cookie2});
UUID uuid = UUID.randomUUID();
when(sifAuthorizationService.getEdUserIdFromAuthJWT(cookie2.getValue())).thenReturn(String.valueOf(uuid));
assertTrue(cookieSessionUtils.verifyState(request, ""));
}
}
I took the assumption that StateUtils.checkJWT does not need to be mocked
The points above are still valid and need to be resolved in either case.
Remarks
As the system under test is currently a Service, I suggest to drop WebMvcTest and test it with plain mockito instead.
Should SUT be a service? It is more typical to handle auth code in filters.
note usage of doReturn when stubbing a method on a spy.
You use mocks in more places than needed. For example Cookie is trivial to construct, there is no point in using a mock
The error is here:
when(cookieSessionUtils.getEdUserId(eq("anyString()"), eq("anyString()"))).thenReturn(eq(String.valueOf(uuid)));
It should read like
when(cookieSessionUtils.getEdUserId(anyString()), anyString()).thenReturn(uuid);
Please refer to the Mockito documentation of Argument matchers.
Because the argument matchers looking for the string "anyString()" they never match the actual parameters the method call is providing and so there is never returned the uuid you expecting.

Need to return value from scheduled method in Spring MVC

I am writing scheduler in my web application for notification purpose, the task of my scheduler is simple, It will hit the third party centralised database and look for the availability of data, if data is available then it returns true otherwise false.
But I am stuck here, I want to show the notification on based on the result (true/false)returning by my scheduler, but I am not able to think, how do I implement the same? I thought of bind the variable in session, but because it is time even so session is not possible here.
Suppose scheduler returning true, now I want this value inside my JSP page(Dashboard page) where I can able to show the message that "Data is available" in user's dashboard. I need this value to check condition
if(true)
"data is available"
else
no notification
Please see my code and suggest me.
package com.awzpact.uam.scheduler;
import com.awzpact.prayas.dao.HRMSPickSalaryDataDAO;
import com.awzpact.uam.domain.SalaryDetailReport;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
public class PayrollDataNotificationScheduler {
private static boolean AVAIL_STATUS = false;
private static final Logger LOGGER = Logger.getLogger(PayrollDataNotificationScheduler.class);
public boolean checkDataAvailability() {
try {
List<SalaryDetailReport> list = salaryDataDAO.findAll();
if (list.size() > 0) {
AVAIL_STATUS = true;
return AVAIL_STATUS;
}
return false;
} catch (Exception e) {
e.printStackTrace();
LOGGER.info("Data is not available for migrate");
return false;
}
}
#Autowired
HRMSPickSalaryDataDAO salaryDataDAO;
}
You run your scheduled task periodically if there's some data retrieved - you save it to your DB.
// in your scheduled #Component
#Autowired
private SomeDataDAO someDataDAO;
#Scheduled(cron = "...")
public void fetchThirdPartyData() {
SomeData thirdPartyData = getThirdPartyData();
someDataDAO.save(thirdPartyData);
}
private SomeData getThirdPartyData() {
// calling their API...
}
Then you create a controller which is going to get the data from db (if exists, notice the Optional interface - you can use this in your DAO method)
// a rest controller
#RestController
#RequestMapping("/someData")
public class SomeController {
#Autowired
private SomeDataDAO someDataDAO;
#GetMapping
public SomeData getSomeData() {
return someDataDao.getSomeData().orElse(null);
}
}
Now, in your fronted you do some AJAX call, depending on what you're using there and then you can do your check and print the message.
Scheduling means that you want to make some actions on the schedule basis.
Waiting for response looks more like request/response communication between client and server.
To check that data is available - it's better to use simple method invocation via REST Controller and don't use a scheduler at all.

How to use Mockito to mock including an EntityManager

Currently in school we are working on a rather large project. However testing in Java wasn't really explained that well so I didn't really work TDD like I was suppose to.
protected EntityManager getEntityManager() {
return EntityController.getEntityManager();
}
// Get all exam skeletons from the DB
#Override
public List<ExamSkeleton> getAllSkeletons() {
EntityManager entityManager = getEntityManager();
try {
TypedQuery<ExamSkeleton> query = entityManager.createQuery("SELECT NEW ExamSkeleton (s.id, s.filename, s.course, s.visible) FROM ExamSkeleton as s", ExamSkeleton.class);
List<ExamSkeleton> skeletons = query.getResultList();
return skeletons;
} catch (IllegalArgumentException exception) {
LOGGER.error(exception);
}
return Collections.emptyList();
}
So my question is, how do I test this method using Mockito?
Approach 1: Test the Code As Is
The getEntityManager method is private and it invokes a static method so, as things stand, you would need to use PowerMockito to provide a mocked instance of EntityManager in your test. For example:
#RunWith(PowerMockRunner.class)
#PrepareForTest({EntityController.class})
public class SomeTest {
#Test
public void aTest() {
PowerMockito.mockStatic(EntityController.class);
EntityManager entityManager = Mockito.mock(EntityManager.class);
Mockito.when(EntityController.getEntityManager()).thenReturn(entityManager);
TypedQuery<ExamSkeleton> query = (TypedQuery<ExamSkeleton>) Mockito.mock(TypedQuery.class);
Mockito.when(entityManager.createQuery("SELECT NEW ExamSkeleton (s.id, s.filename, s.course, s.visible) FROM ExamSkeleton as s")).thenReturn(query);
List<ExamSkeleton> expected = new ArrayList<>();
Mockito.when(query.getResultList()).thenReturn(expected);
ExamRepository examRepository = new ExamRepository();
List<ExamSkeletons> actual = examRepository.getAllSkeletons();
// this assertion verifies that getAllSkeletons gives you the result of the above SQl query
assertSame(expected, actual);
}
}
Approach 2: Refactor For Separation of Concerns and Ease of Testing
However, you could simplify things, from a testing and design perspective, by externalising the creation of the entity manager into a factory, for example.
public class EntityManagerFactory {
public EntityManager create() {
return EntityController.getEntityManager();
}
}
Next, inject an instance of EntityManagerFactory into whatever class contains getAllSkeletons() (i.e. the class you are testing). The simplest way of doing this is to declare it as a constructor argument:
public class SomeDao {
private final EntityManagerFactory entityManagerFactory;
public SomeDao(EntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
}
#Override
public List<ExamSkeleton> getAllSkeletons() {
try {
TypedQuery<ExamSkeleton> query = entityManager.createQuery("SELECT NEW ExamSkeleton (s.id, s.filename, s.course, s.visible) FROM ExamSkeleton as s", ExamSkeleton.class);
List<ExamSkeleton> skeletons = query.getResultList();
return skeletons;
} catch (IllegalArgumentException exception) {
LOGGER.error(exception);
}
return Collections.emptyList();
}
}
Now, you can test this code using vanilla mockito. For example:
public class SomeDaoTest {
#Test
public void canGetAllSkeletons() {
EntityManagerFactory entityManagerFactory = Mockito.mock(EntityManagerFactory.class);
Mockito.when(entityManagerFactory.create()).thenReturn(entityManager);
SomeDao sut = new SomeDao(entityManagerFactory.class);
// now SomeDao will use your mocked EntityManager so you can set expectations
// on createQuery etc to drive your test scenarios
// ...
}
}
1) The EntityManager should not be associated to the controller :
return EntityController.getEntityManager();
In terms of design, it is not desirable : low layer and high layer should not be mixed, otherwise why use them ?
In terms of testing for getAllSkeletons(), this coupling will also make the unit test harder to set and to write.
2) The actual method doesn't have logic to test but the exception case : you just create a query, execute it and return the result.
It is a good case for an integration test (without mocking the DB layer), less for an unit test.
As it will make the unit test complex and with not a lot of value.
Example of what you could get with Mockito and that I don't recommend.
Make the EntityManager a dependency of the class under test : with injection or not.
In your unit test, mock this dependency.
It could look like :
#Mock
EntityManager entityManagerMock;
#Test
public void getAllSkeletons(){
TypedQuery<ExamSkeleton> queryByMock = (TypedQuery<ExamSkeleton>) Mockito.mock(TypedQuery.class);
Mockito.when(entityManagerMock.createQuery("SELECT NEW ExamSkeleton (s.id, s.filename, s.course, s.visible) FROM ExamSkeleton as s"))
.thenReturn(queryByMock);
List<ExamSkeleton> skeletons = new ArrayList<>();
Mockito.when(queryByMock.getResultList())
.thenReturn(skeletons);
Foo foo = new Foo();
foo.setEntityManager(entityManagerMock);
// action
List<ExamSkeleton> actualSkeletons = foo.getAllSkeletons();
// assertion
Assert.assertSame(skeletons, actualSkeletons);
}
Really don't write this kind of code that just describes the flow of invocations.
It makes just a test brittle that will very rarely catch regressions.

Categories