Mocking and Expecting from a Class instance created using new operator in Google Mock - googletest

Need your inputs regarding the below:
I am facing an issue regarding how to write a mock for a base class (StackBT) of which an instance is created in the derived class's constructor (ApplicationBT) that I want to test.
My intention is to write a mock for the StackBT class (Mock_StackBT) and then link this to the unit test so that the instance of the mock is created when doing "new StackBT()" in ApplicationBT's constructor. So that using this I can mock the expectations on StackBT class while testing ApplicationBT class.
out/linux_host/obj/TestApplicationBT.o: In function `TestApplicationBT::SetUp()':
tst/_src/TestApplicationBT.cpp:33: undefined reference to `mockPtr_StackBT'
out/linux_host/lib/libServer.a(ApplicationBT.o): In function `ApplicationBT::init()':
/_src/ApplicationBT.cpp:36: undefined reference to `StackBT::registerCallbacks()'
/_src/ApplicationBT.cpp:43: undefined reference to `StackBT::sendBTMacAddress(std::string)'
collect2: error: ld returned 1 exit status
make: *** [out/linux_host/bin/Test] Error 1
I get the above compiler error while compiling the below code snippet:
StackBT.h:
class StackBT
{
StackBT(){}
void registerCallbacks();
void sendBTMacAddress(std::string str);
}
Mock_StackBT.h:
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include <string>
using ::testing::NiceMock;
class Mock_StackBT;
extern NiceMock < Mock_StackBT >* mockPtr_StackBT;
class Mock_StackBT: public StackBT
{
Mock_StackBT(){}
MOCK_METHOD0(registerCallbacks, void());
MOCK_METHOD1(sendBTMacAddress, void(std::string str));
}
Mock_StackBT.cpp:
#include "Mock_StackBT.h"
NiceMock < Mock_StackBT >* mockPtr_StackBT;
void registerCallbacks()
{
mockPtr_StackBT->registerCallbacks();
}
void sendBTMacAddress(std::string str)
{
mockPtr_StackBT->sendBTMacAddress(std::string str);
}
ApplicationBT.h:
class ApplicationBT
{
public:
ApplicationBT() : mpoStackBT(new StackBT())
void init()
{
mpoStackBT->registerCallbacks();
mpoStackBT->sendBTMacAddress("AB:CD:EF:GH:IJ:KL");
}
friend class TestApplicationBT;
scoped_ptr<StackBT> mpoStackBT;
}
TestApplicationBT.h
class TestApplicationBT : public ::testing::Test
{
protected:
virtual void SetUp ()
{
mockPtr_StackBT = &stackBTMock;
ptrApplicationBT = new ApplicationBT();
}
void TearDown()
{
delete ptrApplicationBT;
}
public:
TestApplicationBT ()
{
}
~TestApplicationBT ()
{
ptrApplicationBT = NULL;
}
scoped_ptr<ApplicationBT> ptrApplicationBT;
StackBT* ptrStackBT;
NiceMock<Mock_StackBT> stackBTMock;
};
TEST_F(TestApplicationBT, Init)
{
EXPECT_CALL(stackBTMock, registerCallbacks() ).Times(1);
EXPECT_CALL(stackBTMock, sendBTMacAddress(_) ).Times(1);
ptrApplicationBT->init();
}

First problem is that you are using mockPtr_StackBT in TestApplicationBT.cpp, but it is defined in
Mock_StackBT.cpp. The second issue is that the call to ApplicationBT::init method calls functions
registerCallbacks and sendBTMacAddress through pointer mpoStackBT, but if you look closely at
the constructor for class ApplicationBT you will se that this pointer is set to an object of class StackBT
and not Mock_StackBT. This causes a linker error because you did not implement functions
registerCallbacks and sendBTMacAddress for class StackBT, you have only declared them.
The main problem is that you are not swapping your real implementation with a mock, your approach is
not correct. First of all, you are not suppossed to create implementations for functions registerCallbacks
and sendBTMacAddress in the mock class, googlemock does that for you (file Mock_StackBT.cpp is completely
unnecessary). Also, you need a common interface for classes StackBT and Mock_StackBT so you can
switch implementations. Here is how you do it:
Create interface:
class IStackBT
{
public:
virtual IStackBT() {}
virtual void registerCallbacks() = 0;
virtual sendBTMacAddress(std::string str) = 0;
}
Create class for production:
class StackBT : public IStackBT
{
public:
void registerCallbacks() override
{
// Your code that registers callbacks
}
void sendBTMacAddress(std::string str) override
{
// Your code that sends mac address
}
}
Create mock class:
class StackBTMock : public IStackBT
{
public:
MOCK_METHOD0(registerCallbacks, void());
MOCK_METHOD1(sendBTMacAddress, void(std::string str));
}
Now, make your class ApplicationBT hold a IStackBT pointer and use some form of factory method
to create a real or mock object, depending on the fact if you are building unit test or deployment code. There
are several ways, here is how I did it on my gmock project. Create a preprocessor define for your unit testing
project that indicates the code is built for unit tests. If it is, for example, named MY_UNIT_TESTS, then in
constructor of ApplicationBT do the following:
ApplicationBT() : mpoStackBT(createStackBT())
where createStackBT is a function defined as:
IStackBT * createStackBT()
{
#ifdef MY_UNIT_TESTS
return new StackBTMock;
#else
return new StackBT;
#endif
}
This will perform the swapping of implementation during compilation time when you are building your unit test executable. Since you will be performing this swapping on several classes as you write more tests, I suggest that you wrap the factory functions in some class that provides the desired implementations (mock or production) of your classed. For instance, my project has a class named ImplementationProvider that performs this task.

Related

Passing native class pointer to another C++/CLI

I have two wrappers written in C++/CLI as followings.
One wrapper get a native class handle and it send this native handle to another class, however, I got a compile error.
I think there are some work-around,
1) #pragme make_public()
2) using IntPtr(sender) and static_cast with IntPtr.ToPointer(receiver).
What is the best solution?
namespace AWrapper {
public ref class AClass
{
public:
NativeClass* GetInfo() { return nativeClass; }
...
private:
NativeClass* nativeClass;
}
namespace BWrapper {
...
void ImageSensor::SetClass(AWrapper::AClass^ aclass)
{
NativeClass* native_tpr;
native_tpr = aclass->GetInfo(); // Not visible, like private
}
}

NSubstitute: Received Calls asserts wrongly

I've created this test:
[TestFixture]
public class UsersTests
{
private Core.Kernel coreKernel;
private Core.Configuration.ICoreConfiguration coreConfiguration;
[SetUp]
public void SetUp()
{
this.coreConfiguration = NSubstitute.Substitute.For<Core.Configuration.ICoreConfiguration>();
this.coreKernel = NSubstitute.Substitute.For<Core.Kernel>(this.coreConfiguration);
this.coreKernel.Initialize();
}
[Test]
public void AddUserTest()
{
Core.Communication.Entities.UserIdentity receivedUserIdentity = new Core.Communication.Entities.UserIdentity("user1", "passwd1");
((Core.Communication.ICoreService)this.coreKernel).AddUserIdentity(receivedUserIdentity);
this.coreKernel.Received(100).AddUser(Arg.Is<Core.Identity.UserIdentity>(u => u.UserId.Equals(receivedUserIdentity.UserId)));
}
}
where Core.Kernel is:
public partial class Kernel : Core.IKernel
{
public Kernel(Configuration.ICoreConfiguration configuration)
: this(configuration, null, Enumerable.Empty<Type>())
{
}
public Kernel(Configuration.ICoreConfiguration configuration, Communication.ICoreService service, IEnumerable<Type> producerTypes)
{
if (configuration == null)
throw new ArgumentException("configuration object must be provided", "configuration");
if (producerTypes.Any(t => !t.IsAssignableFrom(typeof(Core.Extensibility.AbstractProducerPlugin))))
throw new ArgumentException("All types must inherit from AbstractProducerPlugin", "plugins");
this.state = KernelState.initializing;
this.configuration = configuration;
this.service = service ?? this;
this.producerTypes = producerTypes;
this.backends = new Dictionary<Core.Identity.DomainIdentity, Backend.Infrastructure.IBackend>();
}
internal virtual void AddUser(Core.Identity.UserIdentity userIdentity) {...}
}
Nevertheless, this.coreKernel.Received(100).AddUser(... is not called 100 times, only one. What am I doing wrong?
I mean, I'm not trying to make 100 calls to AddUser. I'm checking AddUser should be called 100 times. So, assertion should fail.
EDIT
Guess this code (Core.IKernel.AddUserIdentity(...) implementation):
public class Core.Kernel {
public override void Core.IKernel.AddUserIdentity(UserIdentity userIdentity) {
this.AddUser(userIdentity); <<----- AddUser(...) is called
}
}
I think the problem is related with:
Core.Kernel implements Core.IKernel. Core.IKernel has AddUserIdentity(...) method.
I'm mocking Core.Kernel instead of mocking a Core.IKernel.
According to Core.IKernel.AddUserIdentity(...) method implementation AddUser should ne reached.
AddUser is an internal virtual method of Core.Kernel. It's not an implementation of any method interface.
I want to assert AddUser is called once when AddUserIdentity is reached.
Other questions about mocking:
For<T> where T is a concrete class -> virtual methods are replaced? no virtual methods are executed?
ForPartsOf<T> where T is a concrete class -> Which parts of this class are mocked (virtual methods, overrided interface methods)?
It is only called once because you are only calling AddUser once. The Received assertion checks how many times it has been called, it doesn't tell NSubstitue to call your method 100 times, you need to do that manually :)
NSubstitute also gives you the option of asserting a specific number of calls were received by passing an integer to Received(). This will throw if the substitute does not receive exactly that many matching calls
http://nsubstitute.github.io/help/received-calls/

C++ CLI Wrapper

I’ve a question about creating a C++ CLI Wrapper for a native C++ class to be used in C#.
Here is an example code:
#include "stdafx.h"
#pragma once
using namespace System;
namespace Wrapper {
class NativeClass
{
public:
NativeClass() {}
int Add(int a, int b)
{
return a+b;
}
};
public ref class Wrapper
{
public:
Wrapper() {pNative = new NativeClass();}
int Add(int a, int b)
{
return(pNative->Add(a,b));
}
~Wrapper()
{
delete pNative;
pNative = 0;
}
!Wrapper()
{
this->~Wrapper();
}
//My problem is here.
NativeClass* GetNative()
{
return pNative;
}
private:
NativeClass* pNative;
};
}
This code works fine. I need to retrieve the pointer that refers the native class to use it in the other wrapper classes. However, I don’t want the function “GetNative” to be visible in C# when I’m using this wrapper class. How can I hide it?
If the other wrapper classes are in the same assembly, make the access internal instead of public. – Roger Rowland Apr 25 '13 at 9:47
.
if they are not in the same assembly? ...
Look into friend assemblies – Sebastian Cabot Feb 1 at 15:43

CA1047 'Make member raise private, public, or internal' and C++/CLI events

When I declare a public event in a sealed C++/CLI class, I get Code Analysis warning CA1047. The warning seems to come from auto-generated protected member functions. How can I fix this warning?
Here's an example. This code
ref class Test sealed {
public:
event EventHandler^ blah;
};
generates:
warning: CA1047 : Microsoft.Design : Make member 'Test::blah::raise(Object^, EventArgs^)' private, public, or internal
I'll document the question better. This code
ref class Test sealed {
public:
event EventHandler^ blah;
};
generates:
warning: CA1047 : Microsoft.Design : Make member 'Test::blah::raise(Object^, EventArgs^)' private, public, or internal
Yes, when you don't specify the event accessors yourself then the compiler will generate them for you. It auto-generates the add, remove and raise accessors. The latter one looks like this when you look with ildasm.exe:
.method family hidebysig specialname instance void
raise_blah(object value0,
class [mscorlib]System.EventArgs value1) cil managed
{
// etc..
}
The family attribute is what causes the code analysis warning. The auto-generated add and remove accessors are of course public. Writing them yourself is a questionable workaround, you really only want to do this if you have a real reason to implement custom accessors. The boilerplate version would look like this:
using namespace System::Runtime::CompilerServices;
ref class Test sealed {
private:
EventHandler^ foo;
public:
event EventHandler^ blah {
[MethodImpl(MethodImplOptions::Synchronized)]
void add(EventHandler^ d) { foo += d; }
[MethodImpl(MethodImplOptions::Synchronized)]
void remove(EventHandler^ d) { foo -= d; }
private:
void raise(Object^ sender, EventArgs^ e) {
EventHandler^ handler = foo;
if (handler != nullptr) handler(sender, e);
};
}
};
Well, that certainly suppresses the warning. I recommend you use the [SuppressMessage] attribute if that doesn't spin your propeller.

Rhino.Mocks how to test abstract class method calls

I'm trying to test if the method I want to test calls some external (mock) object properly.
Here is the sample code:
using System;
using Rhino.Mocks;
using NUnit.Framework;
namespace RhinoTests
{
public abstract class BaseWorker
{
public abstract int DoWork(string data);
}
public class MyClass
{
private BaseWorker worker;
public BaseWorker Worker
{
get { return this.worker; }
}
public MyClass(BaseWorker worker)
{
this.worker = worker;
}
public int MethodToTest(string data)
{
return this.Worker.DoWork(data);
}
}
[TestFixture]
public class RhinoTest
{
[Test]
public void TestMyMethod()
{
BaseWorker mock = MockRepository.GenerateMock<BaseWorker>();
MyClass myClass = new MyClass(mock);
string testData = "SomeData";
int expResponse = 10;
//I want to verify, that the method forwards the input to the worker
//and returns the result of the call
Expect.Call(mock.DoWork(testData)).Return(expResponse);
mock.GetMockRepository().ReplayAll();
int realResp = myClass.MethodToTest(testData);
Assert.AreEqual(expResponse, realResp);
}
}
}
When I run this test, I get:
TestCase 'RhinoTests.RhinoTest.TestMyMethod'
failed: System.InvalidOperationException : Invalid call, the last call has been used or no call has been made (make sure that you are calling a virtual (C#) / Overridable (VB) method).
at Rhino.Mocks.LastCall.GetOptions[T]()
at Rhino.Mocks.Expect.Call[T](T ignored)
RhinoTest.cs(48,0): at RhinoTests.RhinoTest.TestMyMethod()
The exception is thrown on the Expect.Call line, before any invocation is made.
How do I approach this - i.e. how to check if the method under test properly forwards the call?
This is .Net 2.0 project (I can no change this for now), so no "x =>" syntax :(
I have to admit, I'm not entirely sure what's going on here, but using Rhino.Mocks 3.6 and the newer syntax, it works fine for me:
[Test]
public void TestMyMethod()
{
MockRepository mocks = new MockRepository();
BaseWorker mock = mocks.StrictMock<BaseWorker>();
MyClass myClass = new MyClass(mock);
string testData = "SomeData";
int expResponse = 10;
using (mocks.Record())
{
//I want to verify, that the method forwards the input to the worker
//and returns the result of the call
Expect.Call(mock.DoWork(testData)).Return(expResponse);
}
using (mocks.Playback())
{
int realResp = myClass.MethodToTest(testData);
Assert.AreEqual(expResponse, realResp);
}
}
It doesn't have anything to do with the Rhino.Mocks version. With the old syntax, I get the same error as you're getting. I didn't spot any obvious errors in your code, but then again, I'm used to this using syntax.
Edit: removed the var keyword, since you're using .NET 2.0.