Тестирование конечных точек и сервисного уровня Kotlin Spring Boot с использованием слоя репозитория - PullRequest
1 голос
/ 09 ноября 2019

Для тестирования конечных точек я использую JUnit с SpringRunner и @WebMvcTest

@RunWith(SpringRunner::class)
@WebMvcTest(UserEndpoints::class)
class UserEndpointsTest {
}

UserEndpoints зависит от UserSevice

UserService зависит от UserRepository

Я бы посмеялся UserRepository, чтобы проверить UserEndpoints

@RunWith(SpringRunner::class)
@WebMvcTest(UserEndpoints::class)
class UserEndpointsTest2 {

    @Autowired
    private val mockMvc:MockMvc?=null

    @MockBean
    private val userRepository:UserRepository?=null

    @InjectMocks
    private var userService:UserService?=null

    @Before
    fun setup() {
        initMocks(this)

        Mockito.`when`(userRepository !!.findById(eq("1")))
                .thenReturn(Optional.of(users().get(0)))

        Mockito.`when`(userRepository.findById(eq("2"))).thenReturn(Optional.of(users().get(1)))
    }

    @Test
    fun testGetUser() {
        this.mockMvc!!.perform(get("/user").param("id", "2"))
                .andExpect(MockMvcResultMatchers.status().isOk)
                .andExpect(MockMvcResultMatchers.jsonPath("$.username").value(Matchers.equalTo("username1")))
                .andExpect(MockMvcResultMatchers.jsonPath("$.remaining_requests").value(Matchers.equalTo(101)))
                .andExpect(MockMvcResultMatchers.jsonPath("$.type").value(Matchers.equalTo("USER")))
    }

    fun users(): List<User> {
        val user1 = User("1", "username", "password", "123", 100, UserType.BETA)
        val user2 = User("2", "username1", "password1", "1234", 101, UserType.USER)
        return arrayListOf<User>(user1, user2)
    }

    private fun <T> any(type: Class<T>): T {
        Mockito.any(type)
        return null as T
    }
}

Проблема в том, что не работает, потому что нет repositoryBean для инъекции в userService bean.

Не удается с

org.mockito.exceptions.misusing.InjectMocksException: 
Cannot instantiate @InjectMocks field named 'userService' of type 'class service.UserService'.
You haven't provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : Parameter specified as non-null is null: method service.UserService.<init>, parameter userRepository

Как правильно корректировать слой репозитория?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...