amir elhajjam
amir elhajjam

Reputation: 95

Mock Method of authowired bean using mockito and spring mock

I have to impelement a test for MyService that conntain two methods method1 & method2:

and the method1 call method2 (method1 --> method2 )

so i've somthing like this in my test class

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringBootApplicationTest.class)
@ContextConfiguration(classes = { conf.class })
public class CommonCAMServiceTest {

    @Autowired
    private MyService myService;

     test_method_1(){...}// this is what i want to implement and i have to mock the method2 call
     test_method_2(){...}//this work fine


... 

so i want to test my method1 but with the mock of method ( even my service class is autowired not mocked)

Thanks

Upvotes: 2

Views: 6321

Answers (3)

DwB
DwB

Reputation: 38300

Mockito supports what I will call "partial mocking"; it is called Spy.

Instead of creating a mock bean for your service, create a Spy. Also, as mentioned in other answers, don't user @Autowire for the service.

Here is some example code:

public class CommonCAMServiceTest
{
    @Spy
    private MyService myService;

    @Before
    public void before()
    {
        MockitoAnnotations.initMocks(this);

        // Mock method2 for every test.
        doReturn(something).when(myService).method2();
    }

    @Test
    public void someTestName()
    {
        // Mock method2 in this test.
        doReturn(somethingElse).when(myService).method2();

        ... call method1 to do stuff.
    }
}

Upvotes: 3

Daniel Taub
Daniel Taub

Reputation: 5379

Lets assume that your Service look like that:

@Service
public class MyService {
    public void method1() {
        method2();
    }

    public void method2() {
        System.out.println("calling method 2");
    }
}

So if you willing to Mock the method2 function you we'll need to use a Mocked Bean for that using Spring & Mockito

@MockBean // Use that instead of @Autowired, will create a Mocked Bean
public MyService service;

@Test
public void testing() {
    Mockito.doAnswer((Answer<Void>) invocation -> {
        System.out.println("mocked");

        return null;
    }).when(service).method2();


    Mockito.doCallRealMethod().when(service).method1();

    service.method1();
}

Upvotes: 0

GabrielJoerg
GabrielJoerg

Reputation: 91

Create two Services for those two Methods. Then you can mock one service to test the other.

Upvotes: 0

Related Questions