Unit Testing a method containing Environment.Exit() call within it - c#

I have a public method say,
public void ErrorEncounter()
{
//Global Error Counter
gblErrorCount++;
//Process tremination
Environment.Exit();
}
This method terminates whenever it is called. However, it will update the Global Error Count which i'm suppose to test. Is there any way to perform Unit Testing on this method?
I'm Using NUnit Framework for Unit Testing.

This method is designed to be difficult to test!
Most obviously, because it terminates the application when called. But also because it changes a global (I assume static) variable. Both of these things prevent writing a good unit test that calls the method.
Three ways around this:
1. Eliminate the method
2. Don't test the method
3. Modify the method
Option 1. If this method only called exit, then you could simply drop it and call Exit directly. However, that would make some other method difficult to test, so this isn't really a great option.
Option 2. Sometimes a method is so simple that you can avoid testing it. Whether this is such a method depends on how gblErrorCount is used elsewhere. It would appear, however, that incrementing the count has no effect, since the process immediately exits.
Option 3. Modify the method and those methods that call it. One approach would be to use an event handling mechanism and terminate the app in the event handler. You could make this easier to test by injecting a different event handler when running tests.
IOW, this is basically a pretty untestable method. Hopefully, you are in control of the system under test and can change it.

This question contains answers that show how Environment.Exit() can be tested.
Constructor Dependency Injection
One option is to convert it into a dependency by injecting it through an interface :
interface ITerminator
{
void Exit();
}
class RealTerminator
{
void Exit()=>Environment.Exit();
}
public class MyErrorChecker
{
ITerminator _terminator;
public class MyErrorChecker(ITerminator terminator)
{
_terminator=terminator;
}
public void ErrorEncounter()
{
//Global Error Counter
gblErrorCount++;
//Process tremination
_terminator.Exit();
}
}
The test project will implement a fake terminator class that sets a flag if Exit is called:
class FakeTerminator:ITerminator
{
public bool Called{get;private set;}
public void Exit()
{
Called=true;
}
}
Mocking
Another option is to mock it by extracting the call to a virtual method that can be replaced in a mock class :
public void ErrorEncounter()
{
//Global Error Counter
gblErrorCount++;
//Process tremination
ForceExit();
}
internal virtual void ForceExit()
{
Environment.Exit();
}
The test project could create a mock error checker class:
class MockErrorChecker:MyErrorChecker
{
public bool Called{get;private set;}
public override void ForceExit()
{
Called=true;
}
}
Function injection
This option isn't included in the linked question. Pass an exit Action as a parameter to ErrorEncounter whose default will be to call Environment.Exit() :
public void ErrorEncounter(Action exitFn=null)
{
var doExit=exitFn ?? (()=>Environment.Exit());
//Global Error Counter
gblErrorCount++;
//Process tremination
doExit();
}
The test could pass its own function that sets a flag:
[Test]
public void Test_Exit_Is_Called
{
bool called;
void fakeExit() { called=true; }
thatClass.ErrorEncounter(fakeExit);
Assert.True(called);
}

Related

NUnit - Unit Test - Dispose issue

