Google Mock and protected copy constructor - constructor

I have a class with a protected copy constructor:
class ThingList
{
public:
ThingList() {}
virtual ~ThingList() {}
std::vector<Thing> things;
protected:
ThingList(const ThingList &copy) {}
};
I have another class the uses this one:
class AnotherThing
{
public:
AnotherThing()
{
}
virtual ~AnotherThing() {}
void DoListThing(const ThingList &list)
{
}
};
and a Mock version of this class:
class MockAnotherThing : public AnotherThing
{
public:
MOCK_METHOD1(DoListThing, void(const ThingList &list));
};
I want to call this method DoListThing with a real argument to supply a real list:
TEST(Thing, DoSomeThingList)
{
MockThing thing;
ThingList list;
MockAnotherThing anotherThing;
list.things.push_back(Thing());
EXPECT_CALL(anotherThing, DoListThing(list));
anotherThing.DoListThing(list);
}
I get an error compiling this:
1>..\mockit\googletest\googlemock\include\gmock\gmock-matchers.h(3746): error C2248: 'ThingList::ThingList': cannot access protected member declared in class 'ThingList'
Yet if I make a non-Mock call it works just fine:
ThingList list;
AnotherThing theRealThing;
theRealThing.DoListThing(list);
If in the Mock test I call with '_', it works:
TEST(Thing, DoSomeThingList)
{
MockThing thing;
ThingList list;
MockAnotherThing anotherThing;
list.things.push_back(Thing());
EXPECT_CALL(anotherThing, DoListThing(_));
anotherThing.DoListThing(list);
}
However, how can I pass a list in this case? If the list was returned by DoListThing, I could use Return but what do I for an argument that get modified like this?

I was unable to get past a protected copy constructor so my answer was to create a fake (dummy) version of a class and ignore Google Mock. This worked well enough for me to test the class in question. The example I provided here is a simplified version of the bigger package.

Related

Trouble creating a base ViewModel for MvvmCross 5.1.0

I'm currently diving into the world of Xamarain with the MvvmCross framework. In my current project I want to make use of a MVVM base ViewModel to be able to reuse some of my code in other ViewModels.
When trying to implement this I've ran into a problem when using the MvxViewModel which supports passing parameters between navigation.
public abstract class BaseViewModel<TParameter> : MvxViewModel, IMvxViewModel<TParameter> where TParameter : class
{
protected readonly IMvxNavigationService _navigationService;
public BaseViewModel(IMvxNavigationService navigationService)
{
_navigationService = navigationService;
}
public new abstract Task Initialize(TParameter parameter);
}
This way I'm able to use the BaseViewModel as following.
public class ExampleViewModel : BaseViewModel<ExampleParameters>
{
private ExampleParameters _parameter;
public ExampleViewModel(IMvxNavigationService navigationService) : base(navigationService)
{
}
public override Task Initialize(ExampleParameters parameter)
{
return Task.Run(() => { _parameter = parameter; });
}
}
In this situation I think this is a pretty good solution. The ExampleViewModel even tells me I need to implement the Initialize Task when I've forgotten.
Still this solution is not great in every situation. When I have ViewModel that doesn't require the passing of parameters I still need to specify a parameters object and implement the Initialize method.
public class ParameterlessViewModel : BaseViewModel<object>
{
public ParameterlessViewModel(IMvxNavigationService navigationService) : base(navigationService)
{
}
public override Task Initialize(object parameter)
{
return Task.Run(() => { });
}
}
When removing the abstract method from the BaseViewModel I wont need to implement the Initialize method but then I won't be forced to implement it when I'm creating a ViewModel that requires the passing of parameters.
The above solution is workable but I'm curious if anyone ran into this same problem and maybe has a better solution? One which is good in both situations without having to setup two BaseViewModel classes.
Kind regards,
Jop Middelkamp
The documentation for this states: https://www.mvvmcross.com/documentation/fundamentals/navigation
If you have a BaseViewModel you might not be able to inherit MvxViewModel<TParameter> or MvxViewModel<TParameter, TResult> because you already have the BaseViewModel as base class. In this case you can implement the following interface:
IMvxViewModel<TParameter>, IMvxViewModelResult<TResult> or IMvxViewModel<TParameter, TResult>
In case you use TResult you can just copy the source code into your viewmodel:
public override TaskCompletionSource<object> CloseCompletionSource { get; set; }
public override void ViewDestroy()
{
if (CloseCompletionSource != null && !CloseCompletionSource.Task.IsCompleted && !CloseCompletionSource.Task.IsFaulted)
CloseCompletionSource?.TrySetCanceled();
base.ViewDestroy();
}
Do we do the add the Interface IMvxViewModel in the base class or the device class, can you give a simple example
In this case you can implement the following interface:
IMvxViewModel<TParameter>, IMvxViewModelResult<TResult> or IMvxViewModel<TParameter, TResult>

