Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing Spring Boot application Service layer

I'm a bit confused about the test capabilities and utilities provided by Spring Boot.

I'm using spring-boot-starter-test in my project and I'd like to unit test my services without the database connection

At the moment I'm using @WebMvcTest for contoller test suites and @SpringBootTest for all the other test classes.

But I read somewhere that @SpringBootTest is meant to be used only in integration tests...

Reading documentation I didn't understood what's the suggested approach for services. Should I only test them in integration with repos?

UPDATE

That's an excerpt of a test class for one of my services:

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@SpringBootTest
internal class SignupServiceTest(
        @Autowired val signupService: SignupService
) {
    @MockkBean
    lateinit var userRepository: UserRepository

    @Test
    fun `should return exception if username already used`() {
        every { userRepository.findByUsername("registered-user") } returns fakeUser(username = "registered-user")

        assertThatThrownBy {
            signupService.createNewAccount(fakeSignupForm(username = "registered-user"))
        }.isExactlyInstanceOf(UsernameNotAvailableException::class.java)
    }

    // ... other tests

}
like image 549
davioooh Avatar asked Oct 23 '25 02:10

davioooh


1 Answers

Using @SpringBootTest for unit tests is a bit of a overkill. Because this would boot up the whole application context.

To test individual (service) classes I would go with @RunWith(MockitoJUnitRunner.class) and instead of @Autowired and @MockBean use @Mock and @InjectMocks(If you use constructor injection, you wouldn't have to use this. which would be the better option)

You could still use @Autowired with @ContextConfiguration and load specific classes(if there are not too many transitive dependencies)

If you do not want to use mocks, then you can use embedded databases and use @DataMongoTest or @DataJpaTest and use Springboot testing capabilities.

Keep it simple....

like image 61
pvpkiran Avatar answered Oct 24 '25 17:10

pvpkiran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!