I have a simple mock class:
class MockCanInterface : public lib::CanInterface {
public:
MockCanInterface() : CanInterface({"mock"}) {}
MOCK_METHOD1(Write, bool(const lib::CanFrame& frame));
MOCK_METHOD1(Read, bool(lib::CanFrame* frame));
};
In the test code I want to pass an object to the Write method. Is there a way to do this with .With clause? It works with passing argument directly, but now with .With. The code compiles, but fails during execution - the size of the object is correct, but the data isn't.
This works:
EXPECT_CALL(can_, Write(expected_command_))
.WillOnce(Return(true));
This doesn't:
EXPECT_CALL(can_, Write(_))
.With(Args<0>(expected_command_))
.WillOnce(Return(true));
I admit that there may be something missing in the way the code sets the expected object.
I think the point is: The method Write() required a CanFrame argument passed by reference.
I suggest to use the Actions provided by GMock:
SetArgReferee - reference or value
SetArgPointee - pointer
You can find examples and much more here
However this solution works for me, I hope for you too ;)
EXPECT_CALL(can_, Write(_))
.WillOnce(SetArgReferee<0>(expected_command_));
or with the return value:
EXPECT_CALL(can_, Write(_))
.WillOnce(DoAll(SetArgReferee<0>(expected_command_), Return(true)));
Related
Trying to figure out how to pass some parameters to my custom implementation of TestWatcher in Junit5. The base class for all tests is set to #ExtendWith with the TestWatcher. Trying to keep it as simple as possible and I can't seem to find a straightforward answer on how to do this
I was struggling on a similar problem, basically I needed a global parameter (a separator string data) for the annotation #DisplayNameGenerator().
Because the lack of code examples of how you're trying to resolve this I'm gonna explain my approach of how to get a parameter provided by the user and see if it works for you,
I created a interface with the return of the String value that is my custom parameter that I wanted to get from the user,
#Target(ElementType.TYPE)
#Retention(RetentionPolicy.RUNTIME)
#Inherited
#API(status = EXPERIMENTAL, since = "5.4")
public #interface IndicativeSentencesSeparator {
String value();
}
So this way I could create my test with this new interface, and passing the parameter but also making it optional to use, like this,
#DisplayName("My Test")
#DisplayNameGeneration(DisplayNameGenerator.IndicativeSentencesGenerator.class)
#IndicativeSentencesSeparator(" --> ")
class MyTestClass { //Some test methods and stuff }
To get the this new class in the implementation, I used the java method class.getAnnotation(classType) in the class that you're trying to extract the value, sending by parameter the class to find, in this case the interface I created.
IndicativeSentencesSeparator separator =
myTestClass.getAnnotation(IndicativeSentencesSeparator.class);
And finally to get the parameter used the getter value,
String parameter = separator.value();
How can I pass property getter to a function that accepts function type?
Here is an example of what I want achieve:
class Test {
val test: String
get() = "lol"
fun testFun(func: ()->String) {
// invoke it here
}
fun callTest() {
testFun(test::get)
// error: Type mismatch: inferred type is
// KFunction1<#ParameterName Int, Char> but () -> String was expected
}
}
Is there a way?
You can reference the getter by writing ::test (or this::test).
When you write test::get, you are actually referencing the get method on String. That method takes an index and returns the character at that index.
If the property was a var and you want a reference to its setter, you can write ::test::set.
For more info on property references, see here: https://kotlinlang.org/docs/reference/reflection.html#bound-function-and-property-references-since-11
As already mentioned, you can use this::test to refer to the getter. Alternatively, if you have kotlin-reflect, you can do this::test.getter.
When you pass the field as a function, it assumes you mean the getter. As a result, if you want the setter, you have two options:
this::test::set
or
this::test.setter
The latter, just like this::test.getter requires kotlin-reflect, or the program will crash (tested locally with Kotlin 1.2.50)
You can, however, get the getter in another way. But I recommend you just stick with this::test because it's shorter.
You can do:
this::something::get
With just something::get it refers to the method inside the String class, which returns a char at an index. For reference, the method declaration:
public override fun get(index: Int): Char
If you don't mind, just use { test } (e.g. testFun { test }). This will exactly translate to your () -> String. The next best alternative is probably ::test (or this::test) as was already mentioned.
The second has probably only minor (negligible?) impact on performance. I did not test it myself, nor did I found any source which tells something regarding it. The reason why I say this, is how the byte code underneath looks like. Just due to this question I asked myself about the difference of the two: Is the property reference (::test) equivalent to a function accessing the property ({ test }) when passed as argument e.g. `() -> String`?
It seems that you are doing something wrong on logical level.
If you are overriding get method of a variable, then you can access it's value through this get method. Thus, why bother with test::get (which is totally different method, by the way, all you are doing is trying to access char from string), when you can just access variable by it's name?
If I have a public method, I can call it inside its class using both $.name and self.name:
class TEST {
has Int $.a;
method b($x) {
return $!a * $x;
}
method c($y) {
return self.b($y) * 3; # or $.b($y)
}
}
my $m = TEST.new(a => 10);
say $m.c(2); # 60
But if I make b a private method, I only can call it with self!b, not $!b, otherwise I get the following error message:
Attribute $!b not declared in class TEST
What's behind this rule? What are the rules of calling a method inside its own class?
An attribute can always be referred to as $!foo in a class. If you do that, than the code will be generated to directly access the attribute itself, and any classes subclassing your class will not be able to change this behaviour.
If you use has $.foo in the declaration of a class, it means that a public accessor (and if you add is rw it can also function as a mutator).
When you use $.foo in your code otherwise, it is exactly the same as $( self.foo ). This means that it will call the method foo on self, and itemize the return value (make it a single "thing" if it wasn't yet). This will go wrong if you defined your attribute with $!foo and you did not supply a method foo yourself.
This goes even further: $.bar really means self.bar: you only need to have a method existing by the name bar, which may not be related to any attribute at all.
If you define a private method !baz, the ! just indicates the privacy of the method, which means you need to call it indeed as self!baz. There is no short syntax for it.
Personally I dislike the fact that you can say $.zippo even if zippo is not an attribute. But I'm afraid that ship has sailed. But this behaviour is now causing you confusion :-(
So what's behind the rule for not having a short syntax for calling a private method? Not sure, I guess really that $!foo was already taken to mean direct access to the attribute, and provide you with a compile time error if the attribute doesn't exist.
Hope this answers your question!
I am missing something ...
I have a class SocketComm. I have a derived class SocketTCP : public SocketComm.
SocketComm has the following in it:
static SocketComm *Instance; // static pointer to the singleton instance du jour
I am trying to define a method in SocketComm as follows:
static inline SocketTCP *GetTCPclass()
{
// consistent method to return a SocketTCP* cast of SocketComm::Instance (or NULL)
SocketTCP *s = dynamic_cast<SocketTCP *>(Instance);
assert( s != NULL );
return s;
}
I am getting (VS 2010)
error C2680: 'SocketTCP *' : invalid target type for dynamic_cast
What am I missing? SocketComm is abstract -- is that the problem?
The answer seems to be that dynamic_cast needs a full declaration of the target class.
See my comment above.
Yeah, like #ViRusTriNiTy says, I suppose I could have put it in SocketTCP as a static inline. That would probably have worked too. But it seems more logical to me in the base class, and there is no performance reason to make it inline. The compiler will inline it when it can (in SocketComm.cpp) anyway.
According to your comments you are mixing code that belongs to a derived class into a base class. This is the wrong approach and you now see why: SocketTCP' : class must be defined before using in a dynamic_cast.
Just approach this in a different way like say adding a separate helper class that does the dynamic_cast.
I have a problem while using jmockit for the following scenario. Did a research on the web, but couldn't locate the answers yet.
In the record phase, I am setting the expectation on an object that is partially mocked. While doing it, I would like to mock a private method with single parameter. But i don't really concerned with that parameter value. I want to match all invocation of that particular private method with any instance of argument passed to it. How do I do it in Jmockit. Is there a way?
new Expectations(student) {
{
Deencapsulation.invoke(student, "setDepartment", (Department) any);
result = new Delegate<Student>() {
public void setDepartment(Department dept) {
System.out.println("Mocked setDepartment() methodd.....");
}
};
}
};
In the above code, (Department) any can not be passed, since Deencapsulation.invoke(...) method doesn't accept null value.
Note the API documentation for the any field says:
"In invocations to non-accessible methods or constructors (for example, with Deencapsulation.invoke(Object, String, Object...)), use withAny(T) instead."
That is, you need to use withAny(Department.class) with the invoke(...) call.
As of JMockit v1.49, I use:
withInstanceOf(Department.class)
It works as expected.