Kotlin equivalent of Swift Expectations/Promises










1















I am trying to write some UnitTests for my native mobile applications, but have ran into a roadblock in my Android Tests. Specifically, I am struggling to find an example of Kotlin's version of Swift's Expectations/Promises..



I've found examples of Kotlin Promises, but they seem to be way more complicated than needed...



For example, here is a test for the login API function in my iOS project:



func testLogin() 

/// Prepare for login
if CURRENT_USER != nil
logout()


/// Login
let promise = expectation(description: "User is logged in.")

// 1. Given
var isSuccess: Bool = false

// 2. When
User.login(username: maleUsername, password: malePassword, success:
isSuccess = true
promise.fulfill()
) (_, agreeToTerms) in
XCTFail()

wait(for: [promise], timeout: maxTimeOut)

// 3. Then
XCTAssertNotNil(CURRENT_USER)
XCTAssertTrue(isSuccess)

/// Logout
logout()



This is pretty simple to me. I have an asynchronous method login that has two possible completion blocks: success and failure; and I need to wait for one of them to complete before evaluating. To do this, I create a promise before the call, then I fulfill the promise in the two completion blocks, and I wait for the promise to fulfill before running my assertions.



Now in Kotlin, I have a similar test:



private val loginFragment = LoginFragment()

@Test
fun loginTest()

val username = ""
val password = ""

// TODO: Create Promise

loginFragment.loginViewModel
.login(username, password)
.observe(loginFragment, Observer
loginFragment.activity?.onResult(it?.result,

onSuccess =
// TODO: Fill Promise
,
onValidationError =
// TODO: Fail Test
)
)

// TODO: Assertions




But I can't find an equivalent of swift's promises..



Does one exist in Kotlin? If not, how would I implement a version of my Swift's testLogin method in Kotlin?










share|improve this question






















  • This might help: medium.com/@tonyowen/…

    – Mike Taverne
    Nov 14 '18 at 1:48











  • The most straightforward analog of a promise on Kotlin-Android is the plain old CompletableFuture.

    – Marko Topolnik
    Nov 14 '18 at 9:03















1















I am trying to write some UnitTests for my native mobile applications, but have ran into a roadblock in my Android Tests. Specifically, I am struggling to find an example of Kotlin's version of Swift's Expectations/Promises..



I've found examples of Kotlin Promises, but they seem to be way more complicated than needed...



For example, here is a test for the login API function in my iOS project:



func testLogin() 

/// Prepare for login
if CURRENT_USER != nil
logout()


/// Login
let promise = expectation(description: "User is logged in.")

// 1. Given
var isSuccess: Bool = false

// 2. When
User.login(username: maleUsername, password: malePassword, success:
isSuccess = true
promise.fulfill()
) (_, agreeToTerms) in
XCTFail()

wait(for: [promise], timeout: maxTimeOut)

// 3. Then
XCTAssertNotNil(CURRENT_USER)
XCTAssertTrue(isSuccess)

/// Logout
logout()



This is pretty simple to me. I have an asynchronous method login that has two possible completion blocks: success and failure; and I need to wait for one of them to complete before evaluating. To do this, I create a promise before the call, then I fulfill the promise in the two completion blocks, and I wait for the promise to fulfill before running my assertions.



Now in Kotlin, I have a similar test:



private val loginFragment = LoginFragment()

@Test
fun loginTest()

val username = ""
val password = ""

// TODO: Create Promise

loginFragment.loginViewModel
.login(username, password)
.observe(loginFragment, Observer
loginFragment.activity?.onResult(it?.result,

onSuccess =
// TODO: Fill Promise
,
onValidationError =
// TODO: Fail Test
)
)

// TODO: Assertions




But I can't find an equivalent of swift's promises..



Does one exist in Kotlin? If not, how would I implement a version of my Swift's testLogin method in Kotlin?