Kotlin #JvmStatic and accidental override in a companion object

I'm working on a Swing look&feel using kotlin. In order to create a UI, Swing requires to have a static method createUI with the following signature:
class ButtonUI: BasicButtonUI() {
...
companion object {
#JvmStatic fun createUI(p0: JComponent): ComponentUI {
...
}
}
}
and then it is called via reflection in Swing code:
m = uiClass.getMethod("createUI", new Class[]{JComponent.class});
Unfortunately, the code above cannot be compiled by the kotlin compiler because of:
Error:(88, 9) Kotlin: Accidental override: The following declarations have the same JVM signature (createUI(Ljavax/swing/JComponent;)Ljavax/swing/plaf/ComponentUI;):
fun createUI(c: JComponent): ComponentUI
fun createUI(p0: JComponent!): ComponentUI!
Is there a workaround for this case?
it's a kotlin bug KT-12993. Unfortunately, the bug is not fixed yet. just using java implements your ButtonUI or switch between java and kotlin to solving the problem if you want to let kotlin implements your ui logic. for example, you should define a peer between java and kotlin.
the java code as below:
public class ButtonUI extends BasicButtonUI {
private ButtonUIPeer peer;
public ButtonUI(ButtonUIPeer peer) {
this.peer = peer;
}
#Override
public void installUI(JComponent c) {
peer.installUI(c, () -> super.installUI(c));
}
// override other methods ...
public static ComponentUI createUI(JComponent c) {
// create the peer which write by kotlin
// |
return new ButtonUI(new YourButtonUIPeer());
}
}
interface ButtonUIPeer {
void installUI(Component c, Runnable parentCall);
//adding other methods for the ButtonUI
}
the kotlin code as below:
class YourButtonUIPeer : ButtonUIPeer {
override fun installUI(c: Component, parentCall: Runnable) {
// todo: implements your own ui logic
}
}
IF you have more than half dozen methods to implements, you can using the Proxy Design Pattern just delegate request to the target ButtonUI which implemented in kotlin (many IDE support generates delegate methods for a field). for example:
public class ButtonUIProxy extends BasicButtonUI {
private final BasicButtonUI target;
//1. move the cursor to here ---^
//2. press `ALT+INSERT`
//3. choose `Delegate Methods`
//4. select all public methods and then click `OK`
public ButtonUIProxy(BasicButtonUI target) {
this.target = target;
}
public static ComponentUI createUI(JComponent c){
// class created by kotlin ---v
return new ButtonUIProxy(new ButtonUI());
}
}
In latest version of Kotlin 1.3.70 the error can be suppressed with #Suppress("ACCIDENTAL_OVERRIDE"). I am not sure since which version it works.

How do I use Mockito to mock a protected method?

