Unit Test can't see friend class variables - c++11

I'm converting Google tests to Visual Studio Native unit tests. I'm running into an issue where the Visual Studio unit test isn't seeing variables of it's friend class. Any idea how to fix this?
In my VSUT-Br.cpp class (ported from Google unit test):
#include "DocFriendClass.h
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace VSUTBr
{
TEST_CLASS(BrTest)
{
public:
protected:
virtual ~BrTest();
virtual void SetUp();
virtual void TearDown();
std::unique_ptr<DocFriendClass> TestDoc;
...
TEST_METHOD_INITIALIZE(File_Initialize)
{
pP = CreateP();
TestDoc = std::make_unique<DocFriendClass>(OurString("Test"));
TestDoc->m_Parser.setParser(pP); //it can't see m_Parser either
...
OurString sColor(kszColor);//it's not seeing kszColor in friend
}
};
}
In my DocFriendClass.h:
...
private:
Parser m_Parser;
...
#ifdef UNIT_TEST
friend class BrTest;
#endif
Then I went to my VSUT-Br project and right clicked and selected properties, and edited the C/C++ Preprocessor settings; Preprocessor Definitions now include UNIT_TEST=1. I clean built and it still couldn't find the friend variable. I exited VS and went back in, and clean built and it's not finding the friend variable. It worked having that as a friend with the old Google test. Any ideas?
I looked at unit test friend but it's not the same problem. I found elsewhere and they were saying I can't have a friend to my VS Unit Test, but I have a feeling that's internet garbage (can't find link now).
Update: I added some info on a variable, m_Parser in DocFriendClass that it's not seeing. Error info:
C2248 'DocFriendClass::m_Parser': cannot access private member declared in class 'DocFriendClass'. File VSUT-Br.
It should be able to access this. The Google test could as a friend.

We wound up working around the issue by making the private variables we were accessing public. Then it didn't need to be a friend anymore. (they just shared nicely)

Related

Why am I getting a warning to include pch.h even though it's already included?

I'm trying to reproduce an issue, so I have created an empty MFC C++ application using the VS2019 wizard and a separate native Unit Test project.
Before adding the Unit Test project, the MFC application compiled and launched successfully.
The MFC application still compiles successfully, but the Unit Test project will not compile. I'm getting two errors:
E0035 #error directive: "include 'pch.h' before including this file for PCH"
C1189 #error: "include 'pch.h' before including this file for PCH"
However, the only file in the Unit Test project (UnitTest1.cpp) already includes pch.h at the top of the file:
#include "pch.h"
#include "CppUnitTest.h"
#include "../MFCApplication1/MFCApplication1.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTest1
{
TEST_CLASS(UnitTest1)
{
public:
TEST_METHOD(TestMethod1)
{
CMFCApplication1App app;
bool result = app.InitInstance();
Assert::IsTrue(result);
}
};
}
It seems to be telling me to do something that is already done.
What's going on here?
Try to include stdafx.h and remove pch.h, it resolves the issue
I had the same issue. I found that I could not include the MFC DLL project's default header file directly. In your example this would be #include "../MFCApplication1/MFCApplication1.h"
I eventually found this example MFC DLL project code: https://github.com/Microsoft/VCSamples/tree/master/VC2010Samples/MFC/advanced from a list of examples here.
Notice that in the example that the default header/implementation files created by the MFC DLL project creation wizard (in this example, DLLScreenCap.h) don't export or provide any additional functionality. An existing MFC DLL project that I work with did the same.
So I added a class to the MFC DLL project to be tested and exported a simple function from it, and tested this exported function from my unit test project after linking to the project under test.
Exported class and function look like this:
#pragma once
class __declspec(dllexport) MFCLibraryExports
{
public:
// tests returning 17 to test unit test library against an mfc project
int SampleExport();
};
In your example I know that you are trying to test an instanced app and my answer doesn't help with that, but I was able to confirm that I can test at least a function exported from an MFC DLL project using the MS Unit Test framework. I'm not sure if you are expected to be able to get access to the application from a unit test as in your example; I am not able to include that header directly.

Eclipse can't understand boost and smart pointers?

We're using Eclipse CDT for C++ 11 code. I have a class I need to refactor so it can be tested. We're using Google Test/Google Mock to write our unit tests. One class contains a Boost socket, like such:
class BoostUser {
...
private:
...
boost::asio::ip::udp::socket theSocket;
....
}
We need to mock calls coming back from the socket, so we decided to change theSocket to a pointer and inject it via the constructor. Since we're using C++ 11, I used a unique_ptr. So our member changed to this:
class BoostUser {
...
private:
...
std::unique_ptr<boost::asio::ip::udp::socket> theSocket = nullptr;
....
}
I changed all the uses of theSocket to use -> instead of .. So calls changed from something like this:
theSocket.open(listenEndpoint.protocol());
to this:
theSocket->open(listenEndpoint.protocol());
I compiled it, it compiled fine with no errors. I already had a few unit tests, and they still worked. I started to change the constructor so it took another parameter, the socket for the dependency injection. And that's when I noticed a peculiarity.
All the instances where I changed the dot . to the arrow -> showed as errors. The Eclipse errors reported "Method '[function_name] could not be found'". It showed them for every instance where I made the changes, but, remember, it compiled with no errors. If these were real errors, I would've gotten compile errors.
As an experiment, I changed the smart pointers to just a raw pointer, like this:
boost::asio::ip::udp::socket* theSocket = nullptr;
And Eclipse was perfectly happy with that. It still compiled fine, and Eclipse didn't show any errors. But since this is C++ 11, we're using unique_ptr all over the place, and Eclipse is perfectly happy with them. It's just in this instance where Eclipse freaks out over smart pointers, and I can't check in code that uses raw pointers.
Has anyone else run across this problem with Eclipse, smart pointers and Boost classes?

