Unit testing visual c++ code throws when deleting pointer - unit-testing

I am currently unit testing unmanaged visual c++ code in visual studio 2010.
My solution is structured as following:
<Solution>
- [0] Static library project (visual c++, no clr)
- [1] Project that's using [0] (visual c++, no clr, referencing [0])
- [2] Unit Test Project (dynamic library, /clr, referencing [0])
</Solution>
Project [0] is being tested by Project [2] and contains SomeClass:
class SomeClass
{
public:
SomeClass() {}
int Testme() { return 42; }
};
In Project [2] I am testing SomeClass as following, and this works:
[TestClass]
public ref class SomeClassUnitTests
{
public:
[TestMethod]
void TestmeReturns42()
{
SomeClass sc;
Assert::AreEqual<int>(42, sc.Testme());
}
};
But when I allocate the memory for SomeClass on the heap and only when I afterwards call delete on it, a message pops up showing that the heap was corrupt/invalid.
[TestClass]
public ref class SomeClassUnitTests
{
public:
[TestMethod]
void TestmeReturns42()
{
SomeClass *ptr = new SomeClass();
Assert::AreEqual<int>(42, ptr->Testme());
// Without following line, everything works:
if (ptr) delete ptr;
}
};
What could be the issue causing the Tests to throw right here, and why does allocating memory with 'new' work, but deleting doesn't?

Related

How to mock an ATL COM object in googletest unit tests

I am working on a legacy project that makes massive use of ATL COM objects. The task is to extend the unit testing (googletest) by the capability of mocking COM objects, or the smart pointers accessing them. To illustrate, I created a small example project with a single ATL simple object, which only exports the method methodB (part of idl file):
object,
uuid(070a4996-d9cf-4434-a823-3ea9043de394),
dual,
nonextensible,
pointer_default(unique)
]
interface IMyATLObj : IDispatch
{
[id(1)] HRESULT methodB([in] SHORT in, [out, retval] SHORT *out);
};
The objects are accessed using smart pointers of base type _com_ptr_t, such as in this example:
#include <comdef.h>
#include ".../ATLExample_i.h"
_COM_SMARTPTR_TYPEDEF(IMyATLObj, __uuidof(IMyATLObj));
IMyATLObjPtr create() {
IMyATLObjPtr objPtr;
objPtr.CreateInstance(__uuidof(MyATLObj));
return objPtr;
}
void use(IMyATLObjPtr objPtr) {
short val = 0;
objPtr->methodB(1, &val);
std::cout << val << std::endl;
}
Now the question is how I can test the function use(...) without actually creating a COM object. Of course I can create a wrapper class as a facade to all COM interactions that I can mock as usual, e.g.:
class MyObjFacade {
public:
MyObjFacade() {
objPtr.CreateInstance(__uuidof(MyATLObj));
}
virtual short methodB(short in) {
short val;
if (objPtr->methodB(in, &val) == S_OK)
return val;
else
throw;
}
IMyATLObjPtr objPtr;
};
class MYObjMock : public MyObjFacade {
public:
MOCK_METHOD1(methodB, short(short in));
};
void use(MyObjFacade *objPtr) {
short val = 0;
val = objPtr->methodB(1);
std::cout << val << std::endl << std::flush;
}
TEST_F(COMMockTest, Test1) {
MYObjMock mock;
EXPECT_CALL(mock, methodB(_)).WillOnce(Return(43));
use(&mock);
}
But that would obviously leave me with lots of boiler plate code and (possibly) unnessessary changes - this solution would probably not be well adopted. I am looking for an elegant solution that, for example, either introduces a mock object into IMyATLObjPtr mocks the pointer object itself. However, I don't really know where to start because all the available interfaces are generated by ATL and are not easily accessible.
Any ideas?

How to verify some other object was constructed, when using mockito

