如何使用Constructor注入来制作mockito测试用例



我想用mockito 制作junit测试用例

有课。

MyProps : the properties data class @Configuration
MyService : my main logic @Service class
MyClient : webClient class @Component

如何用mockito测试myService结果逻辑??以及如何简单地制作数据类(MyProps(???

错误如下:您还没有在字段声明中提供实例,所以我尝试构造该实例。然而,构造函数或初始化块引发了异常:指定为非null的参数为null:

@Configuration
@ConfigurationProperties("application.something")
class MyProps {
lateinit var broker: String
lateinit var url: String
}
@Service
class MyService(private val client: MyClient,
private val myProps: MyProps
){
fun getReulst(params: Params): Flux<MyEntity> {
// some logic, and I want check this part result
return client.get(params)
}
}
@Component
class MyClient(val myProps: MyProps) {
private val webClient: WebClient = WebClient.create()
fun get(params: Params): Flux<MyEntity> {
val params = BodyInserters.fromValue(query)
return webClient
.post()
.uri(myProps.broker)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.body(params)
.retrieve()
.bodyToFlux(MyEntity::class.java)
}
}

这是测试代码


//----------------
@SpringBootTest(classes = [MyService::class, MyProps::class, MyClient::class])
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class MyServiceTest {
@MockBean
private lateinit var myProps: MyProps
@MockBean
private lateinit var myClient: MyClient
@InjectMocks
private lateinit var countService: MyService

@BeforeEach
fun mock() {
given(myProps.broker).willReturn("http://url.com")
given(myProps.web).willReturn("something")
given(myClient.get2(query)).willReturn(
Flux.fromIterable(listOf(
MyEntity("2020-03-22", Count(1)),
MyEntity("2020-03-23", Count(2)),
MyEntity("2020-03-24", Count(3)),
MyEntity("2020-03-25", Count(6)),
MyEntity("2020-03-26", Count(5)),
MyEntity("2020-03-27", Count(4))
))
)
MockitoAnnotations.initMocks(this)
}
@Test
fun `I want to check!! here`(){
val param = Params(1,2,3) // some params
myService.getReulst(param).subscribe() // <-  here is error maybe param is null... why??
}
}

由于您将mock注入到服务中,因此实际上不需要全面的春季启动测试。这将使您的测试更快。

此外,由于您在嘲笑MyClient,所以您并没有真正调用它的代码。因此,CCD_ 2中发生的任何事情在这里都可以忽略。你将在它自己的测试中涵盖它。

以下是我如何用JUnit5编写这个测试(如果你还在使用它,你必须将它翻译成JUnit4(:

@ExtendWith(MockitoExtension::class)
class MyServiceTest(
@Mock val myProps: MyProps,
@Mock val myClient: MyClient
) {
// you can use @InjectMocks if you prefer
val countService: MyService = MyService(myProps, myClient)
@BeforeEach
fun mock() {
// you only need these if they're called in MyService
`when`(myProps.broker).thenReturn("http://url.com")
`when`(myProps.web).thenReturn("something")
`when`(myClient.get(Params(1,2,3))).thenReturn(
Flux.fromIterable(listOf(
MyEntity("2020-03-22", Count(1)),
MyEntity("2020-03-23", Count(2)),
MyEntity("2020-03-24", Count(3)),
MyEntity("2020-03-25", Count(6)),
MyEntity("2020-03-26", Count(5)),
MyEntity("2020-03-27", Count(4))
))
)
}
@Test
fun `I want to check!! here`(){
val param = Params(1,2,3)
myService.getReulst(param).subscribe()
}
}

最新更新