I am very new to Kotlin.
I have a class that calls a top level function (which makes a http call). I am trying to write unit tests for my class without having it go out to the network.
Is there a way to mock/powermock/intercept the call from my class to the Kotlin top level function?
class MyClass {
fun someMethod() {
// do some stuff
"http://somedomain.com/some-rest/action".httpGet(asList("someKey" to "someValue")).responseString { (request, response, result) ->
// some processing code
}
}
}
It is using the kittinunf/Fuel library for the httpGet call.
It adds a top level function to String that ultimately calls a companion object function in Fuel (Fuel.get()).
The unit test needs to intercept the call to httpGet so that I can return a json string for the test.
I encourage you to encapsulate remote API calls behind an interface that would be injected through constructor to the class using it:
class ResponseDto
interface SomeRest {
fun action(data:Map<String,Any?>): ((ResponseDto)->Unit)->Unit
}
class FuelTests(val someRest: SomeRest) {
fun callHttp(){
someRest.action(mapOf("question" to "answer")).invoke { it:ResponseDto ->
// do something with response
}
}
}
Another way is to to inject a fake Client to be used by Fuel:
FuelManager.instance.client = object: Client {
override fun executeRequest(request: Request): Response {
return Response().apply {
url = request.url
httpStatusCode = 201
}
}
}
Fuel.testMode()
"http://somedomain.com/some-rest/action".httpGet(listOf()).responseString { request, response, result ->
print(response.httpStatusCode) // prints 201
}
It seems that "top level functions" can be seen as static methods in disguise.
And from that point of view, the better answer is: do not use them in such a way. This leads to high, direct coupling; and makes your code harder to test. You definitely want to create some interface Service which all your objects should be using; and then use use dependency injection to equip your client code with some object that implements the Service interface.
By doing so, you also get rid of the requirement to Powermock completely.
Related
I'm trying to use Mockk to mock a method with context receiver:
class MyClass {
// The method I'm going to mock
context(CallContext)
fun myMethod(a: Int) Int { a }
}
It's hard to get the instance of CallContext in the unit test. So I hope I can write a unit test in this way:
/*
This should work, but I can't get the CallContext instance
with(callContextInstance) {
Every { mockedMyClass.myMethod(1) } returns 2
}
*/
// I hope a unit test can be written like this... But it won't compile now.
with(any<CallContext>) {
Every { mockedMyClass.myMethod(1) } returns 2
}
So what should I do? Thanks in advance.
At the time of writing, MockK does not support context receivers, and it probably won't until context receivers are released - so some time after Kotlin 1.9, so maybe in 2024).
(Context receivers are explicitly described as not ready for production. A stable release won't be available until after the K2 release, and the K2 beta is targeted for Kotlin 1.9, which has a planned release of December 2023.)
That said, if anyone wants to attempt support, then get stuck in! MockK is an community supported open source project that accepts PRs.
Confounding factors
However, there are two hinderances before MockK can fully support context receivers:
Context receivers aren't finished, nor is their current implementation stable. KT-10468. Their implementation could change significantly. Trying to implement support for a moving target is challenging.
IDE support is limited, which makes developing with them difficult (follow KTIJ-20857 for updates)
Workaround
In the meantime, you could adjust your code to allow for manual mocking.
First, adjust MyClass to either be an open class, or introduce a new interface that describes the behaviour you want to mock (code to an interface).
/** Describe the API that [MyClass] will implement */
interface MyClassSpec {
context(CallContext)
fun myMethod(a: Int): Int
}
And then implement the interface
/** Concrete implementation of [MyClassSpec] */
class MyClass: MyClassSpec {
context(CallContext)
override fun myMethod(a: Int): Int = a
}
Now in your test you can create a mock by creating an anonymous object that implements MyClassSpec - and now you have a mock that supports context receivers.
#Test
fun myTest() {
val myClassMock = object : MyClassSpec {
context(CallContext)
override fun myMethod(a: Int): Int = 123
}
}
If I get the idea what exactly do you try to mock, the following works with mockk 1.13.3:
interface CallContext
class MyClass {
context(CallContext)
fun myMethod(a: Int): Int = a
}
class ContextMockTest {
private val myClassMock: MyClass = mockk()
#Test
fun mockContextWorks() {
every {
with(any<CallContext>()) {
myClassMock.myMethod(any())
}
} returns 123
val context = object : CallContext { }
with(context) {
assertEquals(123, myClassMock.myMethod(1))
}
verify {
with(any<CallContext>()) {
myClassMock.myMethod(1)
}
}
}
}
A link to the gist just in case
For few test cases I'm trying to follow a DRY principle, where only the interactions are different with same test case conditions. I'm not able to find a way to implement multiple methods in the interaction { } block.
As mentioned in http://spockframework.org/spock/docs/1.3/interaction_based_testing.html#_explicit_interaction_blocks, I'm using interaction { } in the then: block like below:
Java Code:
// legacy code (still running on EJB 1.0 framework, and no dependency injection involved)
// can't alter java code base
public voidGetData() {
DataService ds = new DataService();
ds = ds.findByOffset(5);
Long len = ds.getOffset() // happy path scenario; missing a null check
// other code
}
// other varieties of same code:
public voidGetData2() {
ItemEJB tmpItem = new ItemEJB();
ItemEJB item = tmpItem.findByOffset(5);
if(null != item) {
Long len = item.getOffset();
// other code
}
}
public voidGetData3() {
ItemEJB item = new ItemEJB().findByOffset(5);
if(null != item) {
Long len = item.getOffset();
// other code
}
}
Spock Test:
def "test scene1"() {
given: "a task"
// other code ommitted
DataService mockObj = Mock(DataService)
when: "take action"
// code omitted
then: "action response"
interaction {
verifyNoDataScenario() // How to add verifyErrorScenario() interaction to the list?
}
}
private verifyDataScenario() {
1 * mockObj.findByOffset(5) >> mockObj // the findByOffset() returns an object, so mapped to same mock instance
1 * mockObj.getOffset() >> 200
}
private verifyErrorScenario() {
1 * mockObj.findByOffset(5) >> null // the findByOffset() returns null
0 * mockObj.getOffset() >> 200 // this won't be executed, and should ie expected to throw NPE
}
The interaction closure doesn't accept more than one method call. I'm not sure if it's design limitation. I believe more can be done in the closure than just mentioning the method name. I also tried interpolating the mockObj as a variable and use data pipe / data table, but since it's referring the same mock instance, it's not working. I'll post that as a separate question.
I ended up repeating the test case twice just to invoke different interaction methods. Down the line I see more scenarios, and wanted to avoid copy & paste approach. Appreciate any pointers to achieve this.
Update:
Modified shared java code as the earlier DataService name was confusing.
As there's no DI involved, and I didn't find a way to mock method variables, so I mock them using PowerMockito, e.g. PowerMockito.whenNew(DataService.class).withNoArguments().thenReturn(mockObj)
Your application code looks very strange. Is the programming style in your legacy application really that bad? First a DataService object is created with a no-arguments constructor, just to be overwritten in the next step by calling a method on that instance which again returns a DataService object. What kind of programmer creates code like that? Or did you just make up some pseudo code which does not have much in common with your real application? Please explain.
As for your test code, it also does not make sense because you instantiate DataService mockObj as a local variable in your feature method (test method), which means that in your helper method mockObj cannot be accessed. So either you need to pass the object as a parameter to the helper methods or you need to make it a field in your test class.
Last, but not least, your local mock object is never injected into the class under test because, as I said in the first paragraph, the DataService object in getData() is also a local variable. Unless your application code is compeletely fake, there is no way to inject the mock because getData() does not have any method parameter and the DataService object is not a field which could be set via setter method or constructor. Thus, you can create as many mocks as you want, the application will never have any knowledge of them. So your stubbing findByOffset(long offset) (why don't you show the code of that method?) has no effect whatsoever.
Bottom line: Please provide an example reflecting the structure of your real code, both application and test code. The snippets you provide do not make any sense, unfortunately. I am trying to help, but like this I cannot.
Update:
In my comments I mentioned refactoring your legacy code for testability by adding a constructor, setter method or an overloaded getData method with an additional parameter. Here is an example of what I mean:
Dummy helper class:
package de.scrum_master.stackoverflow.q58470315;
public class DataService {
private long offset;
public DataService(long offset) {
this.offset = offset;
}
public DataService() {}
public DataService findByOffset(long offset) {
return new DataService(offset);
}
public long getOffset() {
return offset;
}
#Override
public String toString() {
return "DataService{" +
"offset=" + offset +
'}';
}
}
Subject under test:
Let me add a private DataService member with a setter in order to make the object injectable. I am also adding a check if the ds member has been injected or not. If not, the code will behave like before in production and create a new object by itself.
package de.scrum_master.stackoverflow.q58470315;
public class ToBeTestedWithInteractions {
private DataService ds;
public void setDataService(DataService ds) {
this.ds = ds;
}
// legacy code; can't alter
public void getData() {
if (ds == null)
ds = new DataService();
ds = ds.findByOffset(5);
Long len = ds.getOffset();
}
}
Spock test:
Now let us test both the normal and the error scenario. Actually I think you should break it down into two smaller feature methods, but as you seem to wish to test everything (IMO too much) in one method, you can also do that via two distinct pairs of when-then blocks. You do not need to explicitly declare any interaction blocks in order to do so.
package de.scrum_master.stackoverflow.q58470315
import spock.lang.Specification
class RepeatedInteractionsTest extends Specification {
def "test scene1"() {
given: "subject under test with injected mock"
ToBeTestedWithInteractions subjectUnderTest = new ToBeTestedWithInteractions()
DataService dataService = Mock()
subjectUnderTest.dataService = dataService
when: "getting data"
subjectUnderTest.getData()
then: "no error, normal return values"
noExceptionThrown()
1 * dataService.findByOffset(5) >> dataService
1 * dataService.getOffset() >> 200
when: "getting data"
subjectUnderTest.getData()
then: "NPE, only first method called"
thrown NullPointerException
1 * dataService.findByOffset(5) >> null
0 * dataService.getOffset()
}
}
Please also note that testing for exceptions thrown or not thrown adds value to the test, the interaction testing just checks internal legacy code behaviour, which has little to no value.
I have an interface that communicates with my presenter who checks whether the fields of a form are valid.
My interface is:
interface MainView {
fun showMessage(data: LoginEntity)
fun showEmailError()
fun showPasswordError()
}
My method in the presenter is like that:
fun sendForm(loginData: LoginDataPresentation, view: MainView) {
if (isValid()) {
view.showMessage(mapData(loginData))
} else if (isValidPassword()) {
view.showPasswordError()
} else {
view.showEmailError()
}
}
My test class with KotlinTest:
class LoginPresentationKtTest : StringSpec() {
init {
"given a bunch of Login Data should be matched successfully" {
forAll(EmailGenerator(), PasswordGenerator(), { email: String, password: String ->
val loginData: LoginDataPresentation(email, password)
val mockMainView = mockMainView()
sendForm(loginData, mockMainView())
})
}
}
private fun mockMainView(): MainView {
//How to mock?????
}
}
Using the KotlinTest library, is there any way to verify that the call to the showMessage method of the MainView class is done provided that the email and password generated is always correct? Is it possible to use a mock library like mockito?
With the response of the user #mkobit, the following modification can be made using Mockito-Kotlin, with which the test would be as follows:
class LoginPresentationKtTest : StringSpec() {
init {
"given a bunch of Login Data should be matched successfully" {
forAll(EmailGenerator(), PasswordGenerator(), { email: String, password: String ->
val loginData = LoginDataPresentation(email, password)
val mockMainView = Mockito.mock(MainView::class.java)
sendForm(loginData, mockMainView)
verify(mockMainView).showMessage()
true
})
}
}
}
At each execution of the loop, it will be checked if the verify () function has been called. If the execution flow is the expected one, it will proceed to the next execution of the loop. If the verify () function fails, an error will occur in the console indicating that the test has failed.
Is there any better solution?
You mentioned Mockito, so I'll show you can example. I'm going to also use the nhaarman/mockito-kotlin library that makes it more expressive and easier to use in Kotlin.
import com.nhaarman.mockito_kotlin.mock
val mockMainView: MainView = mock()
This is basically equivalent to val mockMainView = Mockito.mock(MainView::class.java) from Mockito.
In Kotlin, we can get a more concise and compact code due to some of its features.
If you want to do some stubbing (like return values, exceptions, etc.) you could use the whenever (Mockito.when(T methodCall)) API.
See the documentation for details.
I'm going to skip that for now.
So, now you would call for method:
sendForm(loginData, mockMainView)
Then, you can perform verification.
Using mockito-kotlin method verify (Mockito.verify(T mock)) the behavior.
import com.nhaarman.mockito_kotlin.verify
verify(mockMainView).showPasswordError()
verify(mockMainView).showEmailError()
Using any() (Mockito.any(Class<T> type)) to not just verify method is called with any value.
import com.nhaarman.mockito_kotlin.any
verify(mockMainView).showMessage(any())
There is support for other argument matchers if you want to be more explicit with what is being passed in.
Note that Mockito also supports opt-in mocking of final classes/methods.
The example for Gradle would be something like adding a file to src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker with the contents of mock-maker-inline.
References:
Mockito Javadoc
mockito-kotlin Wiki documentation
We are in process of writing Unit test cases using Spock, I am not able to understand the following code snippet in then section varifying the declaration,
then:
1 * service.fraudMigrationOnboardingService.onboard(_) >>
{merchantId -> successCallBack.call(response)}
what is the meaning of the above code.
Because your question is lacking detail, I have to speculate and make an educated guess about your test. :-/
So you have a service with a member or getter fraudMigrationOnboardingService.
fraudMigrationOnboardingService has a method onboard taking a single parameter.
Obviously fraudMigrationOnboardingService is a mock or spy, which is why you can check interactions like 1 * ... on it.
The developer who wrote this test and whom, as it seems, you are too shy to ask about its meaning or who has left your company, wanted something specific to happen when method onboard(_) is called (probably by service) during the test: a call-back method call. Thus she declared the method stub { merchantId -> successCallBack.call(response) } as a replacement for what onboard(_) would normally do in this case. In a spy it would execute the original method, in a mock it would no nothing at all. But obviously that is not the desired behaviour, maybe because the test relies on different behavious later on.
In general, I think a test which is hard to read should be refactored, but anyway, here I am replicating your situation:
package de.scrum_master.stackoverflow
import spock.lang.Specification
class DummyTest extends Specification {
static class Service {
FraudMigrationOnboardingService fraudMigrationOnboardingService
void doSomething(String name) {
println "Doing something"
fraudMigrationOnboardingService.onboard(name)
}
}
static class FraudMigrationOnboardingService {
void onboard(String name) {
println "On-boarding $name"
}
}
static class SuccessCallBack {
void call(int httpResponse) {
println "Callback HTTP response = $httpResponse"
}
}
def "Some service test"() {
given:
def onboardingService = Mock(FraudMigrationOnboardingService)
def service = new Service(fraudMigrationOnboardingService: onboardingService)
def successCallBack = new SuccessCallBack()
def response = 200
when:
service.doSomething("ACME Inc.")
then:
1 * service.fraudMigrationOnboardingService.onboard(_) >>
{ merchantId -> successCallBack.call(response) }
}
}
The console log says:
Doing something
Callback HTTP response = 200
If you would comment out >> { merchantId -> successCallBack.call(response) }, it would only print
Doing something
for a mock and if you also change the Mock(FraudMigrationOnboardingService) into a Spy(FraudMigrationOnboardingService) it would print
Doing something
On-boarding ACME Inc.
Update: Maybe you still don't understand what the closure means, I am not sure. So I will explain it a bit more: As I said, it is just a stub for the onboard(String) method. The method parameter is mapped to merchantId but not used in the stubbed method. Instead the callback is triggered.
Here is my situation:
I want to test on the "HasSomething()" function, which is in the following class:
public class Something
{
private object _thing;
public virtual bool HasSomething()
{
if (HasSomething(_thing))
return true;
return false;
}
public virtual bool HasSomething(object thing)
{
....some algo here to check on the object...
return true;
}
}
So, i write my test to be like this:
public void HasSomethingTest1()
{
MockRepository mocks = new MockRepository();
Something target = mocks.DynamicMock(typeof(Something)) as Something;
Expect.Call(target.HasSomething(new Object())).IgnoreArguments().Return(true);
bool expected = true;
bool actual;
actual = target.HasSomething();
Assert.AreEqual(expected, actual);
}
Is my test written correctly?
Please help me as i can't even get the result as expected. the "HasSomething(object)" just can't be mock in that way. it did not return me 'true' as being set in expectation.
Thanks.
In response to OP's 'answer': Your main problem is that RhinoMocks does not mock members of classes - instead it creates mock classes and we can then set expectations and canned responses for its members (i.e. Properties and Functions). If you attempt to test a member function of a mock/stub class, you run the risk of testing the mocking framework rather than your implementation.
For the particular scenario of the logical path being dependent on the return value of a local (usually private) function, you really need an external dependency (another object) which would affect the return value that you require from that local function. For your code snippet above, I would write the test as follows:
[Test]
public void TestHasSomething()
{
// here I am assuming that _thing is being injected in via the constructor
// you could also do it via a property setter or a function
var sut = new Something(new object());
Assert.IsTrue(sut.HasSomething);
}
i.e. no mocking required.
This is one point of misunderstanding that I often had in the past with regards to mocking; we mock the behaviour of a dependency of the system under test (SUT). Something like: the SUT calls several methods of the dependency and the mocking process provides canned responses (rather than going to the database, etc) to guide the way the logic flows.
A simple example would be as follows (note that I have used RhinoMocks AAA syntax for this test. As an aside, I notice that the syntax that you are using in your code sample is using the Record-Replay paradigm, except that it isn't using Record and Replay! That would probably cause problems as well):
public class SUT
{
Dependency _depend
public SUT (Dependency depend)
{
_depend = depend;
}
...
public int MethodUnderTest()
{
if (_depend.IsReady)
return 1;
else
return -1;
}
}
...
[Test]
public void TestSUT_MethodUnderTest()
{
var dependency = MockRepository.GenerateMock<Dependency>();
dependency.Stub(d => d.IsReady).Return(true);
var sut = new SUT(dependency);
Assert.AreEqual(1, sut.MethodUnderTest());
}
And so the problem that you have is that you are attempting to test the behaviour of a mocked object. Which means that you aren't actually testing your class at all!
In a case like this, your test double should be a derived version of class Something. Then you override the method HasSomething(object) and ensure that HasSomething() calls your one.
If I understand correctly, you are actually interested in testing the method HasDynamicFlow (not depicted in your example above) without concerning yourself with the algorithm for HasSomething.
Preet is right in that you could simply subclass Something and override the behavior of HasSomething to short-circuit the algorithm, but that would require creating some additional test-dummy code which Rhino is efficient at eliminating.
Consider using a Partial Mock Stub instead of a Dynamic Mock. A stub is less strict and is ideal for working with Properties. Methods however require some extra effort.
[Test]
public void CanStubMethod()
{
Foo foo = MockRepository.GenerateStub<Foo>();
foo.Expect(f => f.HasDynamicFlow()).CallOriginalMethod(OriginalCallOptions.NoExpectation);
foo.Expect(f => f.HasSomething()).CallOriginalMethod(OriginalCallOptions.NoExpectation);
foo.Expect(f => f.HasSomething(null)).IgnoreArguments().Return(true);
Assert.IsTrue(foo.HasDynamicFlow());
}
EDIT: added code example and switched Partial Mock to Stub