PRITAM MOHAPATRA
PRITAM MOHAPATRA

Reputation: 98

Mockito return false

I write a simple test on mokito.

public class ContactServiceTest {

    @Mock
    private ServiceClient client;

    @Mock
    private ContactService contactService;

    @Before
    public void init() {
        client = mock(ServiceClient.class);
        contactService = mock(ContactService.class);
    }

    @Test
    public void test_sendEmailContact() {
        ContactDTO cDto = new ContactDTO();
        cDto.setTitle("Mr");
        cDto.setFirstName("Pritam");
        cDto.setLastName("Mohapatra");
        cDto.setTelephone("9439586575");
        cDto.setEmail("[email protected]");
        cDto.setBetreff("test value");
        cDto.setAnfrage("test value");
        when(client.postToService("customer/sendEmailContact", cDto, Boolean.class)).thenReturn(true);
        Assert.assertEquals(true, contactService.sendEmailContact(cDto));
    }

}

Upvotes: 1

Views: 2926

Answers (1)

Nenad Bozic
Nenad Bozic

Reputation: 3784

You are probably using ServiceClient in ContactService to actually send email contact. However you defined your ContactService to be mock so you are actually testing mock instead of real class.

Option 1 prefered option if ContactService does not need to be mock:

  1. Define ContactService as real class with new ClientService
  2. Inject somehow mock of ServiceClient (via constructor or setter, you did not posted code so I do not know how they work together)
  3. Since ContactService is now real instance with injected mock of ServiceClient it will go to real method and invoke client.postToService which will return true as you defined.

Option 2 would be to do thenCallRealMethod on ContactService mock if you really need it to be mock (but I do not see why it should be mock). Something like:

when(contactService.sendEmailContact(cDto)).thenCallRealMethod();

Upvotes: 3

Related Questions