user8914226
user8914226

Reputation:

Mocking a method for @InjectMocks in Spring

I facing the following problem. I want to mock a method which is inside the class which I want to test. Consider for the following example.

ExampleClass(){
    method1DependsOnMethod2(){
        // some code

        method2(){
            // some code

        }
    }
}

Now I want to test method1DependsOnMethod2 which depends on method2 but I want to mock the result of method2 to test only method1DependsOnMethod2.

I tried the following

@InjectMocks
@Spy
ExampleClass exampleClass

when(exampleClass.method2()).thenReturn()

or

doReturn(..).when(exampleClassmethod()).method2()

I also tried to use two instances

@InjectMocks
ExampleClass exampleClass
@Mock
ExampleClass exampleClassMock

but none of the approaches results in the desired.

I am thankful for any help

Greetings Matthias

Upvotes: 0

Views: 356

Answers (1)

user8914226
user8914226

Reputation:

as Dawood ibn Kareem mentioned, it works with @Spy.

I have to remove the @InjectMocks annotation, as WildDev mentioned, otherwise it seems that the "injected version" wants to initialize everything in the called method and do not mock it properly.

Furthermore I have to use

doReturn(bla).when(exampleClass).method1DependsOnMethod2(); 

I tried it with

when(exampleClass.method1DependsOnMethod2()).thenReturn(bla); 

but this was also not working.

Thanks Dawood ibn Kareem and WildDev for your help.

Greetings Matthias

Upvotes: 1

Related Questions