I’m using Mockito 1.9.5. How do I mock what is coming back from a protected method? I have this protected method …
protected JSONObject myMethod(final String param1, final String param2)
{
…
}
However, when I attempt to do this in JUnit:
final MyService mymock = Mockito.mock(MyService.class, Mockito.CALLS_REAL_METHODS);
final String pararm1 = “param1”;
Mockito.doReturn(myData).when(mymock).myMethod(param1, param2);
On the last line, I get a compilation error “The method ‘myMethod’ is not visible.” How do I use Mockito to mock protected methods? I’m open to upgrading my version if that’s the answer.
This is not an issue with Mockito, but with plain old java. From where you are calling the method, you don't have visibility. That is why it is a compile-time issue instead of a run-time issue.
A couple options:
declare your test in the same package as the mocked class
change the visibilty of the method if you can
create a local (inner) class that extends the mocked class, then mock this local class. Since the class would be local, you would have visibility to the method.
Responding to the request for a code sample of option 3 from John B's answer:
public class MyClass {
protected String protectedMethod() {
return "Can't touch this";
}
public String publicMethod() {
return protectedMethod();
}
}
#RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
class MyClassMock extends MyClass {
#Override
public String protectedMethod() {
return "You can see me now!";
}
}
#Mock
MyClassMock myClass = mock(MyClassMock.class);
#Test
public void myClassPublicMethodTest() {
when(myClass.publicMethod()).thenCallRealMethod();
when(myClass.protectedMethod()).thenReturn("jk!");
}
}
You can use Spring's ReflectionTestUtils to use your class as it is and without needing of change it just for tests or wrap it in another class.
public class MyService {
protected JSONObject myProtectedMethod(final String param1, final String param2) {
return new JSONObject();
}
public JSONObject myPublicMethod(final String param1) {
return new JSONObject();
}
}
And then in Test
#RunWith(MockitoJUnitRunner.class)
public class MyServiceTest {
#Mock
private MyService myService;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
when(myService.myPublicMethod(anyString())).thenReturn(mock(JSONObject.class));
when(ReflectionTestUtils.invokeMethod(myService, "myProtectedMethod", anyString(), anyString())).thenReturn(mock(JSONObject.class));
}
}
Something like following worked for me, using doReturn() and Junit5's ReflectionSupport.
[Note: I tested on Mockito 3.12.4]
ReflectionSupport.invokeMethod(
mymock.getClass()
// .getSuperclass() // Uncomment this, if the protected method defined in the parent class.
.getDeclaredMethod("myMethod", String.class, String.class),
doReturn(myData).when(mymock),
param1,
param2);
John B is right, this is because the method you're trying to test is protected, it's not a problem with Mockito.
Another option on top of the ones he has listed would be to use reflection to gain access to the method. This will allow you to avoid changing the method you are testing, and avoid changing the pattern you use to write tests, and where you store these tests. I've had to do this myself for some tests where I was not allowed to change the existing code base which included a large number of private methods that needed to be unit tested.
These links explain Reflection and how to use it very well, so I will link to them rather than copy:
What is reflection and whit is it useful
How to test a class that has private methods, fields, or inner classes
WhiteBox.invokeMethod() can be handy.
public class Test extend TargetClass{
#Override
protected Object method(...) {
return [ValueYouWant];
}
}
In Spring, you can set it high high-priority like this:
#TestConfiguration
public class Config {
#Profile({"..."})
#Bean("...")
#Primary // <------ high-priority
public TargetClass TargetClass(){
return new TargetClass() {
#Override
protected WPayResponse validate(...) {
return null;
}
};
}
}
It is the same to override the origin bean.

PythonQt how to override virtual function

I am trying to add Python scripting capability to my Qt application. So far, I have been able to write wrappers for many classes. However, one class has a virtual 'init()' function which can be overridden by a derived class if necessary.
// C++ class
class MyClass : public QObject
{
Q_OBJECT
public:
MyClass()
{
init(); // perform user initialization
}
virtual void init() {}
};
The MyClass constructor calls the virtual function 'init()'. It is intended that when MyClass is sub-classed that the init function can be overridden if necessary to provide user initialization.
I wish to use 'MyClass' in PythonQt so I have written a wrapper class:
class MyClass_Wrapper : public QObject
{
Q_OBJECT
public Q_SLOTS:
// add a constructor
MyClass* new_MyClass() {return new MyClass(); }
void init(MyClass* mc) { mc->init(); }
};
The class 'MyClass' is now registered with PythonQt:
PythonQt::self()->registerCPPClass("MyClass",NULL,"myModule", PythonQtCreateObject<MyClass_Wrapper>);
Now, I create a Python script to use 'MyClass':
import myModule
Class TestClass(MyClass) :
def init(self):
# init() is called exactly once at the beginning to do
# any necessary configuration.
print "Inside init(self)"
.
.
.
return
The problem is that the print statement (and the following code) is never executing. The init() function is not being overridden by the PythonQt code.

