How to Mock repository calls ATG - mockito

Can we use Mockito to write tests for methods which implements repository calls? For example below method is using Named query to get eBooks from a Book Repository -
public RepositoryItem[] getEBooks(DynamoHttpServletRequest request) {
RepositoryItem[] results = null;
Repository rep = (Repository) request.resolveName("/atg/products/BookRepository");
try {
RepositoryItemDescriptor desc = rep.getItemDescriptor("Book");
RepositoryView view = desc.getRepositoryView();
if (view instanceof NamedQueryView) {
NamedQueryView nameView = (NamedQueryView) view;
ParameterSupportView pSupportView = (ParameterSupportView) view;
String queryName = "GetBooks";
Query namedQuery = nameView.getNamedQuery(queryName);
Object[] params = { "ebook" }; //book type
results = pSupportView.executeQuery(namedQuery, params);
}
} catch (RepositoryException e) {
logError(e.getMessage());
}
return results;
}
Thanks.

Yes you can. The question is though are you testing YOUR code or ATG in this instance?
Assuming your method above is contained in a class called GetBooks your test could look something like this:
#InjectMocks private GetBooks testObj;
#Mock private DynamoHttpServletRequest requestMock;
#Mock private Repository bookRepositoryMock;
#Mock private RepositoryItemDescriptor bookRepositoryItemDescriptorMock;
#Mock private GSAView bookRepositoryViewMock; //The only oddity here but GSAView is the common denominator for NamedQueryView and ParameterSupportView
#Mock private Query namedQueryMock;
#Mock private RepositoryItem resultRepositoryItem1, resultRepositoryItem2;
#BeforeMethod(groups = { "unit" })
public void setup() throws Exception {
testObj = new GetBooks();
MockitoAnnotations.initMocks(this);
Mockito.when(requestMock.resolveName("/atg/products/BookRepository")).thenReturn(bookRepositoryMock);
Mockito.when(bookRepositoryMock.getItemDescriptor("Book")).thenReturn(bookRepositoryItemDescriptorMock);
Mockito.when(bookRepositoryItemDescriptorMock.getRepositoryView()).thenReturn(bookRepositoryViewMock);
Mockito.when(bookRepositoryViewMock.getNamedQuery("GetBooks")).thenReturn(namedQueryMock);
List<RepositoryItem> resultArrayList = new ArrayList<RepositoryItem>();
resultArrayList.add(resultRepositoryItem1);
resultArrayList.add(resultRepositoryItem2);
Object[] params = { "ebook" }; //It may be simpler to test if this was a constant
Mockito.when(bookRepositoryViewMock.executeQuery(namedQueryMock, params)).thenReturn(resultArrayList.toArray(new RepositoryItem[resultArrayList.size()]));
}
#Test(groups = { "unit" })
public void testGetEBooks()throws Exception{
RepositoryItem[] result = testObj.getEBooks(requestMock);
Assert.assertTrue(result.length == 2); //What do you want to test?
}
This gives a greenbar when executed via TestNG. But what are you really testing here?
On a separate note. You should really use (protected) constants more since you'll then be able to use them in the package scope of your Mockito tests.

Related

How to create mockito unit tests in functions that use Mutiny.Session

After some investigation I continue to pursue a more intuitive way to mock Mutiny.Session and test my functionality.
Here the method I want to test:
public class ServiceCrud {
#Inject
Mutiny.SessionFactory mutinySessionFactory;
#Inject
MicroserviceService service;
public Uni<Service> get(#NotNull final String identifier) throws ConstraintViolationException, NotFoundException {
return mutinySessionFactory.withSession(session -> {
EntityGraph<Service> entityGraph = session.getEntityGraph(Service.class, "exampleEntityGraph");
return service.get(identifier)
.onItem().ifNull().failWith(NotFoundException::new)
.onItem().transformToUni(
microservice -> Uni.createFrom()
.item(new Service(microservice.getMsId(), microservice.getMsName())));
});
}
}
The only way I found to test was through the argument captor:
#ExtendWith(MockitoExtension.class)
public class ServiceCrudTest {
#InjectMocks
private ServiceCrud serviceCrud;
#Mock
Mutiny.SessionFactory mutinySessionFactory;
#Mock
MicroserviceService service;
#Captor
ArgumentCaptor<Function<Session, Uni<Service>>> captor;
#Mock
Session session;
#Mock
EntityGraph<Service> entityGraph;
#Test
void getTest() {
// data
String msId = "msid";
String msName = "name";
Microservice toBeReturned = new Microservice();
toBeReturned.setMsId(msId);
toBeReturned.setMsName(msName);
Service expected = new Service();
expected.setId(msId);
expected.setName(msName);
// expectation
doReturn(Uni.createFrom().item(toBeReturned))
.when(service).get(anyString());
doReturn(entityGraph).when(session)
.getEntityGraph(Mockito.eq(Service.class), Mockito.anyString());
// action
serviceCrud.get("");
// capture the function and invoke it
Mockito.verify(mutinySessionFactory).withSession(captor.capture());
Function<Session, Uni<Service>> value = captor.getValue();
Uni<Service> callback = value.apply(session);
UniAssertSubscriber<Service> subscriber = callback
.subscribe().withSubscriber(UniAssertSubscriber.create());
subscriber.assertCompleted().assertItem(expected);
}
}
Is it the only way to test? Is this the correct way to test?
Any tips will be appreciated

