-1

I am totally new to Mockito and Software Testing in Java. This is the pseudocode:

class serviceX()
{
   void seedCounter(Apple apple)
   {
    
    Seed seeds = apple.getSeeds(where seed colour is red)
    (if seeds is not null) print("found red seeds")
    else print("found nothing")
   }
   
}

getSeeds is a class method of Apple class. Now I want to test seedCounter. I want to test a scene where I assume(something like mockito.when(i send an apple with red seeds).thenReturn(notNull)) that i send an apple with red coloured seeds. How do i create a mock scene out of this? I want to test if i am getting "found red seeds" as an output or not.

2 Answers2

0

I guess you want to mock the passed apple in your service method, so you can define the return value of your getSeeds. Something like this

Apple mockedApple = Mockito.mock(Apple.class); // retrieve a mocked instance of apple

// when mockedApple.getSeeds("where seed colour is red") is called, "Red seeds" will be returned
Mockito.when(mockedApple.getSeeds(Mockito.eq("where seed colour is red"))).thenReturn("Red seeds");

assertEquals("Red seeds", mockedApple.getSeeds("where seed colour is red"));
// serviceX.seedCounter(mockedApple);

See also https://stackoverflow.com/a/14970545/9479695

smotastic
  • 388
  • 1
  • 11
  • What is this actually testing? It's basically `assertThat(true)`. The method OP wants to test is `seedCounter` – thinkgruen Aug 17 '21 at 07:53
  • Yes, the assert was just for proving that it is actually mocked. Of course (as shown in the code) he has to now call his seedCounter Method to actually test his implementation – smotastic Aug 17 '21 at 08:11
-1

You can follow the documentation in this link for know about mock with Mockito

https://www.baeldung.com/mockito-annotations

I try to show you with your pseudo code :

@RunWith(MockitoJUnitRunner.class)
public class ServiceXTest {

    @Mock
    private Apple apple;

    @InjectMocks
    private ServiceX serviceX;

    @Test
    public void should_seed_cound() {
        // given
        Seed seed = new Seed();
        Mockito.when(apple.getSeeds()).thenReturn(seed);
        // when
        serviceX.seedCounter(apple);
        // do Stuff here
    }
}

The @Mock annotation create a mock object for you. Don't forgot to put @RunWith(MockitoJUnitRunner.class) on you class

  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/29607225) – dm2 Aug 17 '21 at 07:08
  • 1
    Ok I edit my answer with more informations and code exemple. Thank – Dupeyrat Kevin Aug 17 '21 at 07:50