MyProject has an internal class and method as such.
namespace MyProject
{
internal class InboundMailAlertParser
{
internal InboundMailAlert ParseMessageBody(string body)
{
...
}
}
}
I'm using InternalsVisibleTo in my MyProject AssemblyInfo.cs to expose internal classes/methods to a unit test assembly.
[assembly: InternalsVisibleTo("MyProject.Tests")]
My Test looks like this
namespace MyProject.Tests
{
[TestClass]
public class InboundMailAlertParserTests
{
[TestMethod]
public void ParsesBody()
{
InboundMailAlertParser parser = new InboundMailAlertParser();
parser.ParseMessageBody(messageBody.ToString());
}
}
}
My test passes fine when run in Visual Studio, but nCrunch is failing to build the unit test project due to not being able to see the internal InboundMailAlertParser of the MyProject assembly under test. Is there another nCrunch assembly I have to indicate should have internal visiblity to allow nCrunch to be able to build the test assembly?
Turns out I had ignored a component (project) in the nCrunch config. Once I enabled that, the project could build correctly and I got my lovely green dots.
Related
I have two projects in Visual Studio, the core project which is a Windows Service Executable, and the Unit Test Project.
The core project has two original files broken out like this
File1.cs:
using static Proj.ConfigHelper;
namespace Proj
{
class MyClass
{
(lots of code)
}
}
File2.cs looks something like this.
namespace Proj
{
static class ConfigHelper
{
public static NameValueCollection AppSettings { get { return ConfigurationManager.AppSettings; } }
public static NameValueCollection CustomSection { get { return ConfigurationManager.GetSection("CustomSection") as NameValueCollection; } }
}
}
Both of those classes are internal and made visible to the unit test project via InternalsVisibleToAttribute.
Inside of the UnitTest project which is a discrete project within the same solution (and so it has its own app.config), calling ConfigHelper.AppSettings results in a 0-item collection, and calling ConfigHelper.CustomSection results in null. If I attempt to unit test a method within File1.cs that depends on those settings, they run as default values as if they were not configured at all. I don't quite understand why this is happening. Can anyone help me understand what I did wrong? It seems as though the ConfigHelper is not loading the App.Config for its own project.
The app.config for the Windows Service Project is set to "always copy" and the app.config for the unit test project is set to "never copy"
The test will use its own config so you need to mirror it. There are work runarounds: Can a unit test project load the target application's app.config file?
TLDR;
How can I create a pre-processing directive in C# based on values from an app.config file?
I am using Selenium to do integration testing. I have two test method classes which are responsible for testing different areas of my application. My test classes are identified as such with a [TestClass] attribute, and my test methods are identified using a [TestMethod] attribute like so:
[TestClass]
public class TestsForAreaX
{
[TestMethod]
public void TestFoo()
{
//Do test logic here
}
[TestMethod]
public void TestBar()
{
//Do test logic here
}
}
When I rebuild my solution all methods that have had the [TestMethod] applied will appear in the test explorer.
What I would now like to do is add some flags to my app.config to conditionally apply [TestMethod] attributes so that I can specify which tests I want run. The reason for this is that some tests are taking very long and I would like to exclude them without having to fiddle with method attributes directly.
I am aware of pre-processing directives like:
#if DEBUG
//debug mode
#elif
//release mode
#endif
but that only works for build configurations and not values in app config files, unless I am mistaken?
You cannot remove the attributes of the assembly after compilation. Maybe you are looking for Categories:
[TestClass]
public class TestsForAreaX
{
[TestCategory("LongRunning"), TestMethod]
public void TestFoo()
{
//Do test logic here
}
[TestCategory("ShortRunning"), TestMethod]
public void TestBar()
{
//Do test logic here
}
} enter code here
Then you can run tests for different categories at least from the command line, this site explains how:
http://msdn.microsoft.com/en-us/library/dd286683.aspx
I have the following code:
[TestFixture]
public class LexicalTests
{
[Test]
public void LexicalTest1()
{
TestContext.CurrentContext.TestDirectory;
}
}
CurrentContext throws an exception while attempting to get TestDirectory or WorkingDirectory property.
How can I solve this problem?
P.S.: On my home PC tests work perfectly (without strange exceptions).
It seems that some applications that offer the functionality to run NUnit unit tests have a problem with the TestContext class.
The test in class below should pass:
using NUnit.Framework;
namespace UnitTests
{
[TestFixture]
public class UnitTests
{
[Test]
public void CurrentContextTest()
{
Assert.IsNotNull(TestContext.CurrentContext);
Assert.IsNotNull(TestContext.CurrentContext.TestDirectory);
Assert.IsNotNull(TestContext.CurrentContext.WorkDirectory);
}
}
}
If the test doesn't pass then, as Dmitry wrote in his comment above, change the NUnit version in the ReSharper menu. From within Visual Studio, go to ReSharper -> Options -> Tools -> NUnit. Click the Specified NUnit installation radio button and ensure that a folder with nunit.core.dll, nunit.core.interfaces.dll and nunit.util.dll is specified. An error will be displayed if the listed files cannot be found.
Once the NUnit version has been changed, re-run the test and it should pass.
In class they taught us to add a test fixture to the same namespace as the project we're testing. For example:
namespace Project
{
class Decrypt : Cipher
{
public string Execute()
{
//Code here
}
}
[TestFixture]
{
[Test]
public void test1()
{
//Code here
}
}
}
I noticed in the c# menu on my uni computer, there was a 'Test' section (I couldn't get it to run there either, I don't know how). On this old 32b computer there isn't. I've installed NUnit-2.6.2.msi but when I try to run it, it says "Unable to find a version of runtime to run this application"
So I think I have two problems:
installing Nunit (I already have referenced the .dlls from my project separately)
using Nunit (even on a computer with it installed properly)
Normally you'd put your code in separate projects, but reference the project you're testing in the test project
//project: Xarian.Security
//file: Decrypt.cs
namespace Xarian.Security
{
class Decrypt : Cipher
{
public string Execute()
{
//Code here
}
}
}
.
//project: Xarian.Security.Test
//file: DecryptTest.cs
using System;
using NUnit.Framework;
//as we're already in the Xarian.Security namespace, no need
//to reference it in code. However the DLL needs to be referenced
//(Solution Explorer, Xarian.Security.Test, References, right click,
//Add Reference, Projects, Xarian.Security)
namespace Xarian.Security
{
[TestFixture]
class DecryptTest
{
[Test]
public void test()
{
//Code here
Cipher cipher = new Decrypt("&^%&^&*&*()%%&**&&^%$^&$%^*^%&*(");
string result = cipher.Execute();
Assert.AreEqual(string, "I'm Decrypted Successfully");
}
}
}
Right click on the test project's references, go to the Projects tab and select the main project. Once referenced you'll be able to use the classes (etc) from your main project in your test code.
I am using Rhino Mocks as a mocking framework for unit testing.
I have a class called Subject which is the class I want to test. It has a dependency on IStore.
IStore is defined as follows:
//internal interface : has InternalsVisible to both "Subject"
//and "StoreTests" class namespaces
internal interface IStore {
void Store(string name);
//other methods
}
and the Subject class is defined as follows:
class Subject : IStore {
private IStore internalStore;
//constructor injection
void Subject(IStore store) {
internalStore = store;
}
void Store(string name) {
internalStore.Store(name);
}
//other methods
}
My test class using RhinoMocks is as follows:
//test class
class StoreTests {
Subject subject = new Subject();
[Test]
public StoreTest() {
//Arrange
var mockStore = MockRepository.GenerateMock<IStore>();
string testName = "test";
mockStore.Expect(x => x.Store(testName)).Returns(null);
//Act
subject.Store(testName);
//Assert
mockStore.VerifyAllExpectations();
}
//other test methods
}
In my setup, the interface is defined as internal and it has InternalsVisible set for both Subject class and StoreTests class. However, when the test case executes, it throws an exception at var mockStore = MockRepository.GenerateMock();
saying that IStore is not public and therefore it could not generate a Mock.
I think this is because the IStore is not public. However, since I have set InternalsVisibleTo on the IStore dll, will it not be sufficent for StoreTests to create a mock for that class?
Now I think this problem may be solved by making the IStore interface public. However given that this is not an option for me, is there any other way I can create a mock for IStore ?
Did you try making the assembly internals visible to Rhino mocks?
[assembly: InternalsVisibleTo ("DynamicProxyGenAssembly2")]
See Rhino Mocks Internal Members for details.
When a class is mocked, a new class is generated at run-time which is derived from the mocked class. This generated class resides in a separate "temporary" assembly which is called "DynamicProxyGenAssembly2". So, the InternalsVisibleTo attribute needs to be set on the target assembly to allow access to its internal members from the temporary assembly; otherwise, the mock object can't override the internal member as it doesn't have access to it (which is also why the mocked method must be marked as virtual). Note that this is true even if the unit test and the tested class are in the same assembly.
So, you need to make sure that the target class' assembly makes its internals visible to the proxy assembly as such (in AssemblyInfo.cs for example):
Yep it should be enough to add following in the AssemblyInfo.cs file of an assembly under the test:
[assembly: InternalsVisibleTo("Tests.Assembly.Name")]
[assembly: InternalsVisibleTo("NUnit.Framework")]
[assembly: InternalsVisibleTo("Rhino.Mocks, PublicKey=00240000048000009400000006020000002400005253413100040000010001009D1CF4B75B7218B141AC64C15450141B1E5F41F6A302AC717AB9761FA6AE2C3EE0C354C22D0A60AC59DE41FA285D572E7CF33C320AA7FF877E2B7DA1792FCC6AA4EB0B4D8294A2F74CB14D03FB9B091F751D6DC49E626D74601692C99EAB7718ED76A40C36D39AF842BE378B677E6E4EAE973F643D7065241AD86ECC156D81AB")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
Well this might be answered, but for me it didn't work .
So here's what i did to make it work (might help others, and even me, on the next project....):
In Tool menu in Visual studio :
External tools :
Add for name i put "LongStrongName" , but put whatever you feel fit :
(this path, or wherever the sn.exe is for you):
Command:
C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\sn.exe
Arguments:
-Tp $(TargetPath)
(Click the checkbox , output to "Use output Window")
Now you can click on the project, then go to tools and go to the "LongStrongName" menu:
and VS will output :
Public key is 0240000048000009400000006020000002400005253413100040000010001009badbe86c32ec0
ec429f0b3909*********
Public key token is 6ccc051********
Open the assembly.cs and add:
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
add whatever assemblies you need , and voila (i had to put multiple assemblies).