I have a console application. In release environment, it works perfectly at this time. When in IDE debug environment, I don't want the console window close, so I added this function, and calling it in the very end of my program.
[Conditional("DEBUG")]
public static void DebugWaitAKey(string message = "Press any key")
{
Console.WriteLine(message);
Console.ReadKey();
}
It works well for me, when I debug my program. But with unit testing, it still wait for a key before exiting!
The work-around is only unit-testing release edition of my program, or test other functions. But I do want something can identify current session is under unit testing, and use that flag in this function.
I believe this should answer your question. I took a class from there and adapted it to your situation.
/// <summary>
/// Detects if we are running inside a unit test.
/// </summary>
public static class UnitTestDetector
{
static UnitTestDetector()
{
string testAssemblyName = "Microsoft.VisualStudio.QualityTools.UnitTestFramework";
UnitTestDetector.IsInUnitTest = AppDomain.CurrentDomain.GetAssemblies()
.Any(a => a.FullName.StartsWith(testAssemblyName));
}
public static bool IsInUnitTest { get; private set; }
}
Then I added a line to your method which if it is running a test it will not hit the Console.ReadKey();
[Conditional("DEBUG")]
public static void DebugWaitAKey(string message = "Press any key")
{
Console.WriteLine(message);
if(!UnitTestDetector.IsInUnitTest)
Console.ReadKey();
}
Note: This would be considered a hack and would not be considered a best practice.
EDIT:
I also created a sample project on github to demonstrate this code. https://github.com/jeffweiler8770/UnitTest
The simple way if your test runs from a dedicated UnitTest project : use a flag in AppSettings...
I would not investigate around patterns for such a purpose, i would run the test in a dedicated UnitTest project with its own configuration.
If you need to collect data maybe should you simply use traces (they can be customized from your .config file)... ?
Hope this helps...
Rather than looking for whether the program was compiled in debug mode, you can look at whether a debugger is attached:
if (Debugger.IsAttached)
{
Console.WriteLine(message);
Console.ReadKey();
}
Note this will only detect if you start with F5 from Visual Studio, not Ctrl-F5 (i.e. Start with Debugging only)
I used a variation of Jeff's UnitTestDetector. I did not want to check the unit test assembly and wanted to control which unit tests would consider this or not.
So I created a simple class with IsInUnitTest defaulting to false.
Then in the unit test classes where I wanted the conditional code to run I added TestInitializer and TestCleanup where I set the bool accordingly.
Then in my regular code I can use UnitTestDetector.IsInUnitTest
Simple UnitTestDetector class:
/// <summary>
/// Detects if we are running inside a unit test.
/// </summary>
public static class UnitTestDetector
{
static private bool _isInUnitTest = false;
public static bool IsInUnitTest
{
get { return _isInUnitTest; }
set { _isInUnitTest = value; }
}
}
Unit Test to Test this stuff:
[TestClass]
public class UnitTestDetectorTest_WithoutIsInUnitTest
{
[TestMethod]
public void IsInUnitTest_WithoutUnitTestAttribute_False()
{
bool expected = false;
bool actual = UnitTestDetector.IsInUnitTest;
Assert.AreEqual(expected, actual);
}
}
[TestClass]
public class UnitTestDetectorTest_WithIsInUnitTest
{
[TestInitialize()]
public void Initialize()
{
UnitTestDetector.IsInUnitTest = true;
}
[TestCleanup()]
public void Cleanup()
{
UnitTestDetector.IsInUnitTest = false;
}
[TestMethod]
public void IsInUnitTest_WithUnitTestAttribute_True()
{
bool expected = true;
bool actual = UnitTestDetector.IsInUnitTest;
Assert.AreEqual(expected, actual);
}
}
Condition in Code:
if (UnitTestDetector.IsInUnitTest)
return "Hey I'm in the unit test :)";
I know this is old but I really don't like many of these answers, especially anything that hard codes an assembly name or version.
This works well, as long as the class you are testing is not Sealed. It's pretty simple:
Add this class variable to the class you are testing:
protected Boolean IsInUnitTestMode = false;
We default it to false so in production it will always be false.
Add something like this wrapper to your test class
class ProfileTest : Profiles
{
public ProfileTest() : base()
{
IsInUnitTestMode = true;
}
}
In this example Profiles is the class we are testing, ProfileTest is a wrapper class in the test project's namespace. It will never be deployed. The test class uses this to create an instance of the class to be tested:
ProfileTest profiles = new ProfileTest();
As opposed to this:
private Profiles profiles = new Profiles();
The we can use it something like this:
private string ProfilePath
{
get
{
if (IsInUnitTestMode)
return SafeStorage.EnsureFolderExists(Path.Combine(SafeStorage.UserPath, UNITTESTFOLDERNAME)).FullName;
else
return SafeStorage.EnsureFolderExists(Path.Combine(SafeStorage.UserPath, PROFILEFOLDERNAME)).FullName;
}
}
As I said, this won't work with sealed classes, nor will it work well with static ones. With that said the number of times I actually choose to test for the unit test condition is quite rare. This works extremely well for me.
Related
I have a class which contains an internal helper such as following code:
[assembly: InternalsVisibleTo("Tests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
namespace NS.B
{
public class A {
internal readonly B _bHealper;
public int GetBag(string s1, string s2){
return _bHelper.GetBag(s1, s2);
}
}
}
[assembly: InternalsVisibleTo("Tests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
namespace NS.B
{
internal class B
{
public int GetBag(string str1, string str2){
/// do some work
return result;
}
}
}
then I try to mock my helper inside A class and test A class GetBag function by this code:
[Fact]
public void checkBaggageRule()
{
var repo = Substitute.For<A>();
repo._bHelper.GetBag(Arg.Any<string>(), Arg.Any<string>()).Returns(30);
var result = repo.GetBag("oo", "L");
Assert.True(result != null);
Assert.True(result == 30);
}
but I am getting this exception while I debug my test:
NSubstitute.Exceptions.UnexpectedArgumentMatcherException : Argument
matchers (Arg.Is, Arg.Any) should only be used in place of member
arguments. Do not use in a Returns() statement or anywhere else
outside of a member call.
how can I mock this internal member and pass my test?
There's not quite enough code in the sample to tell for sure, but I'm not sure that the internal keyword is causing the problem here. If you make them all public instead do you get the same error?
There are a few other possible issues that could be causing problems for you here.
First, try installing the NSubstitute.Analyzers package, which will detect issues like trying to substitute for non-virtual members.
Next, the sample code does not show how A._bHelper gets initialised. Let's update it to use constructor injection, and we'll substitute for the dependency rather than the entire class under test (as pointed out by #Nkosi in the comments).
public class A
{
public A(MssqlEntityHelper helper) { _bHelper = helper; }
internal readonly MssqlEntityHelper _bHelper;
public int GetBag(string s1, string s2) {
return _bHelper.GetBag(s1, s2);
}
}
// Tests:
[Fact]
public void SampleTest() {
var repo = new NS.B.A(Substitute.For<NS.B.MssqlEntityHelper>());
repo._bHelper.GetBag(Arg.Any<string>(), Arg.Any<string>()).Returns(30);
var result = repo.GetBag("oo", "L");
Assert.True(result == 30);
}
As the NSubstitute.Analyzers package will point out, MssqlEntityHelper.GetBag() will need to be made virtual in order for NSubstitute to work with it:
public class MssqlEntityHelper {
public virtual int GetBag(string str1, string str2) { ... }
}
Those changes will get a passing test based on the sample code provided. The exact exception you are seeing may be as a result this test or problems in other tests, perhaps attempting to substitute for non-virtual members in earlier tests. Installing the NSubstitute.Analyzers package will hopefully help you find these cases. If this still doesn't resolve the problem there are a few other debugging steps we can try (running the test in isolation, running a single fixture, looking at test logs to see test execution order and seeing if preceding tests are causing problems that bleed into this test, etc.).
So in my test suite, I have an abstract base class that my integration tests inherit from. Each derivation of this base class has their own set of tests. The assertions that the child classes make are run through protected methods on the base class. During those assertions, the base class logs which values in a dictionary have been tested. After the child classes have run all their tests, I want the base class to run a test that verifies all the correct things were tested.
A few disclaimers:
Yes, I know this is an ordered test, and that those are frowned
upon. However, this is something I want to do anyway.
I know this is a test that tests my test suite, in a sense. While this is
often frowned upon, I find it useful. If you want your tests to
genuinely be your documentation, it is good to have some rudimentary
tests that verify some basic things about your documentation - that
it's complete, for example. (In most projects, this would probably
be overkill and not worth it. In this particular project, however,
it is both a personal project and an experiment in working with 100%
code coverage.)
For now, I have marked the summary test with both [Test] and [TestFixtureTearDown], which does make the test run at the end. However, it also means that when the test fails, the test suite gets angry because a tear down failed. What I want in an ideal world is something like [RunLast]. Any ideas on how one might be able to accomplish this?
Example of the code currently:
[TestFixture]
public abstract class AttributesTests : IntegrationTests
{
[Inject]
public IAttributesMapper AttributesMapper { get; set; }
protected abstract String tableName { get; }
private Dictionary<String, IEnumerable<String>> table;
private List<String> testedNames;
[TestFixtureSetUp]
public void FixtureSetup()
{
testedNames = new List<String>();
}
[SetUp]
public void Setup()
{
table = AttributesMapper.Map(tableName);
}
[Test, TestFixtureTearDown]
public void AllNamesTested()
{
var missingNames = table.Keys.Except(testedNames);
Assert.That(missingNames, Is.Empty, tableName);
}
[Test, TestFixtureTearDown]
public void NoNamesTestedNultipleTimes()
{
var duplicateNames = testedNames.Where(n => testedNames.Count(cn => cn == n) > 1).Distinct();
Assert.That(duplicateNames, Is.Empty, tableName);
}
protected void AssertAttributes(String name, IEnumerable<String> attributes)
{
testedNames.Add(name);
Assert.That(table.Keys, Contains.Item(name), tableName);
foreach (var attribute in attributes)
{
Assert.That(table[name], Contains.Item(attribute));
var actualAttributeCount = table[name].Count(a => a == attribute);
var expectedAttributeCount = attributes.Count(a => a == attribute);
Assert.That(actualAttributeCount, Is.EqualTo(expectedAttributeCount));
}
var extraAttributes = table[name].Except(attributes);
Assert.That(extraAttributes, Is.Empty);
}
}
This works for me:
namespace ZZZ
public class ZZZZZ {
[Test]
public void ZZZZLastTest() {
// Whatever . . .
}
}
There is no explicit [LastTest]-like attribute that I am aware off but I believe you can go with [Suite] instead.
I know this JUnit approach to suites will execute your test classes in lineair order as they are defined (although there is no guarantee to the order in which your tests inside one class are executed).
#RunWith(Suite.class)
#SuiteClasses({ CalculatorTestAdd.class, CalculatorTestSubtract.class })
public class AllTests {
}
Here CalculatorTestSubtract will be executed last. Keeping this in mind, I would say that you should create a suite which has your summary test at the end.
Looking at NUnit documentation, I see that something should be equally possible:
namespace NUnit.Tests
{
using System;
using NUnit.Framework;
private class AllTests
{
[Suite]
public static IEnumerable Suite
{
get
{
ArrayList suite = new ArrayList();
suite.Add(new OneTestCase());
suite.Add(new AssemblyTests());
suite.Add(new NoNamespaceTestFixture());
return suite;
}
}
}
}
You'll have to do some tests to see if they get executed linearly because an ArrayList is not guaranteed to be sorted.
I have a unit test (nUnit). Many layers down the call stack a method will fail if it is running via a unit test.
Ideally you would use something like mocking to setup the object that this method is depending on but this is 3rd party code and I can't do that without a lot of work.
I don't want setup nUnit specific methods - there are too many levels here and its a poor way of doing unit test.
Instead what I would like to do is to add something like this deep down in the call stack
#IF DEBUG // Unit tests only included in debug build
if (IsRunningInUnitTest)
{
// Do some setup to avoid error
}
#endif
So any ideas about how to write IsRunningInUnitTest?
P.S. I am fully aware that this is not great design, but I think its better than the alternatives.
I've done this before - I had to hold my nose while I did it, but I did it. Pragmatism beats dogmatism every time. Of course, if there is a nice way you can refactor to avoid it, that would be great.
Basically I had a "UnitTestDetector" class which checked whether the NUnit framework assembly was loaded in the current AppDomain. It only needed to do this once, then cache the result. Ugly, but simple and effective.
Taking Jon's idea this is what I came up with -
using System;
using System.Reflection;
/// <summary>
/// Detect if we are running as part of a nUnit unit test.
/// This is DIRTY and should only be used if absolutely necessary
/// as its usually a sign of bad design.
/// </summary>
static class UnitTestDetector
{
private static bool _runningFromNUnit = false;
static UnitTestDetector()
{
foreach (Assembly assem in AppDomain.CurrentDomain.GetAssemblies())
{
// Can't do something like this as it will load the nUnit assembly
// if (assem == typeof(NUnit.Framework.Assert))
if (assem.FullName.ToLowerInvariant().StartsWith("nunit.framework"))
{
_runningFromNUnit = true;
break;
}
}
}
public static bool IsRunningFromNUnit
{
get { return _runningFromNUnit; }
}
}
Pipe down at the back we're all big enough boys to recognise when we're doing something we probably shouldn't ;)
Adapted from Ryan's answer. This one is for the MS unit test framework.
The reason I need this is because I show a MessageBox on errors. But my unit tests also test the error handling code, and I don't want a MessageBox to pop up when running unit tests.
/// <summary>
/// Detects if we are running inside a unit test.
/// </summary>
public static class UnitTestDetector
{
static UnitTestDetector()
{
string testAssemblyName = "Microsoft.VisualStudio.QualityTools.UnitTestFramework";
UnitTestDetector.IsInUnitTest = AppDomain.CurrentDomain.GetAssemblies()
.Any(a => a.FullName.StartsWith(testAssemblyName));
}
public static bool IsInUnitTest { get; private set; }
}
And here's a unit test for it:
[TestMethod]
public void IsInUnitTest()
{
Assert.IsTrue(UnitTestDetector.IsInUnitTest,
"Should detect that we are running inside a unit test."); // lol
}
Simplifying Ryan's solution, you can just add the following static property to any class:
public static readonly bool IsRunningFromNUnit =
AppDomain.CurrentDomain.GetAssemblies().Any(
a => a.FullName.ToLowerInvariant().StartsWith("nunit.framework"));
I use a similar approach as tallseth
This is the basic code which could be easily modified to include caching.
Another good idea would be to add a setter to IsRunningInUnitTest and call UnitTestDetector.IsRunningInUnitTest = false to your projects main entry point to avoid the code execution.
public static class UnitTestDetector
{
public static readonly HashSet<string> UnitTestAttributes = new HashSet<string>
{
"Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute",
"NUnit.Framework.TestFixtureAttribute",
};
public static bool IsRunningInUnitTest
{
get
{
foreach (var f in new StackTrace().GetFrames())
if (f.GetMethod().DeclaringType.GetCustomAttributes(false).Any(x => UnitTestAttributes.Contains(x.GetType().FullName)))
return true;
return false;
}
}
}
Maybe useful, checking current ProcessName:
public static bool UnitTestMode
{
get
{
string processName = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
return processName == "VSTestHost"
|| processName.StartsWith("vstest.executionengine") //it can be vstest.executionengine.x86 or vstest.executionengine.x86.clr20
|| processName.StartsWith("QTAgent"); //QTAgent32 or QTAgent32_35
}
}
And this function should be also check by unittest:
[TestClass]
public class TestUnittestRunning
{
[TestMethod]
public void UnitTestRunningTest()
{
Assert.IsTrue(MyTools.UnitTestMode);
}
}
References:
Matthew Watson in http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/11e68468-c95e-4c43-b02b-7045a52b407e/
Somewhere in the project being tested:
public static class Startup
{
public static bool IsRunningInUnitTest { get; set; }
}
Somewhere in your unit test project:
[TestClass]
public static class AssemblyInitializer
{
[AssemblyInitialize]
public static void Initialize(TestContext context)
{
Startup.IsRunningInUnitTest = true;
}
}
Elegant, no. But straightforward and fast. AssemblyInitializer is for MS Test. I would expect other test frameworks to have equivalents.
In test mode, Assembly.GetEntryAssembly() seems to be null.
#IF DEBUG // Unit tests only included in debug build
if (Assembly.GetEntryAssembly() == null)
{
// Do some setup to avoid error
}
#endif
Note that if Assembly.GetEntryAssembly() is null, Assembly.GetExecutingAssembly() isn't.
The documentation says: The GetEntryAssembly method can return null when a managed assembly has been loaded from an unmanaged application.
Just use this:
AppDomain.CurrentDomain.IsDefaultAppDomain()
In test mode, it will return false.
I use this only for skipping logic that disables all TraceAppenders in log4net during startup when no debugger is attached. This allows unit tests to log to the Resharper results window even when running in non-debug mode.
The method that uses this function is either called on startup of the application or when beginning a test fixture.
It is similar to Ryan's post but uses LINQ, drops the System.Reflection requirement, does not cache the result, and is private to prevent (accidental) misuse.
private static bool IsNUnitRunning()
{
return AppDomain.CurrentDomain.GetAssemblies().Any(assembly => assembly.FullName.ToLowerInvariant().StartsWith("nunit.framework"));
}
Having a reference to nunit framework doesn't mean that test is actually running. For example in Unity when you activate play mode tests the nunit references are added to the project. And when you run a game the references are exist, so UnitTestDetector would not work correctly.
Instead of checking for nunit assembly we can ask nunit api to check is code under executing test now or not.
using NUnit.Framework;
// ...
if (TestContext.CurrentContext != null)
{
// nunit test detected
// Do some setup to avoid error
}
Edit:
Beware that the TestContext may be automatically generated if it's required.
I have a solution that's closer to what the original poster wanted. The issue is how to set the test flag to indicate the code is executing as part of a test. This can be implemented with 2 lines of code.
I have added an internal variable called RunningNunitTest at the top of the class. Be sure to make this an internal variable and not public. We don't want to export this variable when we build the project. Also this is how we're going to allow NUnit to set it to true.
NUnit does not have access to private variables or methods in our code. This is an easy fix. In between the using statements and the namespace add a [assembly: InternalsVisibleTo("NUnitTest")] decoration. This allows NUint access to any internal variable or method. My NUnit test project is named "NUintTest." Replace this name with the name of your NUint test Project.
That's it! Set RunningNunitTest to true in your NUnit tests.
using NetworkDeviceScanner;
[assembly: InternalsVisibleTo("NUnitTest")] // Add this decoration to your class
namespace NetworkDeviceScannerLibrary
{
public class DetectDevice
{
internal bool RunningNunitTest = false; // Add this variable to your class
public ulong TotalAddressesFound;
public ulong ScanCount;
NUnit Code
var startIp = IPAddress.Parse("191.168.1.1");
var endIp = IPAddress.Parse("192.168.1.128");
var detectDevice = new DetectDevice
{
RunningNunitTest = true
};
Assert.Throws<ArgumentOutOfRangeException>(() => detectDevice.DetectIpRange(startIp, endIp, null));
works like a charm
if (AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.FullName.ToLowerInvariant().StartsWith("nunit.framework")) != null)
{
fileName = #"C:\Users\blabla\xxx.txt";
}
else
{
var sfd = new SaveFileDialog
{ ... };
var dialogResult = sfd.ShowDialog();
if (dialogResult != DialogResult.OK)
return;
fileName = sfd.FileName;
}
.
Unit tests will skip application entry point. At least for wpf, winforms and console application main() is not being called.
If main method is called than we are in run-time, otherwise we are in unit test mode:
public static bool IsUnitTest { get; private set; } = true;
[STAThread]
public static void main()
{
IsUnitTest = false;
...
}
I was unhappy to have this problem recently. I solved it in a slightly different way. First, I was unwilling to make the assumption that nunit framework would never be loaded outside a test environment; I was particularly worried about developers running the app on their machines. So I walked the call stack instead. Second, I was able to make the assumption that test code would never be run against release binaries, so I made sure this code did not exist in a release system.
internal abstract class TestModeDetector
{
internal abstract bool RunningInUnitTest();
internal static TestModeDetector GetInstance()
{
#if DEBUG
return new DebugImplementation();
#else
return new ReleaseImplementation();
#endif
}
private class ReleaseImplementation : TestModeDetector
{
internal override bool RunningInUnitTest()
{
return false;
}
}
private class DebugImplementation : TestModeDetector
{
private Mode mode_;
internal override bool RunningInUnitTest()
{
if (mode_ == Mode.Unknown)
{
mode_ = DetectMode();
}
return mode_ == Mode.Test;
}
private Mode DetectMode()
{
return HasUnitTestInStack(new StackTrace()) ? Mode.Test : Mode.Regular;
}
private static bool HasUnitTestInStack(StackTrace callStack)
{
return GetStackFrames(callStack).SelectMany(stackFrame => stackFrame.GetMethod().GetCustomAttributes(false)).Any(NunitAttribute);
}
private static IEnumerable<StackFrame> GetStackFrames(StackTrace callStack)
{
return callStack.GetFrames() ?? new StackFrame[0];
}
private static bool NunitAttribute(object attr)
{
var type = attr.GetType();
if (type.FullName != null)
{
return type.FullName.StartsWith("nunit.framework", StringComparison.OrdinalIgnoreCase);
}
return false;
}
private enum Mode
{
Unknown,
Test,
Regular
}
Application.Current is null when running under the unit tester. At least for my WPF app using MS Unit tester. That's an easy test to make if needed. Also, something to keep in mind when using Application.Current in your code.
if (string.IsNullOrEmpty(System.Web.Hosting.HostingEnvironment.MapPath("~")))
{
// Running not as a web app (unit tests)
}
// Running as a web app
There is a really simple solution as well when you are testing a class...
Simply give the class you are testing a property like this:
// For testing purposes to avoid running certain code in unit tests.
public bool thisIsUnitTest { get; set; }
Now your unit test can set the "thisIsUnitTest" boolean to true, so in the code you want to skip, add:
if (thisIsUnitTest)
{
return;
}
Its easier and faster than inspecting the assemblies. Reminds me of Ruby On Rails where you'd look to see if you are in the TEST environment.
Considering your code is normaly run in the main (gui) thread of an windows forms application and you want it to behave different while running in a test you can check for
if (SynchronizationContext.Current == null)
{
// code running in a background thread or from within a unit test
DoSomething();
}
else
{
// code running in the main thread or any other thread where
// a SynchronizationContext has been set with
// SynchronizationContext.SetSynchronizationContext(synchronizationContext);
DoSomethingAsync();
}
I am using this for code that I want to fire and forgot in a gui application but in the unit tests I might need the computed result for an assertation and I don't want to mess with multiple threads running.
Works for MSTest. The advantage it that my code does not need to check for the testing framework itself and if I really need the async behaviour in a certain test I can set my own SynchronizationContext.
Be aware that this is not a reliable method to Determine if code is running as part of a unit test as requested by OP since code could be running inside a thread but for certain scenarios this could be a good solution (also: If I am already running from a background thread, it might not be necessary to start a new one).
I've used the following in VB in my code to check if we ae in a unit test. spifically i didn't want the test to open Word
If Not Application.ProductName.ToLower().Contains("test") then
' Do something
End If
How about using reflection and something like this:
var underTest = Assembly.GetCallingAssembly() != typeof(MainForm).Assembly;
The calling assembly will be where your test cases are and just substitute for MainForm some type that's in your code being tested.
I'm trying to write a C# unit test with VS 2008's built-in unit testing framework and the method I'm testing calls Environment.Exit(0). When I call this method in my unit test, my unit test is Aborted. The method should indeed be calling Exit, and I want a way to test that it does, and also to test the exit code that it uses. How might I do this? I looked at Microsoft.VisualStudio.TestTools.UnitTesting Namespace but didn't see anything that looked relevant.
[TestMethod]
[DeploymentItem("myprog.exe")]
public void MyProgTest()
{
// Want to ensure this Exit's with code 0:
MyProg_Accessor.myMethod();
}
Meanwhile, here's the gist of the code that I want to test:
static void myMethod()
{
Environment.Exit(0);
}
Edit: here's the solution I used in my test method, thanks to RichardOD:
Process proc;
try
{
proc = Process.Start(path, myArgs);
}
catch (System.ComponentModel.Win32Exception ex)
{
proc = null;
Assert.Fail(ex.Message);
}
Assert.IsNotNull(proc);
proc.WaitForExit(10000);
Assert.IsTrue(proc.HasExited);
Assert.AreEqual(code, proc.ExitCode);
You'll need to create a wrapper for the Environment class, then use the wrapper in your code. For your unit tests, inject a mock version of the wrapper. The following example uses RhinoMocks to verify that the method calls the wrapper with the expected argument.
public class EnvironmentWrapper
{
public virtual void Exit( int code )
{
Environment.Exit( code );
}
}
public class MyClass
{
private EnvironmentWrapper Environment { get; set; }
public MyClass() : this( null ) { }
public MyClass( EnvironmentWrapper wrapper )
{
this.Environment = wrapper ?? new EnvironmentWrapper();
}
public void MyMethod( int code )
{
this.Environment.Exit( code )
}
}
[TestMethod]
public void MyMethodTest()
{
var mockWrapper = MockRepository.GenerateMock<EnvironmentWrapper>();
int expectedCode = 5;
mockWrapper.Expect( m => m.Exit( expectedCode ) );
var myClass = new MyClass( mockWrapper );
myclass.MyMethod( expectedCode );
mockWrapper.VerifyAllExpectations()
}
This sounds like an incredibly bad idea. Environment.Exit(0), will obviously do as prescribed, hence why your unit testings are breaking.
If you really want to still test this you can by launching a seperate process and checking the return code- have a look at wrapping it up in Process.Start.
I guess another option is factoring this code out and injecting a test spy, or using a mock object to verify correct behaviour.
Perhaps you can do something with Typemock Isolator- I believe this lets you mock static methods.
You won't be able to test this - Environment.Exit kills the application completely. This means that any AppDomain that uses this code will be unloaded completely, whether it is your production application or the unit testing framework.
Your only option here would be to mock the Environment class with a fakie Exit method.
You can add an argument to your method to pass it a fake environment where the exit() method won't exit.
You can this parametrized method extracted from the method called from your application, and unit test the extracted function. That way, you won't have to modify your app.
The only thing that comes to my mind is something along:
static void myMethod()
{
DoEnvironmentExit(0);
}
static void DoEnvironentExit(int code)
{
#if defined TEST_SOLUTION
SomeMockingFunction(code);
#else
Environment.Exit(code);
#endif
}
I want that my unit tests to cover my POCO's.
How should I test them?
What If I add a new property? How to make my test fail?
Testing the properties and methods I know, but the problem is, how to make sure my tests fail is anything is added to my poco's.
Testing is about verifying whether what is written is able to do what it should do, nothing more, nothing less. So if you write some code, you do that for a reason. Your tests should reflect that the code indeed matches the reason you wrote the code for. That's it, there's nothing else. I.o.w.: if you write a bunch of classes, you should test whether the behavior you've written indeed is correct compared to what the behavior should do.
From the reading of your question, you either misunderstand what a POCO is, or you misunderstand unit testing.
A POCO is just an old fashioned object. It has state and behavior. You unit test the state by putting (setting) values in to the properties, and asserting that the value is what you expected. You unit test behavior by asserting expectations against methods.
Here would be an oversimplified example of a POCO and its tests. Notice that there's more test code than implementation code. When unit testing is done right (TDD), this is the case.
public class Person
{
private Name name = Name.Empty;
private Address address = Address.Empty;
private bool canMove;
public Name Name
{
set { name = value; }
get { return name; }
}
public Address Address
{
private set { address = value; }
get { return address; }
}
public bool CanMove
{
set { canMove = value; }
get { return value; }
}
public bool MoveToNewAddress(Address newAddress)
{
if (!CanMove) return false;
address = newAddress;
return true;
}
}
[TestFixture]
public class PersonTests
{
private Person toTest;
private readonly static Name NAME = new Name { First = "Charlie", Last = "Brown" };
private readonly static Address ADDRESS =
new Address {
Line1 = "1600 Pennsylvania Ave NW",
City = "Washington",
State = "DC",
ZipCode = "20500" };
[SetUp]
public void SetUp()
{
toTest = new Person;
}
[Test]
public void NameDefaultsToEmpty()
{
Assert.AreEqual(Name.Empty, toTest.Name);
}
[Test]
public void CanMoveDefaultsToTrue()
{
Assert.AreEqual(true, toTest.CanMove);
}
[Test]
public void AddressDefaultsToEmpty()
{
Assert.AreEqual(Address.Empty, toTest.Address);
}
[Test]
public void NameIsSet()
{
toTest.Name = NAME;
Assert.AreEqual(NAME, toTest.Name);
}
[Test]
public void CanMoveIsSet()
{
toTest.CanMove = false;
Assert.AreEqual(false, toTest.CanMove);
}
[Test]
public void AddressIsChanged()
{
Assert.IsTrue(toTest.MoveToNewAddress(ADDRESS));
Assert.AreEqual(ADDRESS, toTest.Address);
}
[Test]
public void AddressIsNotChanged()
{
toTest.CanMove = false;
Assert.IsFalse(toTest.MoveToNewAddress(ADDRESS));
Assert.AreNotEqual(ADDRESS, toTest.Address);
}
}
In order to make the test fail first, stub the methods or properties, but do not implement any behavior. Run the tests, watch them fail, then add in behavior one line at a time until it passes. Once it passes, stop. Do not write any more code unless you write more tests (unless you're refactoring, in which case you do not add behavior).
I believe that you shouldn't test
the framework along with your own code
for example if you have a auto
generated property like this:
public string Name
{get;set;}
it's not necessary to have a test
method to see if it's working fine.
You should not test the inner state of you class instead you should test its behavior.
Sometimes (some may say always) it's better to write the test before writing the code.This way you have to understand what you want do to instead of understanding how to do it.(This approach is called test driven development)
Here's the TDD cycle:
Write the test and get a red signal
Write the code and get a green signal
Refactor the code and you should get
a green signal
If you want to add a new feature to the class, write a test that fails because the feature has not been implemented, then implement the feature and see the test pass.
Or...
Run code-coverage metrics as part of the build. They will indicate if code gas been added without being covered by the tests.
Or...
Run mutation tests as part of the build. They will indicate if any tests that cover the code are just running through it and not actually testing anything.
Or all of the above.
Perhaps by POCOs you meant DTOs, in which case the answer would be:
No you should not test your DTOs -- rather, test the services that work with them.