Mocking extension function in Kotlin - unit-testing

How to mock Kotlin extension function using Mockito or PowerMock in tests? Since they are resolved statically should they be tested as static method calls or as non static?

I think MockK can help you.
It supports mocking extension functions too.
You can use it to mock object-wide extensions:
data class Obj(val value: Int)
class Ext {
fun Obj.extensionFunc() = value + 5
}
with(mockk<Ext>()) {
every {
Obj(5).extensionFunc()
} returns 11
assertEquals(11, Obj(5).extensionFunc())
verify {
Obj(5).extensionFunc()
}
}
If you extension is a module-wide, meaning that it is declared in a file (not inside class), you should mock it in this way:
data class Obj(val value: Int)
// declared in File.kt ("pkg" package)
fun Obj.extensionFunc() = value + 5
mockkStatic("pkg.FileKt")
every {
Obj(5).extensionFunc()
} returns 11
assertEquals(11, Obj(5).extensionFunc())
verify {
Obj(5).extensionFunc()
}
By adding mockkStatic("pkg.FileKt") line with the name of a package and file where extension is declared (pkg.File.kt in the example).
More info can be found here: web site and github

First of all, Mockito knows nothing Kotlin specific language constructs. In the end, Mockito will have a look into the byte code. Mockito is only able to understand what it finds there and what looks like a Java language construct.
Meaning: to be really sure, you might want to use javap to deassemble the compiled classfiles to identify the exact names/signatures of the methods you want to mock.
And obviously: when that method is static, you have to user PowerMock, or JMockit; if not, you should prefer to with Mockito.
From a java point of view, you simply avoid mocking static stuff; but of course, things get really interesting, now that different languages with different ideas/concepts come together.