Visual Studio unit test not working and not showing tests

I am following MSDocs guide to put up some unit testing. I've never used them before and I've never been using them because to me they are totally useless, but I see it's a common practice, so I wanted to learn more.
Obviously, this is not working.
I've put up some .NET Standard 2.0 libraries with little to no code to do some log4net logging. I've addet a "Unit test project" as the guide suggests and added a method decorated with the "TestMethod" attribute and all the other attributes.
Test explorer windows does not show any test and I'm not able to even run them in any way. What am I missing?
Here's the code
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MrLogger_netstandard;
namespace UnitTests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void ErrorLogOnFile_Default() => MrLogger.Instance.FileErrorLog("I'M AN ERROR!!! :)");
}
}
The MrLogger class it's just a class that does logger.Debug("Write message"), a classical log4net logging call.
I've tried this too and it changes nothing.
Jeez... help
For anyone wondering, I had to start visual studio as administrator and then it worked.... UGH! :(

Visual Studio Unit Test: Unresolved external symbol

I'm trying to set up a test environment using VS2015. The test project and the project to be tested both reside in the same solution and I've added a reference to the project to be tested. The code to be tested is configured as a DLL. In The object browser, things look like this, which seems to suggest that my test subjects are available to the UnitTest1 project:
Still, when I actually try to use build a simple test case I get unresolved exteral UnitTest1 symbol[...].
The actual test code is:
TEST_METHOD(TestMethod1)
{
int value = 2;
Testee t;
t.set_attribute(value);
//TODO add actual assertions
}

Debugging Nunit Tests inside VS2010 Express

I have written a bunch of unit tests inside VS2010 Express and tests being tests they sometimes fail. Since the express editions of VS don't allow plugins to run I can't simply spin up TestDriven.Net or an equivalent and debug the tests. To try and work around this I've converted my test assembly into a console app and made the main method look like this:
class CrappyHackToDebugUnitTestInVSExpress
{
public static void Main()
{
AppDomain.CurrentDomain.ExecuteAssemblyByName(
#"C:\Program Files\NUnit 2.5.5\bin\net-2.0\nunit-console.exe",
new [] { Assembly.GetExecutingAssembly().Location, "/framework:4.0" });
}
}
In theory I should be able to run this up, set break points in my test. If it worked it would be an acceptable work around, but I keep getting the following:
FileLoadException
Could not load file or assembly 'C:\\Program Files\\NUnit 2.5.5\\bin\\net-2.0\\nunit-console.exe'
or one of its dependencies. The given assembly name or codebase was invalid.
(Exception from HRESULT: 0x80131047)
Now the file exists and when run manually nunit-console runs fine. What might be my problem?
Basically you need to convert your assembly to Windows Forms app, add reference to the nunit-gui-runner.dll assembly and change your Main method to look like this:
[STAThread]
static void Main()
{
NUnit.Gui.AppEntry.Main(new string[] { Assembly.GetExecutingAssembly().Location });
}
here is another example:
...
using NUnit.Gui;
namespace __libs
{
class Program
{
[STAThread]
static void Main(string[] args)
{
NUnit.Gui.AppEntry.Main(new string[] { #"C:\test\bin\Debug\test.exe" });
}
}
}
This will allow you to step into certain tests but is not very good for a red green cycle, so you will want to use this only when debugging and not in other circumstances.
I played with your concept and it appears the issue isn't directly from loading the file, but from dependencies.
I used the following modified code:
And the error was actually a failure to locate nunit.core.dll, which is in the /lib directory.
try
{
String NUnitPath = #"C:\Program Files\NUnit 2.5.7\bin\net-2.0\nunit-console.exe";
AssemblyName asmName = System.Reflection.AssemblyName.GetAssemblyName(NUnitPath);
AppDomain.CurrentDomain.ExecuteAssemblyByName(asmName, new[] { Assembly.GetExecutingAssembly().Location, "/framework:4.0" });
}
catch (Exception ex)
{
Trace.WriteLine(ex.Message);
Trace.WriteLine(ex.StackTrace);
}
(I like getting System.Reflection.AssemblyName because you can inspect and see that everything's in order verses the raw file path.)
A quick bulk copy (xcopy nunit.*.dll) into my test projects' debug directory and it ran just fine. (It should be trivial to discover the minimal dependencies required)
Tested in VC# 2010 Express with NUnit 2.5.7 (breakpoints work, but I didn't really play with any other options.) Although I'm sure you could make a passable build option from it.
Cheers!
PS - First post here so I'm a bit untested as to getting the 'code' blocks formatted. Sorry in advance..
I had a similar problem trying to debug unit tests in VS C# express. Had a hard time getting it to work properly but then I found out about this project template. Works perfectly in C# Express!
http://visualstudiogallery.msdn.microsoft.com/b8a7a8fa-9f5a-4b9b-8e8b-8839a4364f26?SRC=VSIDE
C# Project Template
Integrated tests with Visual Studio, including Visual C# Express
version
Self contained NUnit console runner. Allow to write test fixtures and
test, running from Visual Studio simply by pressing F5 (support test
debugging), or Ctrl-F5 free run with results in console window. In
case of test failure indicate by beep sound.
Contains essential NUnit modules to start test project. No external
dependencies. Simply create new project, using NUnit Test Application
template.

Resources