Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking a service within service (JUnit)

I have the following service:

@Service
public class PlayerValidationService {

@Autowire
private EmailService emailService;


public boolean validatePlayerEmail(Player player) {
    return this.emailService.validateEmail(player.getEmail());

}

Now in my junit test class i'm using a different 3rd service that uses PlayerValidationService :

public class junit {
@autowire PlayerAccountService playerAccountService ;


@Test
public test() {
     this.playerAccountService .createAccount();
     assertAllSortsOfThings();
}

Is it possible to mock the EmailService within the PlayerAccountService when using annotation based autowiring? (for example make the mock not checking the validation of the email via the regular email provider we work with)

thanks.

like image 803
Urbanleg Avatar asked Nov 22 '25 02:11

Urbanleg


1 Answers

There are a couple of ways in which you could do this. First the simplest option is to ensure that your service provides a setEmailService(EmailService) method. In which case you just replace the Spring-injected implementation with your own.

@Autowired
private PlayerValidationService playerValidationService;

@Mock
private EmailService emailService;

@Before
public void setup() {
    initMocks(this);
    playerValidationService.setEmailService(emailService);
}

A shortcoming of that approach is that an instance of the full-blown EmailService is likely to be created by Spring. Assuming that you don't want that to happen, you can use 'profiles'.

In your test packages, create a configuration class which is only active in a particular profile:

@Configuration
@Profile("mockemail")
public class MockEmailConfig {
    @Bean(name = "emailService")
    public EmailService emailService() {
        return new MyDummyEmailService();
    }
}

And add an annotation to your test to activate that profile:

@ActiveProfiles({ "mockemail" })
public class PlayerValidationServiceTest {
    //...
}
like image 183
Steve Avatar answered Nov 24 '25 22:11

Steve