share|improve this question






















  • This might help: medium.com/@tonyowen/…

    – Mike Taverne
    Nov 14 '18 at 1:48











  • The most straightforward analog of a promise on Kotlin-Android is the plain old CompletableFuture.

    – Marko Topolnik
    Nov 14 '18 at 9:03













1












1








1


1






I am trying to write some UnitTests for my native mobile applications, but have ran into a roadblock in my Android Tests. Specifically, I am struggling to find an example of Kotlin's version of Swift's Expectations/Promises..



I've found examples of Kotlin Promises, but they seem to be way more complicated than needed...



For example, here is a test for the login API function in my iOS project:



func testLogin() 

/// Prepare for login
if CURRENT_USER != nil
logout()


/// Login
let promise = expectation(description: "User is logged in.")

// 1. Given
var isSuccess: Bool = false

// 2. When
User.login(username: maleUsername, password: malePassword, success:
isSuccess = true
promise.fulfill()
) (_, agreeToTerms) in
XCTFail()

wait(for: [promise], timeout: maxTimeOut)

// 3. Then
XCTAssertNotNil(CURRENT_USER)
XCTAssertTrue(isSuccess)

/// Logout
logout()



This is pretty simple to me. I have an asynchronous method login that has two possible completion blocks: success and failure; and I need to wait for one of them to complete before evaluating. To do this, I create a promise before the call, then I fulfill the promise in the two completion blocks, and I wait for the promise to fulfill before running my assertions.



Now in Kotlin, I have a similar test:



private val loginFragment = LoginFragment()

@Test
fun loginTest()

val username = ""
val password = ""

// TODO: Create Promise

loginFragment.loginViewModel
.login(username, password)
.observe(loginFragment, Observer
loginFragment.activity?.onResult(it?.result,

onSuccess =
// TODO: Fill Promise
,
onValidationError =
// TODO: Fail Test
)
)

// TODO: Assertions




But I can't find an equivalent of swift's promises..



Does one exist in Kotlin? If not, how would I implement a version of my Swift's testLogin method in Kotlin?










share|improve this question














I am trying to write some UnitTests for my native mobile applications, but have ran into a roadblock in my Android Tests. Specifically, I am struggling to find an example of Kotlin's version of Swift's Expectations/Promises..



I've found examples of Kotlin Promises, but they seem to be way more complicated than needed...



For example, here is a test for the login API function in my iOS project:



func testLogin() 

/// Prepare for login
if CURRENT_USER != nil
logout()


/// Login
let promise = expectation(description: "User is logged in.")

// 1. Given
var isSuccess: Bool = false

// 2. When
User.login(username: maleUsername, password: malePassword, success:
isSuccess = true
promise.fulfill()
) (_, agreeToTerms) in
XCTFail()

wait(for: [promise], timeout: maxTimeOut)

// 3. Then
XCTAssertNotNil(CURRENT_USER)
XCTAssertTrue(isSuccess)

/// Logout
logout()



This is pretty simple to me. I have an asynchronous method login that has two possible completion blocks: success and failure; and I need to wait for one of them to complete before evaluating. To do this, I create a promise before the call, then I fulfill the promise in the two completion blocks, and I wait for the promise to fulfill before running my assertions.



Now in Kotlin, I have a similar test:



private val loginFragment = LoginFragment()

@Test
fun loginTest()

val username = ""
val password = ""

// TODO: Create Promise

loginFragment.loginViewModel
.login(username, password)
.observe(loginFragment, Observer
loginFragment.activity?.onResult(it?.result,

onSuccess =
// TODO: Fill Promise
,
onValidationError =
// TODO: Fail Test
)
)

// TODO: Assertions




But I can't find an equivalent of swift's promises..



Does one exist in Kotlin? If not, how would I implement a version of my Swift's testLogin method in Kotlin?







swift unit-testing kotlin promise






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 13 '18 at 23:34









BlondeSwanBlondeSwan

1198




