Specifically asking, is there a Kotlin version for this java statement?
whenNew(myClass.class).withAnyArguments().thenReturn(myObject);
I have looked everywhere and haven't found anything that has worked for me yet.
I have tried:
every { myClass(any(), any()) } returns myObject
To this I get this error - argumentA must be in the form m.n. This tells me that blank arguments are being fed to myClass constructor but this is not my motive. I want this class to always return myObject whenever a constructor is being called, irrespective of the arguments.
I have also tried this:
every { myClass(TEST_A, TEST_B) } returns myObject
Then I get this error - Missing calls inside every { ... } block.
Another key point to add is - this is not the class I am writing the test for. I am writing the test cases for myOtherClass (actually defined in kotlin as an object, see below). Within one of the methods in myOtherClass, myClass is instantiated by feeding a set of arguments to its public constructor.
object myOtherClass {
fun mainFunction(a: A, b: B): X {
val answer = getAnswer(a, b)
y = convertAnswerToX(answer)
return y
}
private fun getAnswer(a: A, b: B): myClass {
val a1 = doSomethingToA(a)
val b1 = doSomethingToB(b)
return myClass(a1, b1)
}
}
I have the following structure:
class A {
public A(String p){
// ...
}
public String AMethod(String p){
// ...
}
}
class B {
int method(String param){
A a = new A(param); int n;
String s = A.AMethod(param);
// ... (initializes n, ...)
return n;
}
}
Now I want to test method in class B but control the output of AMethod when it is called. But since I do not create the object A in the test class of B, I cannot mock it normally - how can I mock object A instead?
I tried Mockito.spy but it doesn't seem to work:
this.ASpy = spy(new A());
when(ASpy.createSession(any())).then(invocation -> {
// ... (*)
});
(*) still doen't get called... but spy should be the right solution, shouldn't it? My problem is: I never create an object A in my test class, only in method such an object is created but not in the test class.
The best way to handle this (if possible) would be to modify the code of class B so that object A was injected into the method (passed as a parameter, set as a class field or instantiated with usage of a factory class - the factory would be injected as a field and the factory object could be mocked in the test to return a mocked object A).
If actual code modifications are not possible, you could use PowerMock's whenNew method and return a mocked object in your test.
A side note: if you're using JUnit 5, PowerMock may not be a viable solution - read more here.
I had the following class and its mock:
struct Logger
{
virtual void logWarning(string msg);
};
struct LoggerMock : Logger
{
MOCK_METHOD1(logWarning, void(string));
/*! Sets expectation that some warning will be logged */
void expectWarnings()
{
EXPECT_CALL(*this, logWarning(_)).Times(AnyNumber());
}
};
It works. The expectWarnings() method is used when I'm expecting some logs but not interested in them.
LoggerMock mock;
// ignore warnings
mock.expectWarnings();
// some code using mock
But lately, I've decided to add the ability to extend the expectations like:
LoggerMock mock;
mock.expectWarnings().Times(2);
So, I've modified the expectWarnings() method:
auto expectWarnings()
{
return EXPECT_CALL(*this, logWarning(_)).Times(AnyNumber());
}
It's ok for c++14. But for c++11 it is needed to specify the returning type like this:
auto expectWarnings()->decltype(EXPECT_CALL(*this, logWarning(_)).Times(AnyNumber()))
Of course, simply putting EXPECT_CALL inside decltype() is not working.
What is the right way in c++11 to deduce this returning type?
I have a simple class like
class SomeClass {
def foo() {
def bar= bar()
switch( bar ) {
return something based on format
}
}
def bar() {
return someValue
}
}
I've already written complete unit tests for the bar(). Now I need to write unit tests for foo() which is heavily dependant on the use of bar() method. I don't want to duplicate the setup phase as done for bar(), so I'd like to mock it by simply returning values I want.
I'm aware that Groovy supports this sort of "mocking" easily by simply defining it like SomeClass.property = "Hello World". Also, this can be done with collaborators as SomeClass.service = myMockedService. But I've not found a way to accomplish this with methods inside the unit under tests. Is there?
I tried with MockFor as in
def uut = new MockFor( SomeClass )
uut.demand.bar{ /* some values */ }
uut.use {
assert uut.foo() == expected
}
but it gives me
groovy.lang.MissingMethodException: No signature of method: groovy.mock.interceptor.MockFor.foo() is applicable for argument types: () values: []
UPDATE
In fact, I came up with a simple solution of using sub-classing. In the test method I create a subclass of SomeClass where I override the method I wish to mock/stub. After this, using an instance of the subclass gives me what I need.
This seems a bit rough, though. Any other suggestions on this?
If you want to mock the value returned by bar() for a single instance of SomeClass you can use metaprogramming. Try the following in the Groovy console:
class SomeClass {
def foo() {
}
def bar() {
return 'real value'
}
}
def uut = new SomeClass()
uut.metaClass.bar = {
return 'mock value'
}
assert 'mock value' == uut.bar()
If you want to mock bar() for all instances of SomeClass, replace this:
uut.metaClass.bar = {
return 'mock value'
}
with:
SomeClass.metaClass.bar = {
return 'mock value'
}
I'm trying to create a similar router to Rails ActionDispatch router, which allows you to define a route similar to
map.get "/foo", :controller => "Foo", :action => "index"
which will then route GET /foo to FooController#index. With this structure in place you can use methods like
map.resources :foos
which will call methods like
map.get "/foo", :controller => "Foo", :action => "index"
map.get "/foo/:id", :controller => "Foo", :action => "show"
and so on.
In D, I've been able to figure out a lot of the reflexive code required to make this work, but not all of it. In Ruby I can do:
class Foo
def bar
"FOOO BAR!"
end
end
f = Object.const_get("Foo")
f.new.__send__(:bar) #=> "FOOO BAR!"
Which I've tried to translate to
module foo;
import std.stdio;
class Foo {
void bar() {
writeln("FOO BAR!");
}
}
void main() {
auto foo = Object.factory("foo.Foo");
__traits(getMember, foo, "bar");
}
But that doesn't work because the compiler doesn't know what type foo is, so the call to #bar fails during compile. Everywhere I've seen Object.factory used they cast it to a specific type, so
module foo;
import std.stdio;
class Foo {
void bar() {
writeln("FOO BAR!");
}
}
void main() {
auto foo = cast(Foo) Object.factory("foo.Foo");
__traits(getMember, foo, "bar");
}
would work just fine. But if I know what I want to cast the object to what good is using Object.factory? That doesn't make any sense to me!
UPDATE 2 I've fixed compiler issues, but now it's crashing at runtime, saying it couldn't find the method
module foo;
import std.stdio;
class MyDynamic {
void call(C, T...)(C instance, string method, T args) {
foreach(member; __traits(allMembers, C)) {
writeln(member);
if (member == method) {
static if (__traits(compiles, __traits(getMember, instance, member)(args))) {
__traits(getMember, instance, member)(args);
}
return;
}
}
assert(0, "No method found");
}
}
class Foo : MyDynamic {
void bar() {
writeln("FOO BAR!");
}
}
void main() {
auto foo = cast(MyDynamic) Object.factory("foo.Foo");
assert(foo !is null);
foo.call(foo, "bar");
}
Update For anyone coming to this question now, you can see my final solution here: https://github.com/jaredonline/action-pack
The way I do this is to build my own factory function and dynamic dispatches. Using __traits(allMembers), loop through all the supported classes and get a list of methods. Write a wrapper template that takes generic arguments and converts them to the arguments the function needs. Store a reference to the wrapper function in an associative array, or have a dispatch method in your interface to call it.
When it is time to do the work, create the class (with your own wrapper, or you could also use Object.factory and cast it to some generic interface with your dynamic dispatch function), then use the dynamic function. So something like:
// IMPORTANT: Object.factory needs a full name - includes the module and class name!
auto foo = cast(MyDynamic) Object.factory("mymodule.Foo");
assert(foo !is null); // Object.factory can return null if it didn't find the class
// and cast can also return null if it wasn't actually of that interface type, so gotta check
foo.call("my_method", ["arg", "arg2", ...]);
I updated this link with a full example, refresh if you don't see module dynamicstuff; at the top:
http://arsdnet.net/dcode/test46.d
loop allMembers, invoke based on a runtime string. Getting a list of all classes that implement an interface is possible too, by looping over ModuleInfo. See the bottom of the example file for a function to do it.
My web.d does this to do automatic calling of functions from the web. Long, messy code, but it does a lot. Here's the wrapper function:
https://github.com/adamdruppe/misc-stuff-including-D-programming-language-web-stuff/blob/master/web.d#L2538
Note the use of ParameterTypeTuple!func from std.traits.
I put a lot of comments in here http://arsdnet.net/dcode/test46.d so hopefully they will answer your questions. That example briefly demonstrates:
compile time reflection with __traits (MyDynamicImplementation)
run time reflection with ModuleInfo and ClassInfo (getAllDynamicClasses)
User-defined attributes (isDynamicallyAvailable)
Calling a method with dynamic data (MyDynamicImplementation, uses ReturnType, to, ParameterTypeTuple, and there's commented code for Variant if you are interested)
An alternative to multiple inheritance, using an interface and mixin template together.
You don't necessarily have to use all that stuff, but I figured I'd touch upon all of it since these can all be pretty useful for these url routing tasks.