registering open generic decorators for typed implementations in castle windsor

While trying to coerce Windsor into wrapping an implementation with a random number of decorators, i've stumbled upon the following:
i have 3 decorators and an implementation all using the same interface.
if you run this code, windsor resolves icommandhandler<stringcommand> as implementation, which, as far as i can tell, is expected behaviour, because the typed implementation can not be registered with the open typed decorators.
However, if you uncomment the line container.Register(Component.For<ICommandHandler<stringCommand>>().ImplementedBy<Decorator1<stringCommand>>());, all three decorators will be used to resolve implementation, which is the desired result (sort of : ).
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer();
container.Register(Component.For(typeof(ICommandHandler<>)).ImplementedBy(typeof(Decorator1<>)));
container.Register(Component.For(typeof(ICommandHandler<>)).ImplementedBy(typeof(Decorator2<>)));
container.Register(Component.For(typeof(ICommandHandler<>)).ImplementedBy(typeof(Decorator3<>)));
//uncomment the line below and watch the magic happen
//container.Register(Component.For<ICommandHandler<stringCommand>>().ImplementedBy<Decorator1<stringCommand>>());
container.Register(Component.For<ICommandHandler<stringCommand>>().ImplementedBy<implementation>());
var stringCommandHandler = container.Resolve<ICommandHandler<stringCommand>>();
var command = new stringCommand();
stringCommandHandler.Handle(command);
Console.WriteLine(command.s);
Console.ReadKey();
}
}
public interface ICommandHandler<T>
{
void Handle(T t);
}
public class stringCommand
{
public string s { get; set; }
}
public abstract class Decorator<T> : ICommandHandler<T>
{
public abstract void Handle(T t);
};
public class Decorator1<T> : Decorator<T>
where T : stringCommand
{
private ICommandHandler<T> _handler;
public Decorator1(ICommandHandler<T> handler)
{
_handler = handler;
}
public override void Handle(T t)
{
t.s += "Decorator1;";
_handler.Handle(t);
}
}
public class Decorator2<T> : Decorator<T>
where T : stringCommand
{
private ICommandHandler<T> _handler;
public Decorator2(ICommandHandler<T> handler)
{
_handler = handler;
}
public override void Handle(T t)
{
t.s += "Decorator2;";
_handler.Handle(t);
}
}
public class Decorator3<T> : Decorator<T>
where T : stringCommand
{
private ICommandHandler<T> _handler;
public Decorator3(ICommandHandler<T> handler)
{
_handler = handler;
}
public override void Handle(T t)
{
t.s += "Decorator3;";
_handler.Handle(t);
}
}
public class implementation : ICommandHandler<stringCommand>
{
public void Handle(stringCommand t)
{
t.s += "implementation;";
}
}
Why exactly is this happening, is this a feature of windsor that i am not aware of? Is there perhaps a different way to achieve the same effect? (without resorting to reflection)
When windsor tries to resolve a component it will first try to resolve the more specific interface. So when you register Component.For it will prefer to resolve this over an open generic type.
If the same interface is registered multiple times, it will use the first one specified.
So if you don't uncommment the line your application will resolve implementation since this is the most specific component.
If you do uncomment the line decorator1 will be resolved and indeed the magic starts. The decorator will now start looking for the first registered component that satisfies it's constructor, in this case that would be decorator1 again (you did notice that your output show decorator1 2 times ?). Which will the resolve the next registered component and so on till it comes to the actual implementation.
So the only thing I can think about is not registering decorator1 as an open generic but as a specific type.
Kind regards,
Marwijn.