1198












  • This might help: medium.com/@tonyowen/…

    – Mike Taverne
    Nov 14 '18 at 1:48











  • The most straightforward analog of a promise on Kotlin-Android is the plain old CompletableFuture.

    – Marko Topolnik
    Nov 14 '18 at 9:03

















  • This might help: medium.com/@tonyowen/…

    – Mike Taverne
    Nov 14 '18 at 1:48











  • The most straightforward analog of a promise on Kotlin-Android is the plain old CompletableFuture.

    – Marko Topolnik
    Nov 14 '18 at 9:03
















This might help: medium.com/@tonyowen/…

– Mike Taverne
Nov 14 '18 at 1:48





This might help: medium.com/@tonyowen/…

– Mike Taverne
Nov 14 '18 at 1:48













The most straightforward analog of a promise on Kotlin-Android is the plain old CompletableFuture.

– Marko Topolnik
Nov 14 '18 at 9:03





The most straightforward analog of a promise on Kotlin-Android is the plain old CompletableFuture.

– Marko Topolnik
Nov 14 '18 at 9:03












1 Answer
1






active

oldest

votes


















0














You can use Kotlin coroutines, for example:



@Test
fun loginTest()
val result = runBlocking
val loginResult = login()
loginResult

if (result == "Success")
// do your work when Success
else
// do your work when Error


suspend fun login(): String = suspendCoroutine continuation ->
val username = ""
val password = ""
loginFragment.loginViewModel
.login(username, password)
.observe(loginFragment, Observer
loginFragment.activity?.onResult(it?.result,

onSuccess =
continuation.resume("Success")
,
onValidationError =
continuation.resume("Error") // take a look for other methods, e.g. resumeWithException(exception)

)
)



To use coroutines you need to add next lines to app's build.gradle file dependencies:




final KOTLIN_COROUTINES_VERSION = '1.0.1'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$KOTLIN_COROUTINES_VERSION"



Hope it will help.






share|improve this answer

























  • Thanks for the information. So if I were to use this, I would essentially have to write a suspend function and a function that runs the suspend function for every test?

    – BlondeSwan
    Nov 14 '18 at 16:09











  • Yes, the code is more clear and readable that way. You can try avoid of creating of login() method by moving suspendCoroutine block inside runBlocking , but there will be some mess in the code.

    – Sergey
    Nov 14 '18 at 16:51











  • Talk about the lesser of two evils... haha.

    – BlondeSwan
    Nov 14 '18 at 16:53











  • I prefer to create a new method with suspendCoroutine block :)

    – Sergey
    Nov 14 '18 at 16:56











  • I'll be doing separate methods. Kotlin is kinda lame in the sense that you have to choose between (A) concise, but complicated, ultra-nested, messy code or (B) expansive, but simple, readable, clean code. Swift seems to be both clean and concise

    – BlondeSwan
    Nov 14 '18 at 17:04










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53291051%2fkotlin-equivalent-of-swift-expectations-promises%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














You can use Kotlin coroutines, for example:



@Test
fun loginTest()
val result = runBlocking
val loginResult = login()
loginResult

if (result == "Success")
// do your work when Success
else
// do your work when Error


suspend fun login(): String = suspendCoroutine continuation ->
val username = ""
val password = ""
loginFragment.loginViewModel
.login(username, password)
.observe(loginFragment, Observer
loginFragment.activity?.onResult(it?.result,

onSuccess =
continuation.resume("Success")
,
onValidationError =
continuation.resume("Error") // take a look for other methods, e.g. resumeWithException(exception)

)
)



To use coroutines you need to add next lines to app's build.gradle file dependencies:




final KOTLIN_COROUTINES_VERSION = '1.0.1'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$KOTLIN_COROUTINES_VERSION"



Hope it will help.






