I have some code that I need to see when I am running a test, and
TestContext would have to be part of my Test class I need the
debug.writelines of the class being tested displayed. I considered
just passing a TestContext to my MessageStatus static method and may
have to but that will be a PITA because the UnitTest class would have
to pass the TestContext to the object it is testing. Too tightly
coupled for my taste.
In basic terms
[TestMethod]
public void TestA()
{
//....
Assert.IsTrue(Blah.Blah()));
}
public void Blah()
{
Debug.WriteLine("Hello");
}
never shows up when I run the unit tests!
I could change it to:
TestContext t;
[TestMethod]
public void TestA()
{
//....
Assert.IsTrue(Blah.Blah(t)));
}
public void Blah(TestContext p1)
{
p1.WriteLine("Hello");
}
but that is insane it means changing all my signatures and tight coupling. I read the thread at How to write output from a unit test? it does not help :(
If you need to see lines produced by Debug.WriteLine or deal with assertions produced by Debug.Assert you can create your own System.Diagnostic.TraceListener to redirect output to TestContext - see my answer What do I have to do so that assertions won't block automated tests anymore?.
public class MyListenerThatDoesNotShowDialogOnFail:
System.Diagnostics.TraceListener
{
// This is to avoid message box on Debug.Assert(false);
public override void Fail(string message, string detailMessage)
{// do something UnitTest friendly here like Assert.Fail(false)
}
// This (+Write) is to redirect Debug.WriteLine("Some trace text");
public override void WriteLine(string message)
{// do something UnitTest friendly here like TestContext.Write(message)
}
}
Somewhere in the test setup listener. Note that sample below is simplified, you probably want to save current listeners and restore at the end of test.
Debug.Listeners.Clear();
Debug.Listeners.Add(new MyListenerThatDoesNotShowDialogOnFail());
You need to use Console.WriteLine for the output to show up in the test runner. However, this is a bad thing. I recommend using a logging framework like nlog.
Related
I'm tasked with writing some tests to one of our codebases.
Now I have this class:
```
public class A
{
public void method_1()
{
this.method_2();
// Do something
}
public void method_2()
{
Environment.CurrentDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
// Do something
}
}
```
Now I'm trying to write a test for method_1 without invoking method_2 and getting NullReferenceException.
[TestClass]
public class MyTestClass
{
[TestMethod]
public void MyTestMethod()
{
// Ignore the call: Assembly.GetEntryAssembly() because it returns null>
new A().method_1();
}
Any suggestion?
EDIT:
I'm not allowed to change the code.
Without the possibility to override/mock the logic inside method_2 there is not much you can do.
If it is your own codebase I suggest to move the call to Assembly.GetEntryAssembly().Location to some helper method which you can override for the tests.
Assuming you cannot change anything to the code, you can use MS Fakes to mock out static methods like DateTime.Now. Should also work on Assembly.GetEntryAssembly().
I'm not a big fan of MS Fakes though, had a few too many problems with it in the past. If you can make a small change to the code, you can make the method_2 virtual and do something like this:
public class MyTestA : A
{
public override void method_2()
{
//Do nothing
}
}
You can then write your tests against MyTestA.
Of course, putting the code in method 2 in a new class/interface and mock that as a dummy interface is an even cleaner solution.
I know, that in Coded UI there are two methods (MyTestInitialize and MyTestCleanup) which can perform action before and after each tests. I need add some action which launch before and after all tests. For example, if you familiar with rspec there are two methods before() and after(), which take parameter :each (will call before/after each tests) or :all (will call before/after all test).
Create your methods with the [ClassInitialize] and [ClassCleanup] attributes as necessary. This should be within your Test Class. Example:
[CodedUITest]
public class MyTestClass
{
[ClassInitialize]
public void DoSomethingFirst()
{
// your code here that will run at the beginning of each test run.
}
[TestInitialize]
public void RunBeforeEachTest()
{
// your test initialization here
}
[TestMethod]
public void MyTestMethod()
{
}
}
And you would do the same for your [TestCleanup] and [ClassCleanup].
More on this attribute can be found here.
I have got a standard NUnit unit test.
[TestFixture]
public class MyTest
{
[SetUp]
public virtual void Setup()
{
}
[TearDown]
public void CleanUp()
{
}
[Test]
public void Test01()
{
Assert.AreEqual(10, 10);
}
[Test]
public void Test02()
{
Assert.AreEqual(4, 1);
}
[Test]
public void Test03()
{
Assert.AreEqual(1, 51);
}
//......a huge amount of Tests
[Test]
public void TestN()
{
Assert.AreEqual(1, 1);
}
}
As you see, there are a lot of tests here. What I need to do is to handle any error in each test and to get the information about the error without modifying the body of a test method.
So in JUnit there is an interface called TestListener which allows to handle any test error, see the error message, see the name of the test, etc.
I didn't find something similar in NUnit. Does it exist? Or is there is a way to do it?
It sounds like you probably want EventListeners:
EventListeners are able to respond to events that occur in the course of a test run, usually by recording information of some kind. Note that EventListeners called asynchronously with respect to test execution and are not able to affect the actual execution of the test.
It sounds like you'll be interested in this method:
void TestFinished(TestResult result);
(As an aside, it seems odd to me that this doesn't use normal .NET events or provide a no-op interface implementation in an abstract class, but there we go...)
I'm trying to setup my tests using Xunit. I have a requirement to delete all images in a folder start of the tests, and then each method does some image resizing and saves a copy of it's output to the folder. The folder should only be emptied once, and then each method will save their own image into the folder.
When I use IUseFixture<T>, the ClearVisualTestResultFolder function is still being called before every test, so I only end up with one image in the folder.
public class Fixture
{
public void Setup()
{
ImageHelperTest.ClearVisualTestResultFolder();
}
}
public class ImageHelperTest : IUseFixture<EngDev.Test.Fixture>
{
public void SetFixture(EngDev.Test.Fixture data)
{
data.Setup();
}
public static void ClearVisualTestResultFolder()
{
// Logic to clear folder
}
}
If I put the ClearVisualTestResultFolder in the constructor, it is also being called once for every test method. I need this just run once before all test methods are executed, how can I achieve this?
If it matters, I use the ReSharper test runner.
Following the guidance in this xUnit discussion topic, it looks like you need to implement a constructor on the Fixture and also implement IDisposable. Here's a complete sample that behaves the way you want:
using System;
using System.Diagnostics;
using Xunit;
using Xunit.Sdk;
namespace xUnitSample
{
public class SomeFixture : IDisposable
{
public SomeFixture()
{
Console.WriteLine("SomeFixture ctor: This should only be run once");
}
public void SomeMethod()
{
Console.WriteLine("SomeFixture::SomeMethod()");
}
public void Dispose()
{
Console.WriteLine("SomeFixture: Disposing SomeFixture");
}
}
public class TestSample : IUseFixture<SomeFixture>, IDisposable
{
public void SetFixture(SomeFixture data)
{
Console.WriteLine("TestSample::SetFixture(): Calling SomeMethod");
data.SomeMethod();
}
public TestSample()
{
Console.WriteLine("This should be run once before every test " + DateTime.Now.Ticks);
}
[Fact]
public void Test1()
{
Console.WriteLine("This is test one.");
}
[Fact]
public void Test2()
{
Console.WriteLine("This is test two.");
}
public void Dispose()
{
Console.WriteLine("Disposing");
}
}
}
When running this from the console runner, you'll see the following output:
D:\xUnit>xunit.console.clr4.exe test.dll /html foo.htm xUnit.net
console test runner (64-bit .NET 4.0.30319.17929) Copyright (C)
2007-11 Microsoft Corporation.
xunit.dll: Version 1.9.1.1600 Test assembly: test.dll
SomeFixture ctor: This should only be run once
Tests complete: 2 of 2
SomeFixture: Disposing SomeFixture
2 total, 0 failed, 0 skipped, took 0.686 seconds
Then, when you crack open the test output file foo.htm, you'll see the other test output.
The old IUseFixture<T> interface in xUnit.net v1.x has been replaced
by two new interfaces: IClassFixture<T> and ICollectionFixture<T>. In
addition, the mechanism for injecting fixture values into your tests
has changed from property setters to constructor arguments. Class
fixtures are created once and shared amongst all tests in the same
class (much like the old IUseFixture). Collection fixtures work the
same way, except that the single instance is shared amongst all tests
in the same test collection.
NOTE this applies only to xUnit.net v1 - see the accepted answer unless that's your case
IUseFixture<T>.SetFixture gets called once for each test. The Fixture itself is only created once.
In other words, you shouldnt be doing anything in your SetFixture method, but you should be instead be triggering it in the Fixture constructor.
For one-time cleanup, implement an IDisposable.Dispose on the Fixture (it's not required though)
Note that it's a bad idea to be (even potentially) sharing state between tests. Best to use a TemporaryDirectoryFixture like this one.
I am a newbie to unit testing. How do I check the for console output?
I have
namespace XXShapes
{
public abstract class XXShape
{
public virtual void DrawXXShape()
{
Console.WriteLine("The XXShape was drawn.");
}
}
public class XXCircle : XXShape
{
public override void DrawXXShape()
{
Console.WriteLine("The XXCircle was drawn.");
}
}
}
namespace XXShapes.Test
{
[TestFixture]
public class XXShapeTest
{
[Test]
public void MyFirstTest()
{
XXShape s = new XXCircle();
string expected = "The XXCircle was drawn.";
s.DrawXXShape();
string actual = Console.ReadLine();
Assert.AreEqual(expected, actual);
}
}
}
How should I correctly be testing this?
Thanks for any pointers.
Cheers,
~ck
The literal answer would be that you would use Console.SetOut before calling the class under test to direct stdout into a memoryStream or similar, whose contents you can later inspect.
The better answer would be to use a mocking framework, like Rhino Mocks to create a concrete instance of your abstract class, with an expectation set that the DrawXXShape method would be called.
You don't need to test 'Console.WriteLine' routine because you have to assume it works - it is not your code, so why do you want to test it. You need to test whether you produce correct string that is passed to 'Console.WriteLine'
In other words, instead of:
public override void DrawXXShape()
{
Console.WriteLine("The XXCircle was drawn.");
}
you could do:
public override void DrawXXShape()
{
Console.WriteLine(produceXxCircle());
}
public string produceXxCircle()
{
return "The XXCircle was drawn.";
}
and then in the test case:
Assert.AreEqual(produceXxCircle(), "The XXCircle was drawn.");
Hope it helps.
Regads
Simon
That's not at all what you'd do.
In your test you will typically check for the state of the object, with something like:
Assert.IsTrue(foo.Field, Equals, "hello")
Depending on how your chosen framework works. So you'll need to change your approach, in general, to conform to this model.
I'm assuming that some other tests test for the drawing capabilities - If you now want to test that your classes write something in particular to the console, then you should abstract the idea of writing to the console.
Create an interface with a WriteLine() method in it and inject instances that implement this interface into XXShapes. Your tests can inject mocks or stubs which can capture the strings that are written and test their contents in the tests.