namespace Game.SoccerGame
[TestFixture]
public class Score_is_0_0 : SoccerGame
{
[SetUp]
public void SetUp()
{
GivenTheScoreIs(0,0);
}
[TearDown]
public void CleanUp()
{
}
[Test]
public void When_Team1_Scores()
{
WhenTeam1Scores();
Assert.That(ScoreOutput, Is.EqualTo("1:0"));
}
[Test]
public void When_Team2_Scores()
{
WhenTeam2Scores();
Assert.That(ScoreOutput, Is.EqualTo("0:1"));
}
}
Expected:
When_Team1_Scores() = 1:0
When_Team1_Scores() = 0:1
When I run the tests individually they work as expected.
The issue I am having is when I run the tests in the class all at the same time. When I do this the results are:
When_Team1_Scores() = 1:0
When_Team1_Scores() = 1:1
the ScoreOutput keeps its state after the first test and thus my second test fails
What is the best approach the kill the state in-between tests in the TearDown?
I have the object below in a separate class SoccerGame that I inherit that controls the score state
public abstract class SoccerGame : IDisposable
private SetScore currentScore = new SetScore();
protected string ScoreOutput => currentScore.ToString();
public void Dispose()
{
}
I tried to use IDisposable but it doesn't see to work or I am implementing it wrong?
When using NUnit, a single instance of the fixture is created and used for all the tests in the fixture. Because of that, any state that needs to be initialized should be taken care of in the SetUp method, which runs before each test.
You don't show the code for your method GivenTheScoreIs but it sounds like it's supposed to initialize the score. To ensure that it is working correctly, add a test that verifies the score is set (0:0).
The above should work. However, I recommend going a step further and not inheriting from SoccerGame, which is presumably the class you are testing. While inheriting a test in this way is occasionally useful, it isn't the normal or the cleanest way to do it. It's better to separate your system under test from the tests themselves.
To do that, I suggest you instantiate a new SoccerGame for each test, doing so in the SetUp method. That will eliminate any possibility of state carrying over from one test to another since each test will use a new SoccerGame.

Chaining class inheritance with overriding methods

As part of a big framework (so i cant post a MCVE unfortunately) i am trying to inherit a couple of times to hide necessary initialization from the user of the class so the structure is
// internal base class
public class InternalBase
{
// declared internal to avoid subclassing by user - visibility
// is handled in AssemblyInfo.cs so library can subclass
internal InternalBase()
{
}
public virtual void startup()
{
// perform necessary initialization
}
}
// public base class the users should inherit from
public class PublicBase : InternalBase
{
public override void startup()
{
// call base class to perform required init
base.startup();
// perform extra steps like check if init was performed correctly
}
}
// user class trying to use the provided functionaly
public class Test : PublicBase
{
public override void startup()
{
// this is put here by convention/template to ensure execution of
// required init - if this could be avoided, even better
base.startup();
// users are allowed to put their own init here
// perform user init code
}
}
Now as soon as i want to step into base.startup() in the Test class, the system behaves strange. Breakpoints in the other methods are not hit. An exception is thrown from somewhere completely different, log output suggests that the program continued a bit. When the exception (type is from the framework) is thrown, there is no callstack.
Should this work in principle, how could i provide such functionality or debug what i have?

Allways call base.Method in Override without mentioning it for simple Scripts

I am trying to implement C# as a scripting language for my game engine. Everything works fine, only one major problem occurred in my design.
I have the class BaseEntity. And another class BossEntity that derives from BaseEntity. Then I want to be able to create a new entity via script. So I create a class in my script let's say Boss1, that derives from BossEntity.
BaseEntity has an virtual Update Method. BossEntity overrides it and calls also base.Update(). All fine in the design.
But now to my problem. In my script I also want to be able to override the Update Method. So I go ahead and override it again. All works as supposed, the BossEntity override gets lost, as I now override the BaseEntity Update again.
But for simplicity I do not want to have to call in my script base.Update() to have the same behavior as in BossEntity. That's a thing that can be forgotten, which would be for me as for a scripting language bad design.
When scripting you just add functionality not remove some in my opinion.
So my general question is, is there any way to accomplish a call to base.Update() without even calling it extra in my script?
I assume no, or maybe just with a trick, but you never know.
As far as I know, there is no way to automatically invoke the base class's virtual method when an overridden one is invoked. You must explicitly call it.
One of the things you can do is break the parent method up a bit more. Instead of having all of the code in a single overridable method like this:
public class Foo
{
public virtual void Update()
{
// Do stuff
}
}
public class Bar : Foo
{
public override void Update()
{
// Replaces the parents implementation of the
// Update method due to not calling base.Load();
}
}
Instead, you can use the Template Method Pattern to break it up in to multiple parts, so that the user can override the part that is meant explicitly for them.
public class Foo
{
public void Update()
{
this.OnUpdating();
this.PerformUpdate();
this.OnUpdated();
}
public virtual void PerformUpdate()
{
// Leave this empty. Let the subclass override it and
// do their own thing. Your parent code will still
// get called when Update() is called.
}
public void OnUpdating()
{
// Invoke code that you want to guarantee is always
// executed PRIOR the overridden PerformUpdate() method
// is finished.
}
public void OnUpdated()
{
// Invoke code that you want to guarantee is always
// executed AFTER the overridden PerformUpdate() method
// is finished.
}
}
public class Bar : Foo
{
public override void PerformUpdate()
{
// Do custom stuff, don't have to call base.PerformUpdate()
// because it already does it's code in OnUpdating()
// and OnUpdated().
}
}
Hope this makes sense. This is what I do in my game engine. I then document that a call to base.PerformUpdate() is not needed. Another option is to make the PerformUpdate() method abstract, forcing children to implement it. That makes it a bit more clearer that there is no need to invoke base.PerformUpdate().
public class Foo
{
public void Update()
{
this.OnUpdating();
this.PerformUpdate();
this.OnUpdated();
}
// Child class is required to implement this method.
// Only downside is you will no longer be able to instance
// the base class. If that is acceptable, then this is really
// the preferred way IMO for what you are wanting to do.
public abstract void PerformUpdate();
public void OnUpdating()
{
// Invoke code that you want to guarantee is always
// executed PRIOR the overridden PerformUpdate() method is finished.
}
public void OnUpdated()
{
// Invoke code that you want to guarantee is always
// executed AFTER the overridden PerformUpdate() method is finished.
}
}
In the end, this approach lets your base class handle its update code safely, by forcing children to implement their own update method that you do not depend on. Your base class can run through its update stuff before and after the child-class has run through its updates.
This basically lets you do this in your game code:
Bar myFoo = new Bar();
myFoo.Update();
And you can rest assured that your base class update methods get called, and the child update code will get called as well.

c# unit testing with fakes: when and how to setup/dispose ShimsContext's idisposable... and if I don't...?

In visual studio 2012+, I am using Shims to allow the testing of legacy code without accessing the database. I am using the MSTest framework.
I am trying to avoid code duplication of setting up the shims multiple times; I have instead set up a helper method (e.g. below, BuildShim()) to do so. The idea is that by having the ShimObject built in the helper method, I can have it available for each of the Test methods in my test class.
In the constructor for the test class, I initialize a _idisposable = ShimsContext.Create() (which actually returns an IDisposable). In the methods, I have try {} and finally { _idisoposable.Close() };
Microsoft explicitly advises (see http://msdn.microsoft.com/en-us/library/hh549176.aspx ) using a ShimContext like this, however:
using (ShimsContext.Create()){
...
}
Questions:
Is it bad that I'm not doing it the Microsoft way? If I do it the Microsoft way, how can I avoid duplicating Shim setup code? Or it okay to put the ShimsContext initialization in the constructor and disposal in the finally {} blocks as long as I know what I'm getting into? (e.g. it might be bad if I were using ShimObject.AllInstances type methods, since I could accidentally affect a property in one place and inadvertently affect it elsewhere.)
Is there anything wrong creating the ShimsContext in the test constructor and disposing the _shimcontextDisposal in the finally block like this instead?
What happens if I don't dispose of ShimsContext? Will my computer blow up, figuratively? (e.g. will the shims never be unloaded and I would start to get weird behavior if I actually run the app?)
Example code below.
[TestClass()]
public class Tests {
//Variable to store ShimsContext idisposable. Note that we're not holding the ShimsContext,
//but rather the IDisposable object returned by the ShimsContext.Create() method
private IDisposable _shimscontextDisposable;
//Test class constructor
public Tests(){
_shimscontextDisposable = ShimsContext.Create();
}
//Test method
[TestMethod()]
public TestMethod1(){
try {
//Call the helper method below to get the shim
ShimObject shim = this.GetShimObject();
DataObject data = shim.Instance;
//... do something in test method 1
}
finally {
_shimscontextDisposable.Dispose();
}
}
//Test method 2
[TestMethod()]
public TestMethod2(){
try {
//Call the helper method below to get the shim
ShimObject shim = this.GetShimObject();
DataObject data = shim.Instance;
//... do something in test method 2
}
finally {
_shimscontextDisposable.Dispose();
}
}
//Reusable method to Build shims across methods, avoid duplicating shim setup
public ShimObject BuildShim(){
ShimObject shim = new ShimObject();
shim.TitleGet = () => { return "title"; };
shim.UrlGet = () => { return new Uri("http://www.google.com"); };
return shim;
}
For MSTest Unit Tests it is best practice not to use a constructor. Instead use the ClassInitialize or TestInitialize attribute methods, followed by the TestCleanup or ClassCleanup attribute methods.
For your case, you would set your IDisposable object in the Initialize and dispose of it in the Cleanup.
http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.classinitializeattribute.aspx
namespace TestNamespace
{
[TestClass]
public class DivideClassTest
{
[ClassInitialize]
public static void ClassInit(TestContext context)
{
}
[TestInitialize]
public void Initialize()
{
}
[TestCleanup]
public void Cleanup()
{
}
[ClassCleanup]
public static void ClassCleanup()
{
}
}
}

TDD can force the creation of "fake" dependencies

I'm using a boilerplate implementation of Model-View-Presenter in an ASP.NET WebForms application. My View has two events of consequence, one that signals that the user has filled out enough fields on the domain model to initiate a duplication check, and the other is a regular Save event. My pseudo code looks like this:
public class ItemNewPresenter : PresenterBase<IItemNewView>
{
public IItemService Service { get; private set; }
public IItemNewView View { get; private set; }
public ItemNewPresenter(IItemService service, IItemNewView view)
{
Service = service;
View = view;
View.OnSave += DoItemSave;
View.OnItemIsDuplicateCheck+= DoItemIsDuplicateCheck;
}
private void DoItemIsDuplicateCheck(object sender, CheckItemDuplicateEventArgs e)
{
CheckForItemDuplication(e.Item);
}
private void CheckForItemDuplication(Item item){
if (Service.IsDuplicateItem(item))
{
View.RedirectWithNotification(BuildItemUrl(item), "This item already exists");
}
}
private void DoItemSave(object sender, SaveItemEventArgs e)
{
DoItemIsDuplicateCheck(this, e.ToItemDuplicateEventArgs());
Service.Save(e.Item);
}
}
Here's my test for ensuring that my presenter behaves properly when OnItemIsDuplicateCheck is raised from the view:
[Test]
public void presenter_checking_for_existing_item_should_call_redirect_if_found()
{
var service = new Mock<IItemService>();
var view = new Mock<IItemNewView>();
var presenter = new ItemNewPresenter (service.Object, view.Object);
var onCheckExistingHandler = view.CreateEventHandler <CheckItemDuplicateEventArgs>();
view.Object.OnExistingDenominatorCheck += onCheckExistingHandler;
var eventArgs = new CheckItemDuplicateEventArgs();
service.Setup(s => s.IsDuplicate(It.Is<CheckItemDuplicateEventArgs>(c => c.Equals(eventArgs)))).Returns(true);
onCheckExistingHandler.Raise(eventArgs);
view.Verify(v => v.RedirectWithNotification(It.IsAny<String>(), It.IsAny<string>()), Times.Once());
service.Verify();
}
For consistency, I would like to have the same duplicate check fired when the View raises the OnSave event. My question is around how I am supposed to write my test when one of the methods I want to verify (CheckForItemDuplication) is declared on the class under test. The alternative to verifying the method invocation on the SUT (bad) would be to write my save test with lots of duplicated code (setup and assertion of all my mocks would be copied from the above test) and it also makes the unit test less focused.
[Test]
public void presenter_saving_item_should_check_for_dupe_and_save_if_not_one() {
//duplicate mocks/setups/asserts from duplicate check fixture
//additional mocks/setups/asserts to test save logic
}
I think TDD would suggest pulling this private method out into a separate class that collaborates with my Presenter and would be injected via DI. But adding another dependency to my Presenter for functionality that doesn't seem worthy of being a freestanding abstraction *and*represents an internal implementation detail of my Presenter seems...well...crazy. Am I way off base here? There must be some design pattern or refactoring I can apply that would avoid the need to turn a private method into a dependency.
What I have done sometimes, when confronted with this dilemma, is to extract the function, make an internal constructor with the object as argument, AND a public constructor without. The public ctor is forwarded to the internal with a new object such as:
public class ClassThatUseInjection
{
private readonly SomeClass _injectedClass;
public ClassThatUseInjection(): this(new SomeClass()) {}
internal ClassThatUseInjection(SomeClass injectedClass)
{
_injectedClass = injectedClass;
}
}
public class SomeClass
{
public object SomeProperty { get; set; }
}
Thus, you can use the empty constructor from outside, and the other constructor for when you want to inject a stubbed argument for testpurposes. As long as the empty constructor only forwards the call without any logic of its own, you can still test it, like it has only one constructor.
I would go with testing the class as is by adding the duplicate setup code. Once that test is passing and you are confident all test cases are covered you can then refactor your test code to remove duplication.
You can move the dependencies (service and view) to private fields, then add a method to create the SUT:
private Mock<IItemService> _service;
private Mock<IItemNewView> _view;
private PresenterBase<IItemNewView> CreateSUT()
{
_service = new Mock<IItemService>();
_view = new Mock<IItemNewView>();
return new ItemNewPresenter (service.Object, view.Object);
}
(I think most people would prefer to initialize the Mock objects in the Setup method.)
Call the CreateSUT from your tests and now there is a little less duplication. Then you may want to add private method(s) for creating the event handler / raising the event as long as it is something that is being done the same or similar in more than one tests case.
Having this CreateSUT method cuts down on the amount of test code that is calling your constructor making it easier in the future if you were to add / remove / change dependencies. If you treat your test code like any other code and use the DRY principle when you see duplication it can result in more explicit, easier to read, maintainable test code. Dealing with very similar setup and test context is a common issue with unit testing and should not always change how the class being tested is/was designed.
I'll be interested if there are better answers, as I encounter this all the time.
The alternative to verifying the method invocation on the SUT (bad) would be to write my save test with lots of duplicated code (setup and assertion of all my mocks would be copied from the above test) and it also makes the unit test less focused.
I'm not sure why you feel it makes the test less focused, but in your shoes I would do exactly what it sounds like you don't want to do--have duplicated setup code to test isolated cases for the SUT. You are testing the external behavior of the SUT with the test you supplied, which seems exactly right to me.
I am personally not a fan of exposing more than is necessary from a class and/or making behavior that should be the responsibility of the SUT into a dependency just to facilitate testing. The "natural boundry" of the class's responsibility should not be violated just because you want to test it.
It is easier to unit-test the calculation of the url than to unit-test that redirection has occured.
If i understood you corretly you want to test that the mvp-s CheckForItemDuplication() redirects to a certain url by raising
the view-mock-s OnItemIsDuplicateCheck event.
private void CheckForItemDuplication(Item item)
{
if (Service.IsDuplicateItem(item))
{
View.RedirectWithNotification(BuildItemUrl(item),
"This item already exists");
}
}
In my opinion you are doing to much.
What if you rewrite your code as
internal protected GetErrorUrlForItem(Item item)
{
if (Service.IsDuplicateItem(item))
{
return BuildItemUrl(item,
"This item already exists");
}
return null;
}
private void CheckForItemDuplication(Item item)
{
var result = GetErrorUrlForItem(item);
if (result != null)
{
View.RedirectWithNotification(result);
}
}
In the unittest just test the internal method GetErrorUrlForItem(). You have to use the InternalsVisibleTo attribute to allow accessing the internal method.

Categories