Mockito Issue with Long and Lombok

How to write mockito for the below code, I went through: https://examples.javacodegeeks.com/core-java/junit/junit-mockito-when-thenreturn-example/
Code:
#Override
public void saveEmployee(EmployeeDto dto) {
Department department = getByDepartmentId(dto.getDepartmentId());
RoleType roleType = getByRoleTypeId(dto.getRoleTypeId());
Employee departmentMember = convertToEntity(dto, department, roleType);
try {
departmentMemberRepository.save(departmentMember);
} catch (DataIntegrityViolationException e) {
throw new PCDataIntegrityViolationException("error");
} catch (Exception ex) {
throw new InternalServerException(HttpStatus.INTERNAL_SERVER_ERROR, "error", ex);
}
}
private Employee convertToEntity(EmployeeDto dto, Department department, RoleType roleType) {
return Employee.pmBuilder()
.memberEmployeeId(dto.getMemberEmployeeId())
.memberEmployeeName(dto.getMemberEmployeeName())
.createUser(dto.getCreateUser())
.lastUpdateUser(dto.getLastUpdateUser())
.status(StatusEnum.get(dto.getStatus()))
.department(department)
.roleType(roleType)
.build();
}
private Department getByDepartmentId(Long departmentId) {
Optional<Department> optDepartment = departmentRepository.findById(departmentId);
if(!optDepartment.isPresent()) {
throw new ResourceNotFoundException("Error");
}
return optDepartment.get();
}
private RoleType getByRoleTypeId(Integer roleTypeId) {
RoleType roleType = roleTypeRepository.findByRoleTypeId(roleTypeId);
if(roleType == null) {
throw new ResourceNotFoundException("error");
}
return roleType;
}
I've written test class, only issue is that
#RunWith(PowerMockRunner.class)
#PrepareForTest({AHUtils.class })
public class EmployeeServiceTest {
#InjectMocks
private EmployeeServiceimpl employeeServiceimpl;
#Mock
private Pageable pageable;
#Mock
private Page<Employee> employeePage;
#Mock
private EmployeeRepository employeeRepository;
#Mock
private DepartmentRepository departmentRepositoryMock;
#Mock
private Employee employee;
#Mock
private Optional<Employee> employeeOptional;
#Mock
private Department departmentMock;
#Mock
private Optional<Department> departmentOptionalMock;
#Mock
private EmployeeDto employeeDto;
#Mock
private Sort sortMock;
#Mock
private Exception ex;
#Mock
private Environment env;
#Test(expected = ResourceNotFoundException.class)
public void test_RoleTypeNotPresent() {
when(departmentOptionalMock.get()).thenReturn(departmentMock);
when(departmentOptionalMock.isPresent()).thenReturn(true);
when(departmentRepositoryMock.findById(null)).thenReturn(departmentOptionalMock);
doThrow(new ResourceNotFoundException("error")).when(employeeRepository).save(any());
when(employeeDto.getDepartmentId()).thenReturn(null);
employeeServiceimpl.saveEmployee(employeeDto);
}
}
when Optional<Department> optDepartment = departmentRepository.findById(departmentId);, I wanted to have value in that so that I will go ahead, this testcase going inside if block.
In case your DepartmentRepository does not get injected into your EmployeeServiceimpl make sure of the following things
(Based on the javadoc of InjectMocks):
In case you have at least one constructor with arguments:(Mockito used constructor injection in that case)All mocks that are supposed to be injected must be parameters of your constructor with the largest number of arguments.Also note that mockito won't consider the other injection methods if there is a non no-args consturctor.
Second case would be you have setter method for the things you want to mock
(Mockito will use setter injection in that case)
In case you only have a no-args constructor and no setters:
(Mockito will use field injection in that case)All mocks annotated with #Mock have to share the same name as the fields in your EmployeeServiceimpl class.
Overmocking generally refers to the fact you generate too much mocks, even for things that are not needed to be mocks.
You could change the first 3 lines to what the example belows shows.
Note that I changed the .findById(null) to .findById(anyLong()).
I am not sure what getDepartmentId() actually returns, for a primitive long you have to use anyLong() as a mock would return 0 (and not null) by default.
However in the example below I set the departmentId to 1L so it should match regardless.
#RunWith(PowerMockRunner.class)
#PrepareForTest({AHUtils.class })
public class EmployeeServiceTest {
#InjectMocks
private EmployeeServiceimpl employeeServiceimpl;
#Mock
private DepartmentRepository departmentRepositoryMock;
#Test(expected = ResourceNotFoundException.class)
public void test_RoleTypeNotPresent() {
Department department = new Department();
department.setDepartmentId(1L);
// only if you can't simply create that object, use the mock
// Department department = Mockito.mock(Department.class);
when(departmentRepositoryMock.findById(anyLong())).thenReturn(Optional.of(department));
// ... the rest of the example does not match with the code you posted ...
employeeServiceimpl.saveEmployee(employeeDto);
}
}
Note that the remaining part of your test,
doThrow(new ResourceNotFoundException("error")).when(employeeRepository).save(any());
when(employeeDto.getDepartmentId()).thenReturn(null);
does not really match to the code you posted.
Instead your should define some behaviour on the mock of roleTypeRepository.
I am also not sure at what point a exception should be thrown, as there does not seem to be any interaction with an employeeRepository.