share|improve this answer

























  • Thanks for the information. So if I were to use this, I would essentially have to write a suspend function and a function that runs the suspend function for every test?

    – BlondeSwan
    Nov 14 '18 at 16:09











  • Yes, the code is more clear and readable that way. You can try avoid of creating of login() method by moving suspendCoroutine block inside runBlocking , but there will be some mess in the code.

    – Sergey
    Nov 14 '18 at 16:51











  • Talk about the lesser of two evils... haha.

    – BlondeSwan
    Nov 14 '18 at 16:53











  • I prefer to create a new method with suspendCoroutine block :)

    – Sergey
    Nov 14 '18 at 16:56











  • I'll be doing separate methods. Kotlin is kinda lame in the sense that you have to choose between (A) concise, but complicated, ultra-nested, messy code or (B) expansive, but simple, readable, clean code. Swift seems to be both clean and concise

    – BlondeSwan
    Nov 14 '18 at 17:04















0














You can use Kotlin coroutines, for example:



@Test
fun loginTest()
val result = runBlocking
val loginResult = login()
loginResult

if (result == "Success")
// do your work when Success
else
// do your work when Error


suspend fun login(): String = suspendCoroutine continuation ->
val username = ""
val password = ""
loginFragment.loginViewModel
.login(username, password)
.observe(loginFragment, Observer
loginFragment.activity?.onResult(it?.result,

onSuccess =
continuation.resume("Success")
,
onValidationError =
continuation.resume("Error") // take a look for other methods, e.g. resumeWithException(exception)

)
)



To use coroutines you need to add next lines to app's build.gradle file dependencies:




final KOTLIN_COROUTINES_VERSION = '1.0.1'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$KOTLIN_COROUTINES_VERSION"



Hope it will help.






share|improve this answer

























  • Thanks for the information. So if I were to use this, I would essentially have to write a suspend function and a function that runs the suspend function for every test?

    – BlondeSwan
    Nov 14 '18 at 16:09











  • Yes, the code is more clear and readable that way. You can try avoid of creating of login() method by moving suspendCoroutine block inside runBlocking , but there will be some mess in the code.

    – Sergey
    Nov 14 '18 at 16:51











  • Talk about the lesser of two evils... haha.

    – BlondeSwan
    Nov 14 '18 at 16:53











  • I prefer to create a new method with suspendCoroutine block :)

    – Sergey
    Nov 14 '18 at 16:56











  • I'll be doing separate methods. Kotlin is kinda lame in the sense that you have to choose between (A) concise, but complicated, ultra-nested, messy code or (B) expansive, but simple, readable, clean code. Swift seems to be both clean and concise

    – BlondeSwan
    Nov 14 '18 at 17:04













0












0








0







You can use Kotlin coroutines, for example:



@Test
fun loginTest()
val result = runBlocking
val loginResult = login()
loginResult

if (result == "Success")
// do your work when Success
else
// do your work when Error


suspend fun login(): String = suspendCoroutine continuation ->
val username = ""
val password = ""
loginFragment.loginViewModel
.login(username, password)
.observe(loginFragment, Observer
loginFragment.activity?.onResult(it?.result,

onSuccess =
continuation.resume("Success")
,
onValidationError =
continuation.resume("Error") // take a look for other methods, e.g. resumeWithException(exception)

)
)



To use coroutines you need to add next lines to app's build.gradle file dependencies:




final KOTLIN_COROUTINES_VERSION = '1.0.1'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$KOTLIN_COROUTINES_VERSION"



Hope it will help.






share|improve this answer















You can use Kotlin coroutines, for example:



@Test
fun loginTest()
val result = runBlocking
val loginResult = login()
loginResult

if (result == "Success")
// do your work when Success
else
// do your work when Error


suspend fun login(): String = suspendCoroutine continuation ->
val username = ""
val password = ""
loginFragment.loginViewModel
.login(username, password)
.observe(loginFragment, Observer
loginFragment.activity?.onResult(it?.result,

onSuccess =
continuation.resume("Success")
,
onValidationError =
continuation.resume("Error") // take a look for other methods, e.g. resumeWithException(exception)

)
)



To use coroutines you need to add next lines to app's build.gradle file dependencies:




final KOTLIN_COROUTINES_VERSION = '1.0.1'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$KOTLIN_COROUTINES_VERSION"



