Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4036638
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T12:14:52+00:00 2026-05-20T12:14:52+00:00

I have following code I want to test: public class MessageService { private MessageDAO

  • 0

I have following code I want to test:

public class MessageService {
    private MessageDAO dao;

    public void acceptFromOffice(Message message) {
        message.setStatus(0);
        dao.makePersistent(message);

        message.setStatus(1);
        dao.makePersistent(message);

    }
    public void setDao (MessageDAO mD) { this.dao = mD; }
}

public class Message {
    private int status;
    public int getStatus () { return status; }
    public void setStatus (int s) { this.status = s; }

    public boolean equals (Object o) { return status == ((Message) o).status; }

    public int hashCode () { return status; }
}

I need to verify, that method acceptFromOffice really sets status to 0, than persist message, then chage its status to 1, and then persist it again.

With Mockito, I have tried to do following:

@Test
    public void testAcceptFromOffice () throws Exception {

        MessageDAO messageDAO = mock(MessageDAO.class);

        MessageService messageService = new MessageService();
        messageService.setDao(messageDAO);

        final Message message = spy(new Message());
        messageService.acceptFromOffice(message);

        verify(messageDAO).makePersistent(argThat(new BaseMatcher<Message>() {
            public boolean matches (Object item) {
                return ((Message) item).getStatus() == 0;
            }

            public void describeTo (Description description) { }
        }));

        verify(messageDAO).makePersistent(argThat(new BaseMatcher<Message>() {
            public boolean matches (Object item) {
                return ((Message) item).getStatus() == 1;
            }

            public void describeTo (Description description) { }
        }));

    }

I actually expect here that verification will verify calling twice of makePersistent method with a different Message object’s state. But it fails saying that

Argument(s) are different!

Any clues?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T12:14:53+00:00Added an answer on May 20, 2026 at 12:14 pm

    Testing your code is not trivial, though not impossible. My first idea was to use ArgumentCaptor, which is much easier both to use and comprehend compared to ArgumentMatcher. Unfortunately the test still fails – reasons are certainly beyond the scope of this answer, but I may help if that interests you. Still I find this test case interesting enough to be shown (not correct solution):

    @RunWith(MockitoJUnitRunner.class)
    public class MessageServiceTest {
    
        @Mock
        private MessageDAO messageDAO = mock(MessageDAO.class);
    
        private MessageService messageService = new MessageService();
    
        @Before
        public void setup() {
            messageService.setDao(messageDAO);
        }
    
        @Test
        public void testAcceptFromOffice() throws Exception {
            //given
            final Message message = new Message();
    
            //when
            messageService.acceptFromOffice(message);
    
            //then
            ArgumentCaptor<Message> captor = ArgumentCaptor.forClass(Message.class);
    
            verify(messageDAO, times(2)).makePersistent(captor.capture());
    
            final List<Message> params = captor.getAllValues();
            assertThat(params).containsExactly(message, message);
    
            assertThat(params.get(0).getStatus()).isEqualTo(0);
            assertThat(params.get(1).getStatus()).isEqualTo(1);
        }
    
    }
    

    Unfortunately the working solution requires somewhat complicated use of Answer. In a nutshell, instead of letting Mockito to record and verify each invocation, you are providing sort of callback method that is executed every time your test code executes given mock. In this callback method (MakePersistentCallback object in our example) you have access both to parameters and you can alter return value. This is a heavy cannon and you should use it with care:

        @Test
        public void testAcceptFromOffice2() throws Exception {
            //given
            final Message message = new Message();
            doAnswer(new MakePersistentCallback()).when(messageDAO).makePersistent(message);
    
            //when
            messageService.acceptFromOffice(message);
    
            //then
            verify(messageDAO, times(2)).makePersistent(message);
        }
    
    
        private static class MakePersistentCallback implements Answer {
    
            private int[] expectedStatuses = {0, 1};
            private int invocationNo;
    
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                final Message actual = (Message)invocation.getArguments()[0];
                assertThat(actual.getStatus()).isEqualTo(expectedStatuses[invocationNo++]);
                return null;
            }
        }
    

    The example is not complete, but now the test succeeds and, more importantly, fails when you change almost anything in CUT. As you can see MakePersistentCallback.answer method is called every time mocked messageService.acceptFromOffice(message) is called. Inside naswer you can perform all the verifications you want.

    NB: Use with caution, maintaining such tests can be troublesome to say the least.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following code : using System.Collections.Generic; public class Test { static void
I have written the following code : @Controller @RequestMapping(/test) public class Home { @RequestMapping(value
I have the following code: [SetUp] public void SetMeUp() { Mapper.CreateMap<SourceObject, DestinationObject>(); } [Test]
I have the following Java code: import java.util.Arrays; import java.util.Collections; public class Test {
Suppose I have the following classes: public class Test { public static void main(String[]
I have the following (here simplified) code which I want to test with FakeItEasy
I have the following code public ClassToTest : IClassToTest { private readonly DBRepository rep;
I have the following code: public class NewsEditViewDataValidator : AbstractValidator<NewsEditViewData> { public NewsEditViewDataValidator() {
I have the following code: public class OMyObject { public int Id { get;
I have the following: <p>This is a test</p> <pre>public class Car { protected Car()

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.