All of the controllers in our project are as dumb as we can make them. Rightfully so, they simply validate the incoming payload, hand the request over to a service layer, and return whatever response is necessary; http status code, json, etc. I’m trying to see if I can trim down the number of tests we’re writing so that I can make sure we’re covering our code but not writing waste.
For example, I have the following test:
@Test
@Throws(Exception::class)
fun `'getOne' should get 1 brand based on the id`() {
val mockName = "Test getBrand"
val brand = buildBrand(1L, mockName, organization)
`when`(this.brandRepository.findById(1L)).thenReturn(brand)
mockOrganization(1L)
this.mockMvc.perform(this.get(URL!! + "/1"))
.andDo(print())
.andExpect(status().isOk)
.andExpect(jsonPath<String>("$.name", `is`<String>(mockName)))
.andExpect(jsonPath<Int>("$.id", `is`<Int>(1)))
}
I’m struggling with the validity of this. Since we’re mocking the repository call, and the service is just a passthrough to the repository call, I feel like I’m just testing that the Spring Framework works, which I should be able to trust already. I can argue myself into asserting the expected data to be correct, but since it is mocked anyway, I don’t even feel like that is valid.
I’ve already decided to move any tests that were simply making sure @Valid
worked on the request body into pure JUnit tests that don’t require any Spring MVC harnessing at all. So I’m looking for suggestions on unit testing most basic CRUD operations. Especially given that we have unit tests over all our services.
2
There is a big debate on this whether to write tests for the code that is approximately nothing but required to make underlying framework to work.
This is what you have, a dumb Controller
that just talks to Service
. Now framework like Spring
which is very popular and battle tested then why should one has to write unit tests for the same. You should trust the framework. Sometime this is called don’t test labor’s work(framework’s work), trust it and use it.
I was also supporter of that fact until I came across TDD
(Test Driven Development) discipline. I came to know that no production code should be written before test. So test is the prerequisite for code no matter how simple and trustworthy code is.
Why is it so?
We need to understand why tests are required, if the answer is to make sure the code does what it meant to then writing tests for dumb code can be avoided but if the answer is like below:
-
I want to make sure that code does what it meant to do.
-
I want to make sure in future if any change comes to code then my test will detect it and guide me or other developer for correctness.
-
I want to make sure if in any case the version of library or framework changed in my project and that are not compatible with previous version, should be reported immediately.
-
I want to document my source code.
-
I want to have confidence in the code I have written
Then you must write tests.