jeudi 26 juillet 2018

Testing in Spring project - injecting repository into service with Mockito

I'm trying to understand how to use Mockito in a Spring project, but I'm a bit stuck with the following:

I'm about to test a service with a real (in-memory) repository. I'm mocking every other object that's being used by that service. If I understand correctly, annotating an object with @Mock will be mocked, @Spy will use a real object, and with @InjectMocks will kind of "autowire" these annotated objects. However, I think I misunderstood @Spy, because the following code is not working:

@SpringBootTest
@RunWith(SpringRunner.class)
public class UserServiceTests {

    @Spy
    @Autowired
    private UserRepository userRepository;

    @Mock
    private MessageService messageService;

    @InjectMocks
    private UserService userService = new UserServiceImpl();

    @Test
    public void testUserRegistration() {
        userService.registerUser("test@test.test");

        Assert.assertEquals("There is one user in the repository after the first registration.", 1, userRepository.count());
    }

}

If I remove the @Spy annotation and insert the repository in the service with reflection, it works:

ReflectionTestUtils.setField(userService, "userRepository", userRepository);

This seems inconvenient, and I'm pretty sure that @Spy is meant to do this. Can anyone point out what I'm missing/misunderstanding?

Aucun commentaire:

Enregistrer un commentaire