Using Mockito for writing ATG test case

Does anyone have idea about writing unit test case for ATG using Mockito? I came across following discussions while goggling -
Automated unit tests for ATG development and
Using PowerMock to obtain the ATG Nucleus in testing results in NPE
But need a help in setting up Nucleus and other dependencies (DAS, DPS, DSS etc.) and a sample test class for droplet using Mockito.
We are using ATG Dust where we have to set all the dependencies. I am wondering if we can replace ATG Dust completely with Mockito. Here is the example how we are writing the test cases -
A Base class for setting Nucleus -
package com.ebiz.market.support;
import java.io.File;
import java.util.Arrays;
import atg.nucleus.NucleusTestUtils;
import atg.test.AtgDustCase;
import atg.test.util.FileUtil;
public class BaseTestCase extends AtgDustCase {
public atg.nucleus.Nucleus mNucleus = null;
private final String ATGHOME="C://ATG/ATG9.4//home";
private final String ATGHOMEPROPERTY = "atg.dynamo.home";
protected void setUp() throws Exception {
super.setUp();
String dynamoHome = System.getProperty(ATGHOMEPROPERTY);
if(dynamoHome == null)
System.setProperty(ATGHOMEPROPERTY, ATGHOME);
File configpath = NucleusTestUtils.getConfigpath(this.getClass(), this.getClass().getName(), true);
FileUtil.copyDirectory("src/test/resources/config/test/", configpath.getAbsolutePath(), Arrays.asList(new String [] {".svn"}));
copyConfigurationFiles(new String[]{"config"}, configpath.getAbsolutePath(), ".svn");
}
public File getConfigPath() {
return NucleusTestUtils.getConfigpath(this.getClass(), this.getClass().getName(), true);
}
}
Writing the test case by extending the base class -
public class BizDropletTest extends BaseTestCase {
private BizDroplet bizDroplet;
#Before
public void setUp() throws Exception {
super.setUp();
mNucleus = NucleusTestUtils.startNucleusWithModules(new String[] { "DSS", "DPS", "DAFEAR" }, this.getClass(),
this.getClass().getName(), "com/ebiz/market/support/droplet/BizDroplet");
autoSuggestDroplet = (AutoSuggestDroplet) mNucleus.resolveName("com/ebiz/market/support/droplet/BizDroplet");
try {
bizDroplet.doStartService();
} catch (ServiceException e) {
fail(e.getMessage());
}
}
/**
Other methods
*/
}
So, how Mockito can handle these? Again, for me the target is to replace ATG Dust with Mockito completely because ATG Dust take lot of time in running tests due to huge dependencies.
Thanks.
Using Mockito you don't setup Nucleus or other dependencies (unless you need it). You simply mock the objects that you need to use.
Consider a simple class ProductUrlDroplet that retrieves a product from the repository and then outputs a url based on this. The service method would look something like this:
public void service(DynamoHttpServletRequest pRequest, DynamoHttpServletResponse pResponse) throws ServletException, IOException {
Object product = pRequest.getObjectParameter(PRODUCT_ID);
RepositoryItem productItem = (RepositoryItem) product;
String generatedUrl = generateProductUrl(pRequest, productItem.getRepositoryId());
pRequest.setParameter(PRODUCT_URL_ID, generatedUrl);
pRequest.serviceParameter(OPARAM_OUTPUT, pRequest, pResponse);
}
private String generateProductUrl(DynamoHttpServletRequest request, String productId) {
HttpServletRequest originatingRequest = (HttpServletRequest) request.resolveName("/OriginatingRequest");
String contextroot = originatingRequest.getContextPath();
return contextroot + "/browse/product.jsp?productId=" + productId;
}
A simple test class for this will then be:
public class ProductUrlDropletTest {
#InjectMocks private ProductUrlDroplet testObj;
#Mock private DynamoHttpServletRequest requestMock;
#Mock private DynamoHttpServletResponse responseMock;
#Mock private RepositoryItem productRepositoryItemMock;
#BeforeMethod(groups = { "unit" })
public void setup() throws Exception {
testObj = new ProductUrlDroplet();
MockitoAnnotations.initMocks(this);
Mockito.when(productRepositoryItemMock.getRepositoryId()).thenReturn("50302372");
}
#Test(groups = { "unit" })
public void testProductURL() throws Exception {
Mockito.when(requestMock.getObjectParameter(ProductUrlDroplet.PRODUCT_ID)).thenReturn(productRepositoryItemMock);
testObj.service(requestMock, responseMock);
ArgumentCaptor<String> argumentProductURL = ArgumentCaptor.forClass(String.class);
Mockito.verify(requestMock).setParameter(Matchers.eq(ProductUrlDroplet.PRODUCT_URL_ID), argumentProductURL.capture());
Assert.assertTrue(argumentProductURL.getValue().equals("/browse/product.jsp?productId=50302372"));
}
}
The key components are that you need to initialise the class you want to test (testObj). You then simply construct the response for each of the input parameters of the objects you are going to use (in this case productRepositoryItemMock represents the RepositoryItem and productRepositoryItemMock.getRepositoryId() returns a String that you can then test against later).
You will also notice that this test only validates the service method and not the individual methods. How you do it is up to you but generally I've been focused on testing my service and handleXXX methods in the formhandlers and droplets.
Testing the XXXManager, XXXUtil and XXXService classes will all have their own tests and should be 'mocked' into the droplets and formhandlers. For these I would write tests for each method though.
PowerMockito only really comes into the picture when you need to mock static methods and classes and the documentation does enough to explain that.

