简体   繁体   English

如何在Kotlin中使用JUnit Mockito测试/模拟API

[英]How to test/mock API with JUnit Mockito in Kotlin

I am trying to wrote a Unit test in my Android application using kotlin. 我正在尝试使用kotlin在Android应用程序中编写单元测试。 getPosts() get list of POSTS from https://jsonplaceholder.typicode.com/posts getPosts()https://jsonplaceholder.typicode.com/posts获取getPosts()列表

I want to test this function comparing the count or any other way you suggest. 我想比较此计数或您建议的任何其他方式来测试此功能。

I am pretty new to this so any suggestions corrections will be very much helpful 我对此很陌生,因此任何建议的更正将非常有帮助

Here is what I have tried so far. 到目前为止,这是我尝试过的。 your help will be much appreciated. 您的帮助将不胜感激。

R [R

@Singleton
class PostsRemoteDataSource @Inject constructor(
    private val postsService: PostsService
): PostsDataSource {
       override fun getAllPosts(): Flowable<List<PostEntity>> {
        return postsService.getPosts()
            .flatMap { posts ->
                Flowable.fromIterable(posts)
                    .take(10)
                    .toList().toFlowable()
            }
    }
}

PostService 邮政服务

interface PostsService {

    @GET("/posts")
    fun getPosts(): Flowable<List<PostEntity>>
}

Testcase 测试用例

class PostsRemoteDataSourceTest {



    @Before
    fun init() {
        MockitoAnnotations.initMocks(this)
    }

    @Test
    fun getAllPosts() {
        val postService = mock(PostsService::class.java)
        val postsRemoteDataSource = PostsRemoteDataSource(postService)

        var mList = listOf<PostEntity>()

        Mockito.`when`(postService.getPosts()).thenReturn(Flowable.fromArray(mList))

        val allPosts = postsRemoteDataSource.getAllPosts()
        //PRETTY SURE THE LINE BELLOW IS WRONG I AM TRYING TO COMPARE THE 
       //COUNT BUT CANNOT GET appPosts.size as it is Flowable type
        assertEquals(allPosts , CoreMatchers.`is`(10))

    }
}

UPDATE 更新

@Test
    fun getAllPosts() {
        val postService = mock(PostsService::class.java)
        val postsRemoteDataSource = PostsRemoteDataSource(postService)

        var mList = listOf<PostEntity>(
            PostEntity(1,1,"Title 1", "Body 1"),
            PostEntity(1,1,"Title 1", "Body 1")
        )

        Mockito.`when`(postService.getPosts()).thenReturn(Flowable.fromArray(mList))

        val subsciber = postsRemoteDataSource.getAllPosts().test()


        assertEquals(subsciber.assertValueCount(10) , 10)

    }
}

Error message when I run the test 运行测试时出现错误信息


    at io.reactivex.observers.BaseTestConsumer.fail(BaseTestConsumer.java:189)
    at io.reactivex.observers.BaseTestConsumer.assertValueCount(BaseTestConsumer.java:515)
    at com.rao.com.idealarchitecture.data.remote.PostsRemoteDataSourceTest.getAllPosts(PostsRemoteDataSourceTest.kt:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Option 1 选项1

Use blockingFirst() to get data via a blocking call: 使用blockingFirst()通过阻塞调用获取数据:

val allPosts = postsRemoteDataSource.getAllPosts().blockingFirst()
assertEquals(10, allPosts.size)

Note that making blocking calls on a Flowable is usually considered bad practice in production code, but it's safe to do in tests since your object under test is backed by a mock. 请注意,在生产代码中通常对Flowable进行阻塞调用被认为是不好的做法,但是在测试中这样做是安全的,因为被测试的对象由模拟支持。

Option 2 选项2

Obtain a TestSubscriber by calling test() and assert on it: 通过调用test()获得一个TestSubscriber并对其断言:

val subscriber = postsRemoteDataSource.getAllPosts().test()
subscriber.assertValueCount(10)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM