Gallio unit test startup code - unit-testing

This is going to be an amateur level question. Is there a way to add start up code to a test project that uses MBUnit 3.4.0.0? I tried adding [TestFixture] and [FixtureSetUp] attributes to code that I wanted to run first, but unfortunately that didnt help.

The [FixtureSetUp] should be executed once before any test of the tests contained within the [TestFixture], but the two cannot be used interchangeably.
Here's a quick example. Admittedly the class doesn't have to be decorated with the [TestFixture] attribute, but it's good practice.
[TestFixture]
public class SimpelTest
{
private string value = "1";
[FixtureSetUp]
public void FixtureSetUp()
{
// Will run once before any test case is executed.
value = "2";
}
[SetUp]
public void SetUp()
{
// Will run before each test
}
[Test]
public void Test()
{
// Test code here
Assert.AreEqual("2", value);
}
[TearDown]
public void TearDown()
{
// Will run after the execution of each test
}
[FixtureTearDown]
public void FixtureTearDown()
{
// Will run once after every test has been executed
}
}

Related

Mstest [ClassCleanup] not executed at all in VS 2019

[ClassInitialize]
public static void BeforeCls(TestContext tc)
{
Console.WriteLine("ClassInitialize - Before Class");
}
[ClassCleanup]
public static void AfterCls()
{
Console.WriteLine("ClassCleanup - After Class");
}
[TestInitialize]
public void BeforeMethod()
{
Console.WriteLine("TestInitialize - Before Method");
}
[TestCleanup]
public void AfterMethod()
{
Console.WriteLine("TestCleanup - After Method");
}
[TestMethod]
public void TestMethod1()
{
Console.WriteLine("Test Method - 1");
}
Class cleanup is never executed in this code.
here is the Output
ClassInitialize - Before Class
TestInitialize - Before Method
Test Method - 1
TestCleanup - After Method
Invested a bit more time and discovered that using this will work within a test class:
[ClassCleanup(InheritanceBehavior.None))]
public static void ClassCleanup()
{
// Your code goes here
}
And using that will work for a derived test class:
[ClassCleanup(InheritanceBehavior.BeforeEachDerivedClass)]
public static void ClassCleanup()
{
// Your code goes here
}
You can read more about it here.
If the solution is not working for you no matter what, you can define IDisposable. The code will look something like this:
[TestClass]
public class DisposableBaseTest : IDisposable
{
// Your initialize methods
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~DisposableUserBaseTest()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// Your cleanup code
Console.WriteLine("ClassCleanup - After Class");
}
}
}
P.S. And according to carlin.scott from this post, if you receive an exception during ClassInitialize, you want to handle this separately.
ClassCleanup is executed - put a breakpoint inside your method and verify it yourself. Problem is, that this method is executed after all of your tests are completed, so you cannot write message from that method in test output report. This is similar to ClassInitialize method. If you have multiple tests in your file, your ClassInitialize will write a message to only one of them.

How to unit test functions that must occur in pairs?

Quite often I have some functions that must occur in pairs such as
//Example
startSomething()
...
stopSomething()
//Example
openSomething()
...
closeSomething()
while unit testing startSomething() and openSomething() is easy since they require no prior conditions / setup, how should I unit test their counterparts which require the prior to be called?
The majority of unit test frameworks have setup tests which are called before/after all, and/or each, of the test cases. Take NUnit as example:
[TestFixture]
public class MyTest
{
[OneTimeSetup]
public void GeneralSetup()
{ ... } //Called before starts all test cases
[OneTimeTearDown]
public void GeneralTearDown()
{ ... } //Called after all test cases are finished
[Setup]
public void Setup()
{ ... } //Called before each test case
[TearDown]
public void TearDown()
{ ... } //Called after each test case
[Test]
public void Test1()
{ ... }
[Test]
public void Test2()
{ ... }
}

Mockito Mock log4j appender is not invoked while running unit test

I am trying to unit test the log statements generated in my code. I am using slfj, log4j and Mockito. I am using the similar code as below from the blog at
http://bloodredsun.com/2010/12/09/checking-logging-in-unit-tests/
When I run the test it throws exception saying that there are 0 invocations at line:
verify(mockAppender).doAppend(captorLoggingEvent.capture());
Error Message:
Wanted but not invoked: mockAppender.doAppend();
-> at testClass.testLogAdviceAfterReturning(DpsOpsLoggerTest2.java:94) Actually, there were zero interactions with this mock.
I see the logs printed on the console though. Request you to kindly help.
#RunWith(MockitoJUnitRunner.class)
public class ExampleThatLogsTest {
#Mock
private Appender mockAppender;
#Captor
private ArgumentCaptor captorLoggingEvent;
#Before
public void setup() {
LogManager.getRootLogger().addAppender(mockAppender);
}
#After
public void teardown() {
LogManager.getRootLogger().removeAppender(mockAppender);
}
#Test
public void shouldConcatAndLog() {
//given
ExampleThatLogs example = new ExampleThatLogs();
//when
String result = example.concat("foo", "bar");
//then
assertEquals("foobar", result);
verify(mockAppender).doAppend(captorLoggingEvent.capture());
LoggingEvent loggingEvent = captorLoggingEvent.getValue();
//Check log level
assertThat(loggingEvent.getLevel(), is(Level.INFO));
//Check the message being logged
assertThat(loggingEvent.getRenderedMessage(),
is("String a:foo, String b:bar"));
}
}
I tried to emulate your case ,At my end it is working fine
//Log Util
public class LogUtil{
final static Logger logger = Logger.getLogger(LogUtil.class);
public static Log`enter code here`ger getLogger()
{
return logger;
}
//class
public class RunMe {
public String runMe(String parameter) {
LogUtil.getLogger().info("This is info : " + parameter);
return "In runner " + parameter;
}
}
// Unit Test
#RunWith(MockitoJUnitRunner.class)
public class LoggerTest {
#Mock
private Appender mockAppender;
#Captor
private ArgumentCaptor captorLoggingEvent;
#Before
public void setup() {
LogUtil.getLogger().addAppender(mockAppender);
}
#Test
public void shouldConcatAndLog() {
RunMe runner=new RunMe();
String result=runner.runMe("XYZ");
assertEquals("In runner XYZ",result);
verify(mockAppender).doAppend((LoggingEvent) captorLoggingEvent.capture());
LoggingEvent logevent= (LoggingEvent) captorLoggingEvent.getValue();
assertThat(logevent.getLevel(), is(Level.INFO));
}
#After
public void tearDown() {
LogUtil.getLogger().removeAllAppenders();
}
}
I know this is a little bit outdated, but I was struggling with this too. I was logging statements at DEBUG level in the class under test. My configuration in logback.xml for the class under test was set to INFO. Changing my logging statement to INFO allowed the test to pass. In addition, I also read this Github post that is really concise and a clean implementation of testing log output. Hope others will find it useful.

Nesting test runners

I am trying to find out whether and how it is possible to nest JUnit test runners, e.g. combine a GuiceJUnitRunner, a Parameterized and a HierarchicalcontextRunner.
To me, it seems that JUnit was not designed to achieve this easily, otherwise BlockJUnit4ClassRunner should have a method which passes the next Runner as an argument.
Someone also implemented a ParallelParameterized runner, which looks to me like combining Parallel and Parameterized was not easily possible.
When googling for "nested" and "JUnit", it comes up with lots of information for nested classes, but I'm looking for nesting Runners, not classes.
There is something called NestedRunner for running plain old Java classes in nested configuration.
your test starts with #RunWith(NestedRunner.class) and here is the example that I found:
#RunWith(NestedRunner.class)
public class ListTest {
// inner class for sharing common context
public class WithArrayList {
// some context for these tests
ArrayList<String> list = new ArrayList<String>();
public class WhenEmpty {
#Test
public void itIsEmpty() {
assertTrue(list.isEmpty());
}
public class AfterAddingAnElement {
// some more context for these tests
String element = "Element";
// you can use instance initializer to initialize your context
// it will be run once per test
{
// the list is still empty in here
assertTrue(list.isEmpty());
list.add(element);
}
#Test
public void itIsNotEmpty() {
assertFalse(list.isEmpty());
}
#Test
public void itContainsTheElement() {
assertTrue(list.contains(element));
}
#Test
public void addingAnotherElementIncreasesSize() {
int sizeBeforeAdding = list.size();
list.add("AnotherElement");
assertThat(list.size(), is(greaterThan(sizeBeforeAdding)));
}
#Test
public void listSizeIsStillOne() {
assertThat(list.size(), is(equalTo(1)));
}
}
#Test
public void isStillEmpty() {
assertTrue(list.isEmpty());
}
}
public class WithTwoElements {
#Before
public void init() {
list.add("Element1");
list.add("Element2");
}
#Test
public void hasSizeOfTwo() {
assertThat(list.size(), is(equalTo(2)));
}
}
}
}
and here is the source for further info

2 Questions about nUnit

I have 2 questions about functionality of nunit.
What is the difference between [TestFixtureSetUp] and [SetUp] attributes ?
I am writing a some class with tests and I see that half of my test functions need one setup,
And an another half needs another set up.
How can I have in one class two little different SetUp functions that are called with different functions
Thanks.
Method marked with [TestFixtureSetUp] attribute will be executed once before all tests in current test suite, and method marked with [SetUp] attribute will be executed before each test.
As for class with tests which contains tests requring different set up functions. Just split this class in two - each one with it's own SetUp function.
[TestFixture]
public void TestSuite1
{
[SetUp]
public void SetUp1()
{
...
}
[Test]
public void Test1()
{
...
}
}
[TestFixture]
public void TestSuite2
{
[SetUp]
public void SetUp2()
{
...
}
[Test]
public void Test2()
{
...
}
}
or call SetUp function explicitly
[TestFixture]
public void TestSuite
{
public void SetUp1()
{
...
}
public void SetUp2()
{
...
}
[Test]
public void Test1()
{
SetUp1();
...
}
[Test]
public void Test2()
{
SetUp2();
...
}
}
A TestFixtureSetup method is executed once before any of the test methods are executed. A Setup method is executed before the execution of each test method in the test fixture.
How can I have in one class two
little different SetUp functions that are
called with different functions
You can't have two different SetUp functions in a single class marked as TestFixture. If individual tests need some initialization then it makes sense to put the initialization code inside those function themselves.
I see that half of my test functions
need one setup
I think then you need to factor out the tests...