Moq: Verifying protected method on abstract class is called

This is my test
[TestClass]
public class RepositoryTests
{
private APurchaseOrderRepository _repository;
[TestInitialize]
public void TestInitialize()
{
_repository = new FakePurchaseOrderRepository();
}
[TestMethod]
public void RepositoryGetPurchaseOrdersForStoreCallsValidatePurchaseOrders()
{
var store = new Store();
var mockRepo = new Mock<APurchaseOrderRepository>();
mockRepo.Protected().Setup("ValidatePurchaseOrders", ItExpr.IsAny<List<PurchaseOrder>>());
_repository.GetPurchaseOrders(store);
mockRepo.Protected().Verify("ValidatePurchaseOrders", Times.Once(), ItExpr.IsAny<List<PurchaseOrder>>());
}
}
APurchaseOrderRepository and it's interface look like this
public interface IPurchaseOrderRepository
{
List<PurchaseOrder> GetPurchaseOrders(Store store);
}
public abstract class APurchaseOrderRepository : IPurchaseOrderRepository
{
public abstract List<PurchaseOrder> GetPurchaseOrders(Store store);
protected virtual bool ValidatePurchaseOrders(List<PurchaseOrder> purchaseOrders)
{
return true;
}
}
And my Fake
public class FakePurchaseOrderRepository : APurchaseOrderRepository
{
public override List<PurchaseOrder> GetPurchaseOrders(Store store)
{
var purchaseOrders = new List<PurchaseOrder>();
ValidatePurchaseOrders(purchaseOrders);
return purchaseOrders;
}
}
However, my test fails with:
Test method
PreSwapTests.RepositoryTests.RepositoryGetPurchaseOrdersForStoreCallsValidatePurchaseOrders
threw exception: Moq.MockException: Expected invocation on the mock
once, but was 0 times: mock =>
mock.ValidatePurchaseOrders(It.IsAny())
Configured setups: mock =>
mock.ValidatePurchaseOrders(It.IsAny()), Times.Never No
invocations performed.
What am I doing wrong?
Notes:
Moq.4.0.10827
Update:
I think it is this line mockRepo.Protected().Setup("ValidatePurchaseOrders");, because I need to add the parameters to it as a second argument, but I can't seem to get it correct.
Update 2:
Made some modifications, now it compiles, but isn't counting correctly...or something, error message and code are both updated above.
Realized I was doing this all wrong, changed my objects to work with this test
[TestMethod]
public void RepositoryGetPurchaseOrdersForStoreCallsValidatePurchaseOrders()
{
var store = new Store();
var mockPurchaseOrderProvider = new Mock<IPurchaseOrderProvider>();
var mockPurchaseOrderValidator = new Mock<IPurchaseOrderValidator>();
var purchaseOrderRepository = new PurchaseOrderRepository(mockPurchaseOrderProvider.Object, mockPurchaseOrderValidator.Object);
mockPurchaseOrderValidator.Setup(x => x.ValidatePurchaseOrders(It.IsAny<List<PurchaseOrder>>()));
purchaseOrderRepository.GetPurchaseOrders(store);
mockPurchaseOrderValidator.Verify(x => x.ValidatePurchaseOrders(It.IsAny<List<PurchaseOrder>>()), Times.Once());
}
This is a much better structure now I think.
It's because ValidatePurchaseOrders is not in your IPurchaseOrderRepository interface.
The repository is declared as private IPurchaseOrderRepository _repository; so it can only see what is in the interface.