I have following Java code that I want to test. What I am having difficulty is figuring out how do I verify that call to handleAppVersionRequest , actually constructs AppVersionResponse object. Is there any way to do that using Mockito?
Here code is code for method:
class MyClass {
public void handleAppVersionRequest(String dataStr,
final int dataChannelId) {
String ver = "1.0";
final AppVersionResponse resp = new AppVersionResponse(ver);
Timber.d("Sending data %s", resp.toString());
sendResponse(dataChannelId, getGson().toJson(resp));
}
}
And here is method for test:
#Test
public void testHandleAppVersionRequest() throws Exception {
MyClass presenter = Mockito.spy(new MyClass());
String versionRequestJson = "{\"command\":1}";
when(presenter.getGson()).thenReturn(gSon);
presenter.handleAppVersionRequest(versionRequestJson,0);
// How do I verify that AppResponse object was constructed?
verify(presenter,times(1)).sendResponse(anyInt(),anyString());
}
If you must test the creation of the object during a unit test, you can extract a factory, mock it for your test, and then verify that the create method is called on it.
At the same time, consider spending some time looking at some tutorials for Mockito and unit testing in general, like this one. You should choose one class that is going to be the 'system under test'. Don't spy or mock this class! Instead, pass in mocks as dependencies that you will use to test the behaviour of your class.
Here is a factory extracted from your MyClass:
class AppVersionResponseFactory {
AppVersionResponse create(String version) {
return new AppVersionResponse(version);
}
}
Then the refactored version of your class where the dependencies (Gson and the factory) are passed in through the constructor:
class MyClass {
//dependencies that can now be mocked!
private final AppVersionResponseFactory appVersionResponseFactory;
private final Gson gson;
//pass the mockable dependencies in the constructor of the system under test!
public MyClass(AppVersionResponseFactory appVersionResponseFactory, Gson gson) {
this.appVersionResposeFactory = factory;
this.gson = gson;
}
public void handleAppVersionRequest(String dataStr, final int dataChannelId) {
String ver = "1.0";
AppVersionResponse resp = AppVersionResponseFactory.create(ver);
Timber.d("Sending data %s", resp.toString());
sendResponse(dataChannelId, gson.toJson(resp));
}
}
Now your test looks something like this:
//mocks
AppVersionResponseFactory mockAppVersionResposeFactory;
Gson mockGson;
//system under test
MyClass myClass;
#Before
public void setUp() {
mockAppVersionResposeFactory = Mockito.mock(AppVersionResponseFactory.class);
mockGson = Mockito.mock(Gson.class);
myClass = new MyClass(mockGson, mockAppVersionResposeFactory);
}
#Test
public void testHandleAppVersionRequest() throws Exception {
String versionRequestJson = "{\"command\":1}";
myClass.handleAppVersionRequest(versionRequestJson, 0);
verify(appVersionResposeFactory).create("1.0");
}
Please note that although your question asks for a way to verify the construction of an object, a better test would probably test the final outcome of that method i.e., that sendResponse was called with the correct dataChannelId and correct JSON. You can use the same techniques in this answer to do that i.e., extracting a dependency (perhaps a ResponseSender?), passing it in the constructor for your MyClass, mocking it in the test, then calling verify on it.

Test reading from a file using GoogleTest