Instance extension functions can be stubbed and verified like this with the help of mockito-kotlin:
data class Bar(thing: Int)
class Foo {
fun Bar.bla(anotherThing: Int): Int { ... }
}
val bar = Bar(thing = 1)
val foo = mock<Foo>()
with(foo) {
whenever(any<Bar>().bla(any()).doReturn(3)
}
verify(foo).apply {
bar.bla(anotherThing = 2)
}

I use mockk library.
For extension file write java name, like this:
#file:JvmName(name = "ExtensionUtils")
package myproject.extension
...
And for fast codding I created file with different extension mocks:
object FastMock {
fun extension() = mockkStatic("myproject.extension.ExtensionUtils")
fun listExtension() = mockkStatic("myproject.extension.ListExtensionUtils")
}
In test call this:
FastMock.listExtension()
every { itemList.move(from, to) } returns Unit

Related

How to run setup code before any tests run in Rust?

I have a Rust app (a simple interpreter) that needs some setup (initialize a repo) before the environment is usable.
I understand that Rust runs its tests (via cargo test) in a multithreaded manner, so I need to initialize the repo before any tests run. I also need to do this only once per run, not before each test.
In Java's JUnit this would be done with a #BeforeClass (or #BeforeAll in JUnit 5) method. How can I acheive the same thing in Rust?
There's nothing built-in that would do this but this should help (you will need to call initialize() in the beginning of every test):
use std::sync::Once;
static INIT: Once = Once::new();
pub fn initialize() {
INIT.call_once(|| {
// initialization code here
});
}
If you use the ctor crate, you can take advantage of a global constructor function that will run before any of your tests are run.
Here's an example initialising the popular env_logger crate (assuming you have added ctor to your [dev-dependencies] section in your Cargo.toml file):
#[cfg(test)]
#[ctor::ctor]
fn init() {
env_logger::init();
}
The function name is unimportant and you may name it anything.
Just to give people more ideas (for example, how not to call setup in every test), one additional thing you could do is to write a helper like this:
fn run_test<T>(test: T) -> ()
where T: FnOnce() -> () + panic::UnwindSafe
{
setup();
let result = panic::catch_unwind(|| {
test()
});
teardown();
assert!(result.is_ok())
}
Then, in your own tests you would use it like this:
#[test]
fn test() {
run_test(|| {
let ret_value = function_under_test();
assert!(ret_value);
})
}
You can read more about UnwindSafe trait and catch_unwind here: https://doc.rust-lang.org/std/panic/fn.catch_unwind.html
I've found the original idea of this test helper in this medium article by Eric Opines.
Also, there is rstest crate which has pytest-like fixtures which you can use as a setup code (combined with the Jussi Kukkonen's answer:
use std::sync::Once;
use rstest::rstest;
static INIT: Once = Once::new();
pub fn setup() -> () {
INIT.call_once(|| {
// initialization code here
});
}
#[rstest]
fn should_success(setup: ()) {
// do your test
}
Maybe one day rstest will gain scopes support and Once won't be needed anymore.

Using Kotlin and Mockito to mock functions taking vararg parameters

I'm having trouble utilizing Powermock, Mockito, and Kotlin to mock up a return value when
the function signature that needs overriden contains varargs.
Function to mock/override:
public BoundStatement bind(Object... values);
Test File:
class DbSessionTest {
var preparedStatement: PreparedStatement? = null
#Mock
var boundStatement: BoundStatement? = null
#Before
fun setup() {
initMocks(this)
whenever(preparedStatement?.bind(any())).thenReturn(boundStatement)
// Also, have tried it like this
whenever(preparedStatement?.bind(any<Array<Any>>())).thenReturn(boundStatement)
}
}
The fuction in the actual code is called like so:
internal fun createBoundStatement(query: String, vararg params: Any): BoundStatement {
val preparedStatement = prepare(query)
val boundStatement = preparedStatement.bind(*params)
return boundStatement
}
When I step through and the varargs are dereferenced, it turns into an Object[].
When the object array contains all the same type, everything works fine, but when
it contains type String and type Integer, the mock fails to happen and null is
returned.
Note: I have also included com.nhaarman.mockito_kotlin.any package for their specific
any function and anyVararg, but that did not work either.
What is the proper way to mock this so that no matter the type in the Object array,
it will always return the mocked value?
Nicholas Hauschild's answer make me think about removing powermock and just going with regular mockito and junit separately and that worked. Removing powermock and Upgrading mockito to v2.18.3 fixed the issue.

NUnit 3.X - How to pass dynamic parameters into a TestCase or TestCaseSource?

CGrunddaten m_grdDaten;
[SetUp]
public void Init()
{
m_grdDaten = new CGrunddaten();
m_grdDaten.m_cwdGeoH.m_dW = 325.0;
m_grdDaten.m_cwd_tl.m_dW = 15;
}
[Test]
public void TestMethod()
{
m_grdDaten.RechGrdDaten();
Assert.That(m_grdDaten.m_cwd_pl.m_dW, Is.EqualTo(93344).Within(.1),"Außenluftdruck");
Assert.That(m_grdDaten.m_cwd_pl_neb.m_dW, Is.EqualTo(93147.3).Within(.1), "Außenluftdruck Nebenluftberechnung");
Assert.That(m_grdDaten.m_cwd_pl_pmax.m_dW, Is.EqualTo(92928.2).Within(.1), "Außenluftdruck max. zul. Unterdruck");
Assert.That(m_grdDaten.m_cwdRho_l.m_dW, Is.EqualTo(1.124).Within(.001), "Dichte Außenluft");
Assert.That(m_grdDaten.m_cwdRho_l_neb.m_dW, Is.EqualTo(1.184).Within(.001), "Dichte Außenluft Nebenluftberechnung");
Assert.That(m_grdDaten.m_cwdRho_l_pmax.m_dW, Is.EqualTo(1.249).Within(.001), "Dichte Außenluft max. zul. Unterdruck");
}
Is there a way to get this in a TestCase or TestCaseSource, so that I have only one Assert-line ?
I'm talking about this:
m_grdDaten.m_cwd_pl.m_dW, 93344
m_grdDaten.m_cwd_pl_neb.m_dW, 93147.3
m_grdDaten.m_cwd_pl_pmax.m_dW, 92928.2
....
I know that TestCase and TestCaseSource are static.... but is there another way?
The best way to do this test would be using the not-yet-implemented multiple asserts feature, so that all the asserts would run even if some failed.
Since that's not available yet, I can understand your wanting to make this into multiple tests, where each gets reported separately. Using test cases makes this possible, of course, even though this is really logically just one test.
The fact that a test case source method must be static doesn't prevent it from creating an instance of your CGrunddaten class. The tests themselves are all just comparing two doubles for equality and don't need to know anything about that class.
You could write something like this:
private static IEnumerable<TestCaseData> GrundDatenDaten
{
var gd = new CGrunddaten();
gd.m_cwdGeoH.m_dW = 325.0;
gd.m_cwd_tl.m_dW = 15;
gd.RechGrdDaten();
yield return new TestCaseData(gd.m_cwd_pl.m_dW, 93344, .1, "Außenluftdruck");
// und so weiter
}
[TestCaseSource("GrundDatenDaten")]
public void testMethod(object actual, object expected, object tolerance, string label)
{
Assert.That(actual, Is.EqualTo(expected).Within(tolerance), label);
}
However, I don't like that very much as it hides the true function of the test in the data source. I think your original formulation is the best way to do it for now and leaves you with the ability to include the code in an Assert.Multiple block once that feature is implemented.

mocking a method while calling a method in same service class groovy grails

im looking for something similar to what i would do with rhino mocks but in groovy.
i sometimes use partial mocks as well.
in ASP -- Rhino mocks
const string criteria = "somecriteriahere";
ISomeRepository mockSomeRepository = MockRepository.GenerateStrictMock<SomeRepository>();
mockSomeRepository.Expect(m => m.GetSomesByNumber(criteria)).Return(new List<Some>() { });
mockSomeRepository.Expect(m => m.GetSomesByName(criteria)).Return(new List<Some>() { });
mockSomeRepository.Expect(m => m.GetSomesByOtherName(criteria)).Return(new List<Some>() { });
mockSomeRepository.SearchForSomes(criteria);
mockSomeRepository.VerifyAllExpectations();
--------note the virtual -------
public class SomeRepository : ISomeRepository {
public virtual IEnumerable<Some> GetSomesByNumber(string num)
{
//some code here
}
public virtual IEnumerable<Some> GetSomesByName(string name)
{
//some code here
}
public virtual IEnumerable<Some> GetSomesByOtherName(string name)
{
//some code here
}
public IEnumerable<Some> SearchForSomes(string criteria) {
this.GetSomesByNumber(criteria); //tested fully seperatly
this.GetSomesByName(criteria); //tested fully seperatly
this.GetSomesByOtherName(criteria); //tested fully seperatly
//other code to be tested
}
}
GetSomesByNumber, GetSomesByName, GetSomesByOtherName would be tested fully seperatly. If i actually provided values and went into those functions, to me, that seems like in integration test where im testing multiple functionalities and not one unit of work.
So, SearchForSomes i would only be testing that method and mocking away all other dependencies.
In Grails
class XService {
def A() {
}
def B() {
def result = this.A()
//do some other magic with result
}
}
I have tried this -- but failed
def XServiceControl = mockFor(XService)
XServiceControl.demand.A(1..1) { -> return "aaa" }
// Initialise the service and test the target method.
//def service = XServiceControl.createMock();
//def service = XServiceControl.proxyInstance()
// Act
//def result = XServiceControl.B(_params);
XServiceControl.use {
new XService().B(_params)
}
Ive got no idea how to do this, does any one know how?
Thanks
If you're using groovy MockFor (e.g. groovy.mock.interceptor.MockFor), then you need to enclode the usage in a .use{} block.
However, it looks like you are calling mockFor from within a grails.test.GrailsUnitTestCase. In that case, there's no need for the .use{} block: the scope of the mock is the whole test.
thanks for your reply ataylor
seem what i was trying to accomplish is something called partial/half mocking. Here are some links.
http://www.gitshah.com/2010/05/how-to-partially-mock-class-and-its.html
http://mbrainspace.blogspot.com/2010/02/partial-half-mocks-why-theyre-good-real.html
https://issues.apache.org/jira/browse/GROOVY-2630
https://issues.apache.org/jira/browse/GROOVY-1823
http://java.dzone.com/articles/new-groovy-171-constructor
I didnt accomplish this, i ended up extracting B() into its own class and injecting a mock of XService into B's class -- Dependency Injection. I was also informed that extracting away dependencies is a better practice for testing. So, i am now very carefull when using this.() :D

How to use Rhino Mock to mock a local function calling?

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