1

i want mock only one function on a real service, this is Injected via @Autowired (Integration Test) ->

@SpringBootTest(classes = OrderitBackendApp.class)
@ExtendWith(MockitoExtension.class)
@AutoConfigureMockMvc
@WithUserDetails
public class OrderResourceIT {

    @Autowired
    private OrderRepository orderRepository;
    
    ...mor Injections and Tests

Here the mock functionalty ->

    @BeforeEach
    public void initTest() {
        MockitoAnnotations.initMocks(this);
        order = createEntity(em);
        OrderService spy = spy(orderService);
        when(spy.priceIsIncorrect(any())).thenReturn(false);
    }

But this and a few other things that i tried didnt work. What is the right way to do it ?

Yusuf Azal
  • 218
  • 1
  • 14

3 Answers3

2

Suppose we have some class with two methods

    public class OrderService {

    public String priceIsIncorrect(){
        return "price";
    }

    public String someOtherMethod(){
        return "other price";
    }
}

Following test class will mock one method and use real implementation of second method:

public class SomeRandomTest {
    private OrderService orderService = new OrderService();
    @Test
    public void test(){
        OrderService spy = Mockito.spy(orderService);
        Mockito.when(spy.priceIsIncorrect()).thenReturn("Spied method");
        System.out.println(spy.priceIsIncorrect()); //will return "Spied method"
        System.out.println(spy.someOtherMethod()); //will return "other price"

    }
}
Neplooho
  • 21
  • 2
  • 1
    This is not working with @Autowired :(. I need it, because its a integration Test – Yusuf Azal Jan 25 '21 at 16:14
  • have you tried this? https://stackoverflow.com/questions/44455572/using-spy-and-autowired-together – Neplooho Jan 25 '21 at 16:21
  • it might be that you are creating local spy in before step of each step but later in test you are referencing real (global) autowired object – Neplooho Jan 25 '21 at 16:26
1

Try using @InjectMocks and @Mock annotations if you are using Mockito. Look at the example below https://www.springboottutorial.com/spring-boot-unit-testing-and-mocking-with-mockito-and-junit

gcpdev-guy
  • 460
  • 1
  • 10
  • 23
1

What I am missing is the key point where your OrderService gets injected to the system under test (sut).

So there are two options:

  1. Using Reflection to set the OrderService spy instance to the sut
  2. IMHO best approach is to try @SpyBean on your OrderService instancs which AFAIR allows Spies to be used within you Applicationcontext. Give it a try. I'll need to studie the docs later. Maybe I am wrong.

Further: Where does the order service gets invoked within your application? For me this is not clear based on the provided code.