I am trying to test a document reader using Google Test.
My code is organized as follow: there is a Document class which opens the file. A document contains one or more Element, which is a struct with a pointer (field) to a wstring and value.
Obviously I would like to open the file just once and then cycle though the various Elements.
class DocumentTest : public ::testing::Test {
protected:
virtual void SetUp() {
string path = "path/to/file";
Document doc;
doc.Open(path);
}
Element* el;
el = doc.Read();
};
TEST_F(DocumentTest, ReadTest) {
while (file has still elements) {
wchar_t* expectedField = L"expectingThis";
wchar_t* readString = el->field;
EXPECT_EQ(expectedField,readString);
}
but this is clearly not working. Where should I declare my init code?
https://github.com/google/googletest/blob/main/docs/advanced.md
In general googletest allows three different modes of resource management:
SetUp and TearDown() (run before and after each test function)
SetUpTestCase() and TearDownTestCase() (run before and after each class, or "Case")
The Environment class which is run before/after the first and last test, respectively.

should we create object of any class on class level or function level

Which approach is better: I tried to find it on web, but I couldn't get a better answer.
1.
public class OtherClass
{
public int Add(int x, int y)
{
return x + y;
}
}
public class TestClass
{
OtherClass oClass = new OtherClass();
public int Fun1()
{
return oClass.Add(1,2);
}
public int Fun2()
{
return oClass.Add(1, 2);
}
}
2.
public class TestClass
{
public int Fun1()
{
OtherClass oClass = new OtherClass();
return oClass.Add(1, 2);
}
public int Fun2()
{
OtherClass oClass = new OtherClass();
return oClass.Add(1, 2);
}
}
I think it depends on what you are trying to test.
If you're testing the effects of a sequence of functions being executed on the same class instance then you might want to create a single instance (such as stress testing)
But otherwise I'd say it's always better to create a new instance of the class in each test function to ensure that the context of each test is predictable. If your test methods shared an instance of a class, and one test method fails and corrupts the state of the object under test, your subsequent test may fail for no other reason than the state of the object under test was corrupted by the previous failed test (it might appear the multiple tests are failing when in fact only one of the early ones is a true failure).
Depends on the scenario, if the class is gonna be shared on multiple functions and there are no specific arguments needed to create an instance of that class then it's better of being at the class level.
Let's say you're using the Fun1 and Fun2 often, having the instance creation on the method will have instance creation overhead rather than it being at the class level having a single instance, or better yet, make it static or make it singleton if you're sure that it's going to be a single instance throughout the whole app.
One benefit of having it in the class level is if you're doing unit testing, you can make an interface like IOtherClass and Inject it in the constructor of TestClass.
It would look something like this.
public class OtherClass : IOtherClass
{
public int Add(int x, int y)
{
return x + y;
}
}
public class TestClass
{
IOtherClass oClass;
public TestClass(IOtherClass _oClass)
{
oClass = _oClass;
}
public int Fun1()
{
return oClass.Add(1,2);
}
public int Fun2()
{
return oClass.Add(1, 2);
}
}
You're better off having it as a field in the class rather than declaring a new one in each method. The reason for this is simple, there won't be a line of code in each method declaring the variable meaning that if your declaration statement changes you will only have to change it in one place, not every method. Also it will make your code easier to read and add to because this line won't be duplicated everywhere.
Just remember if that field needs to be disposed your class should implement the IDisposable interface.

Unit testing with singletons

I have prepared some automatic tests with the Visual Studio Team Edition testing framework. I want one of the tests to connect to the database following the normal way it is done in the program:
string r_providerName = ConfigurationManager.ConnectionStrings["main_db"].ProviderName;
But I am receiving an exception in this line. I suppose this is happening because the ConfigurationManager is a singleton. How can you work around the singleton problem with unit tests?
Thanks for the replies. All of them have been very instructive.
Have a look at the Google Testing blog:
Using dependency injection to avoid singletons
Singletons are Pathological Liars
Root Cause of Singletons
Where have all the Singletons Gone?
Clean Code Talks - Global State and Singletons
Dependency Injection.
And also:
Once Is Not Enough
Performant Singletons
Finally, Misko Hevery wrote a guide on his blog: Writing Testable Code.
You can use constructor dependency injection. Example:
public class SingletonDependedClass
{
private string _ProviderName;
public SingletonDependedClass()
: this(ConfigurationManager.ConnectionStrings["main_db"].ProviderName)
{
}
public SingletonDependedClass(string providerName)
{
_ProviderName = providerName;
}
}
That allows you to pass connection string directly to object during testing.
Also if you use Visual Studio Team Edition testing framework you can make constructor with parameter private and test the class through the accessor.
Actually I solve that kind of problems with mocking. Example:
You have a class which depends on singleton:
public class Singleton
{
public virtual string SomeProperty { get; set; }
private static Singleton _Instance;
public static Singleton Insatnce
{
get
{
if (_Instance == null)
{
_Instance = new Singleton();
}
return _Instance;
}
}
protected Singleton()
{
}
}
public class SingletonDependedClass
{
public void SomeMethod()
{
...
string str = Singleton.Insatnce.SomeProperty;
...
}
}
First of all SingletonDependedClass needs to be refactored to take Singleton instance as constructor parameter:
public class SingletonDependedClass
{
private Singleton _SingletonInstance;
public SingletonDependedClass()
: this(Singleton.Insatnce)
{
}
private SingletonDependedClass(Singleton singletonInstance)
{
_SingletonInstance = singletonInstance;
}
public void SomeMethod()
{
string str = _SingletonInstance.SomeProperty;
}
}
Test of SingletonDependedClass (Moq mocking library is used):
[TestMethod()]
public void SomeMethodTest()
{
var singletonMock = new Mock<Singleton>();
singletonMock.Setup(s => s.SomeProperty).Returns("some test data");
var target = new SingletonDependedClass_Accessor(singletonMock.Object);
...
}
Example from Book: Working Effectively with Legacy Code
Also given same answer here:
https://stackoverflow.com/a/28613595/929902
To run code containing singletons in a test harness, we have to relax the singleton property. Here’s how we do it. The first step is to add a new static method to the singleton class. The method allows us to replace the static instance in the singleton. We’ll call it
setTestingInstance.
public class PermitRepository
{
private static PermitRepository instance = null;
private PermitRepository() {}
public static void setTestingInstance(PermitRepository newInstance)
{
instance = newInstance;
}
public static PermitRepository getInstance()
{
if (instance == null) {
instance = new PermitRepository();
}
return instance;
}
public Permit findAssociatedPermit(PermitNotice notice) {
...
}
...
}
Now that we have that setter, we can create a testing instance of a
PermitRepository and set it. We’d like to write code like this in our test setup:
public void setUp() {
PermitRepository repository = PermitRepository.getInstance();
...
// add permits to the repository here
...
PermitRepository.setTestingInstance(repository);
}
You are facing a more general problem here. If misused, Singletons hinder testabiliy.
I have done a detailed analysis of this problem in the context of a decoupled design. I'll try to summarize my points:
If your Singleton carries a significant global state, don’t use Singleton. This includes persistent storage such as Databases, Files etc.
In cases, where dependency on a Singleton Object is not obvious by the classes name, the dependency should be injected. The need to inject Singleton Instances into classes proves a wrong usage of the pattern (see point 1).
A Singleton’s life-cycle is assumed to be the same as the application’s. Most Singleton implementations are using a lazy-load mechanism to instantiate themselves. This is trivial and their life-cycle is unlikely to change, or else you shouldn’t use Singleton.