为了测试端点,我将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
模拟存储库层的正确方法是什么?