Mockito verify state halfway through test

I have some code that put simply, sets an object to a state of PROCESSING, does some stuff, then sets it to SUCCESS. I want to verify that the PROCESSING save is done with the correct values.
The problem is when the verify() tests are performed, .equals() is called on the object as it is at the end of the test, rather than halfway through.
For example the code:
public void process(Thing thing) {
thing.setValue(17);
thing.setStatus(Status.PROCESSING);
dao.save(thing);
doSomeMajorProcessing(thing);
thing.setStatus(Status.SUCCESS);
dao.save(thing);
}
I want to test:
public void test() {
Thing actual = new Thing();
processor.process(actual);
Thing expected = new Thing();
expected.setValue(17);
expected.setStatus(Status.PROCESSING);
verify(dao).save(expected);
// ....
expected.setStatus(Status.SUCCESS);
verify(dao).save(expected);
}
On the first verify, actual.getStatus() is Status.SUCCESS, as Mockito just keeps a reference to the object and can only test it's value at the end.
I have considered that if a when(...) where involved then .equals() would be called at the correct time and the result would only happen if Thing was what I wanted it to be. However, in this case .save() returns nothing.
How can I verify that the object is put into the correct states?
Ok, I found a solution, but it's pretty horrible. Verify is no good to me because it runs too late, and stubbing is hard because the method returns a void.
But what I can do is stub and throw an exception if anything but the expected is called, while validating that something is called:
public void test() {
Thing actual = new Thing();
Thing expected = new Thing();
expected.setValue(17);
expected.setStatus(Status.PROCESSING);
doThrow(new RuntimeException("save called with wrong object"))
.when(dao).saveOne(not(expected));
processor.process(actual);
verify(dao).saveOne(any(Thing.class));
// ....
expected.setStatus(Status.SUCCESS);
verify(dao).saveTwo(expected);
}
private <T> T not(final T p) {
return argThat(new ArgumentMatcher<T>() {
#Override
public boolean matches(Object arg) {
return !arg.equals(p);
}
});
}
This infers that expected is called. Only drawback is that it'll be difficult to verify the method twice, but luckily in my case both DAO calls are to different methods, so I can verify them separately.
Why not just mock the Thing itself and verify that? eg:
public class ProcessorTest {
#Mock
private Dao mockDao;
#InjectMocks
private Processor processor;
#BeforeMethod
public void beforeMethod() {
initMocks(this);
}
public void test() {
Thing mockThing = Mockito.mock(Thing.class);
processor.process(thing);
verify(mockThing).setStatus(Status.PROCESSING);
verify(mockThing).setValue(17);
verify(mockDao).save(mockThing);
verify(mockThing).setStatus(Status.SUCCESS);
}
If you want to explicitly test the order in which these things happen, use an InOrder object:
public void inOrderTest() {
Thing mockThing = Mockito.mock(Thing.class);
InOrder inOrder = Mockito.inOrder(mockThing, mockDao);
processor.process(mockThing);
inorder.verify(mockThing).setStatus(Status.PROCESSING);
inorder.verify(mockThing).setValue(17);
inorder.verify(mockDao).save(mockThing);
inorder.verify(mockThing).setStatus(Status.SUCCESS);
inorder.verify(mockDao).save(mockThing);
}
Mockito has a problem verifying mutable objects. There is an open issue about this (http://code.google.com/p/mockito/issues/detail?id=126)
Maybe you should switch to EasyMock. They use a record/playback pattern and do the verification at the time of the call in contrary to Mockito, where the verification happens after the call.
This Mockito version of the test has the mentioned problem:
#Test
public void testMockito() {
Processor processor = new Processor();
Dao dao = Mockito.mock(Dao.class);
processor.setDao(dao);
Thing actual = new Thing();
actual.setValue(17);
processor.process(actual);
Thing expected1 = new Thing();
expected1.setValue(17);
expected1.setStatus(Status.PROCESSING);
verify(dao).save(expected1);
Thing expected2 = new Thing();
expected2.setValue(19);
expected2.setStatus(Status.SUCCESS);
verify(dao).save(expected2);
}
This EasyMock version works fine:
#Test
public void testEasymock() {
Processor processor = new Processor();
Dao dao = EasyMock.createStrictMock(Dao.class);
processor.setDao(dao);
Thing expected1 = new Thing();
expected1.setValue(17);
expected1.setStatus(Status.PROCESSING);
dao.save(expected1);
Thing expected2 = new Thing();
expected2.setValue(19);
expected2.setStatus(Status.SUCCESS);
dao.save(expected2);
EasyMock.replay(dao);
Thing actual = new Thing();
actual.setValue(17);
processor.process(actual);
EasyMock.verify(dao);
}
In my example doSomeMajorProcessing sets value to 19.
private void doSomeMajorProcessing(Thing thing) {
thing.setValue(19);
}
After reviewing https://code.google.com/archive/p/mockito/issues/126
I was able to get my version of this working (Java 15, Mockito 3.6.28):
// ========= CODE ==========
public void process(Thing thing) {
thing.setValue(17);
thing.setStatus(Status.PROCESSING);
dao.save(thing);
doSomeMajorProcessing(thing);
thing.setStatus(Status.SUCCESS);
dao.save(thing);
}
// ========= TEST ==========
// ++++++ NOTE - put this at class level
private final Dao dao = mock(Dao.class, withSettings().defaultAnswer(new ClonesArguments()));
public void test() {
Thing actual = new Thing();
processor.process(actual);
ArgumentCaptor<Thing> captor = ArgumentCaptor.for(Thing.class);
verify(dao, times(2)).save(captor.capture());
List<Things> savedCalls = captor.getAllValues();
assertEquals(Status.PROCESSING, savedCalls.get(0).getStatus());
assertEquals(Status.SUCCESS, savedCalls.get(1).getStatus());
}
Using argThat with a hamcrest Matcher should do the trick. The Matcher would match its passed thing if the thing has the PROCESSING status:
public class ProcessingMatcher extends BaseMatcher<Thing> {
#Override
public boolean matches(Object item) {
if (item instanceof Thing) {
return ((Thing) item).getStatus() == Status.PROCESSING;
}
return false;
}
#Override
public void describeTo(Description description) {
description.appendText(" has the PROCESSING status");
}
}
And then in your test, use the following code :
public class MyTest {
public void test() {
//...
mockDao.save(argThat(hasTheProcessingStatus()));
}
static ProcessingMatcher hasTheProcessingStatus() {
return new ProcessingMatcher();
}
}

Resources