MockWebServer-值计数不同;预期:1,实际:0

时间:2019-02-07 07:40:24

标签: android unit-testing kotlin mocking mockwebserver

Logcat错误:

  

2019年2月7日上午10:52:49 okhttp3.mockwebserver.MockWebServer $ 2执行

     

信息:MockWebServer [54845]开始接受连接

     

[size = 9333 text = [\ n {\ n“ userId”:1,\ n“ id”:1,\ n“ title”:“ quidem molesti…]   2019年2月7日10:52:49 ok okhttp3.mockwebserver.MockWebServer $ 3 processOneRequest

     

信息:MockWebServer [54845]收到请求:GET / albums?userId = HTTP / 1.1并响应:HTTP / 1.1 200 OK

     

2019年2月7日上午10:52:51 okhttp3.mockwebserver.MockWebServer $ 2 acceptConnections   INFO:MockWebServer [54845]完成接受连接:套接字已关闭

     

java.lang.AssertionError:值计数不同;预期值:1,实际值:0(闩锁= 1,值= 0,错误= 0,完成次数= 0,超时!)

     

在io.reactivex.observers.BaseTestConsumer.fail(BaseTestConsumer.java:189)       在io.reactivex.observers.BaseTestConsumer.assertValueCount(BaseTestConsumer.java:515)       在ir.hosseinabbasi.tdd.dao.TestAlbumDaoViaMockWebService.get从模拟服务器获取相册列表(TestAlbumDaoViaMockWebService.kt:58)

系统打印输出:

[size=9333 text=[\n  {\n    "userId": 1,\n    "id": 1,\n    "title": "quidem molesti…]

测试课程:

@RunWith(JUnit4::class)
class TestAlbumDaoViaMockWebService {

    lateinit var albumDao: AlbumDao
    lateinit var mockWebServer: MockWebServer

    @Before
    @Throws
    fun setup() {
        mockWebServer = MockWebServer()
        mockWebServer.start()

        val okHttpClient = OkHttpClient.Builder().build()
        val retrofit = Retrofit.Builder()
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .baseUrl(mockWebServer.url("/").toString())
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build()

        albumDao = retrofit.create(AlbumDao::class.java)
    }

    @Test
    fun `get list of albums from mocked server`() {
        val testObserver = TestObserver<List<AlbumDto>>()
        val path = "/albums?userId="
        val mockResponse = MockResponse()
            .setResponseCode(200)
            .setBody(getJson("json/albums.json"))
        System.out.println(mockResponse.body.toString())

        mockWebServer.enqueue(mockResponse)
        albumDao.getAlbums("").subscribe()
        testObserver.awaitTerminalEvent(2, TimeUnit.SECONDS)

        testObserver.assertNoErrors()
        testObserver.assertValueCount(1) //Error on this line

        val request = mockWebServer.takeRequest()

        assertEquals(path, request.path)
    }

    @After
    @Throws
    fun tearDown() {
        mockWebServer.shutdown()
    }
}

albums.json:

[
  {
    "userId": 1,
    "id": 1,
    "title": "quidem molestiae enim"
  },
  ...and etc...
  ,{
    "userId": 10,
    "id": 100,
    "title": "enim repellat iste"
  }
]

getJson方法:

class Utils {
    companion object {
        fun getJson(path: String): String {
            val uri = this.javaClass.classLoader.getResource(path)
            val file = File(uri.path)
            return String(file.readBytes())
        }
    }
}

我的应用模块中的BuildConfig:

buildConfigField("String", "BASE_URL", "\"https://jsonplaceholder.typicode.com\"")

在我的“应用”模块中进行改造:

class NetDao {

    fun provideRetrofit(): Retrofit =
        Retrofit.Builder()
            .baseUrl(BuildConfig.BASE_URL)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
}

MockWebServer版本: 3.12.1

如果我对此行发表评论,则测试通过: testObserver.assertValueCount(1)

1 个答案:

答案 0 :(得分:1)

我认为您忘记设置

albumDao.getAlbums("").subscribe(TEST_OBSERVER_HERE)

我创建并测试了它。它与给观察者订阅方法一起工作。但是,如果您没有给出与您相同的错误。

@RunWith(AndroidJUnit4::class)
class ApiTest {

@Test
fun jsonPlaceholderTest() {

    val mockWebServer = MockWebServer()
    mockWebServer.start()

    val okHttpClient = OkHttpClient.Builder().build()
    val retrofit = Retrofit.Builder()
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .baseUrl(mockWebServer.url("/").toString())
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build()

    val service = retrofit.create(ServiceInterface::class.java)

    mockWebServer.enqueue(
            MockResponse()
                    .setResponseCode(200)
                    .setBody("[\n" +
                            "  {\n" +
                            "    \"userId\": 1,\n" +
                            "    \"id\": 1,\n" +
                            "    \"title\": \"sunt aut facere repellat  provident occaecati excepturi optio reprehenderit\",\n" +
                            "    \"body\": \"quia et suscipit\\nsuscipit recusandae consequuntur expedita et cum\\nreprehenderit molestiae ut ut quas totam\\nnostrum rerum est autem sunt rem eveniet architecto\"\n" +
                            "  },\n" +
                            "  {\n" +
                            "    \"userId\": 1,\n" +
                            "    \"id\": 2,\n" +
                            "    \"title\": \"qui est esse\",\n" +
                            "    \"body\": \"est rerum tempore vitae\\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\\nqui aperiam non debitis possimus qui neque nisi nulla\"\n" +
                            "  }\n" +
                            "]")
    )

    val testObserver = TestObserver<List<JsonPlaceHolderResponse>>()

    service.test("https://jsonplaceholder.typicode.com/posts").subscribe(testObserver)

    testObserver.awaitTerminalEvent(2, TimeUnit.SECONDS)

    testObserver.assertValueCount(1)

}
}

interface ServiceInterface {
    @GET
    fun test(@Url url : String): io.reactivex.Observable<List<JsonPlaceHolderResponse>>
}

data class JsonPlaceHolderResponse(
    var userId: Int = 0,
    var id: Int = 0,
    var title: String = "",
    var body: String = ""
)