Hope it will help.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 15 '18 at 20:33

























answered Nov 14 '18 at 4:46









SergeySergey

3,93021734




3,93021734












  • Thanks for the information. So if I were to use this, I would essentially have to write a suspend function and a function that runs the suspend function for every test?

    – BlondeSwan
    Nov 14 '18 at 16:09











  • Yes, the code is more clear and readable that way. You can try avoid of creating of login() method by moving suspendCoroutine block inside runBlocking , but there will be some mess in the code.

    – Sergey
    Nov 14 '18 at 16:51











  • Talk about the lesser of two evils... haha.

    – BlondeSwan
    Nov 14 '18 at 16:53











  • I prefer to create a new method with suspendCoroutine block :)

    – Sergey
    Nov 14 '18 at 16:56











  • I'll be doing separate methods. Kotlin is kinda lame in the sense that you have to choose between (A) concise, but complicated, ultra-nested, messy code or (B) expansive, but simple, readable, clean code. Swift seems to be both clean and concise

    – BlondeSwan
    Nov 14 '18 at 17:04

















  • Thanks for the information. So if I were to use this, I would essentially have to write a suspend function and a function that runs the suspend function for every test?

    – BlondeSwan
    Nov 14 '18 at 16:09











  • Yes, the code is more clear and readable that way. You can try avoid of creating of login() method by moving suspendCoroutine block inside runBlocking , but there will be some mess in the code.

    – Sergey
    Nov 14 '18 at 16:51











  • Talk about the lesser of two evils... haha.

    – BlondeSwan
    Nov 14 '18 at 16:53











  • I prefer to create a new method with suspendCoroutine block :)

    – Sergey
    Nov 14 '18 at 16:56











  • I'll be doing separate methods. Kotlin is kinda lame in the sense that you have to choose between (A) concise, but complicated, ultra-nested, messy code or (B) expansive, but simple, readable, clean code. Swift seems to be both clean and concise

    – BlondeSwan
    Nov 14 '18 at 17:04
















Thanks for the information. So if I were to use this, I would essentially have to write a suspend function and a function that runs the suspend function for every test?

– BlondeSwan
Nov 14 '18 at 16:09





Thanks for the information. So if I were to use this, I would essentially have to write a suspend function and a function that runs the suspend function for every test?

– BlondeSwan
Nov 14 '18 at 16:09













Yes, the code is more clear and readable that way. You can try avoid of creating of login() method by moving suspendCoroutine block inside runBlocking , but there will be some mess in the code.

– Sergey
Nov 14 '18 at 16:51





Yes, the code is more clear and readable that way. You can try avoid of creating of login() method by moving suspendCoroutine block inside runBlocking , but there will be some mess in the code.

– Sergey
Nov 14 '18 at 16:51













Talk about the lesser of two evils... haha.

– BlondeSwan
Nov 14 '18 at 16:53





Talk about the lesser of two evils... haha.

– BlondeSwan
Nov 14 '18 at 16:53













I prefer to create a new method with suspendCoroutine block :)

– Sergey
Nov 14 '18 at 16:56





I prefer to create a new method with suspendCoroutine block :)

– Sergey
Nov 14 '18 at 16:56













I'll be doing separate methods. Kotlin is kinda lame in the sense that you have to choose between (A) concise, but complicated, ultra-nested, messy code or (B) expansive, but simple, readable, clean code. Swift seems to be both clean and concise

– BlondeSwan
Nov 14 '18 at 17:04





I'll be doing separate methods. Kotlin is kinda lame in the sense that you have to choose between (A) concise, but complicated, ultra-nested, messy code or (B) expansive, but simple, readable, clean code. Swift seems to be both clean and concise

– BlondeSwan
Nov 14 '18 at 17:04



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53291051%2fkotlin-equivalent-of-swift-expectations-promises%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Use pre created SQLite database for Android project in kotlin

Darth Vader #20

Ondo