How can I fake call to current class' method with NSubstitute? - c#

I'm new to NSubstitue (and quite new to unit testing in .NET at all). I want to test if my class saves all data in different files for each entry in e.g. StringDictionary.
Say I have my class DataManipulation.cs:
using System;
using System.Collections;
using System.Collections.Specialized;
namespace ApplicationName
{
// interface for NSubstitute
public interface IManipulator
{
void saveAllData();
void saveEntry(string entryKey, string entryValue);
}
public class DataManipulator : IManipulator
{
protected StringDictionary _data {get; private set;}
public DataManipulator()
{
_data = new StringDictionary();
}
public void addData(string name, string data)
{
this._data.Add(name, data);
}
public void saveAllData()
{
// potential implementation - I want to test this
foreach (DictionaryEntry entry in this._data)
{
this.saveEntry(entry.Key.ToString(), entry.Value.ToString());
}
}
public void saveEntry(string entryKey, string entryValue)
{
// interact with filesystem, save each entry in its own file
}
}
}
What I want to test: when I call DataManipulator.saveAllData() it saves each _data entry in a separate file - meaning it runs saveEntry number of times that equals to _data.Count. Is it possible with NSubstitute?
Each time I try to use DataManipulation as tested object and separately as a mock - when I run Received() I have info that no calls were made.
NUnit test template I want to use:
using System;
using System.Collections.Generic;
using NUnit.Framework;
using NSubstitute;
namespace ApplicationName.UnitTests
{
[TestFixture]
class DataManipulatorTests
{
[Test]
public void saveAllData_CallsSaveEntry_ForEachData()
{
DataManipulator dm = new DataManipulator();
dm.addData("abc", "abc");
dm.addData("def", "def");
dm.addData("ghi", "ghi");
dm.saveAllData();
// how to assert if it called DataManipulator.saveEntry() three times?
}
}
}
Or should I do it in different way?

According to some OOP principles and testing needs you have to introduce a dependency or some construction to create "seam" which will fit good for testing.
Using of another dependency as a mock
It will encapsulate data storage and you will check your assertions against it. I recommend you to read about what's the difference between fake, stub and mock.
Add new storage interface and implementation.
public interface IDataStorage
{
void Store(string key, string value);
}
public class DataStorage : IDataStorage
{
public void Store(string key, string value)
{
//some usefull logic
}
}
Use it as dependency (and inject via constructor) in your Manipulator implementation
public class DataManipulator : IManipulator
{
protected IDataStorage _storage { get; private set; }
protected StringDictionary _data { get; private set; }
public DataManipulator(IDataStorage storage)
{
_storage = storage;
_data = new StringDictionary();
}
public void addData(string name, string data)
{
this._data.Add(name, data);
}
public void saveAllData()
{
// potential implementation - I want to test this
foreach (DictionaryEntry entry in this._data)
{
this.saveEntry(entry.Key.ToString(), entry.Value.ToString());
}
}
public void saveEntry(string entryKey, string entryValue)
{
_storage.Store(entryKey, entryValue);
}
}
Test it
[Test]
public void saveAllData_CallsSaveEntry_ForEachData()
{
var dataStorageMock = Substitute.For<IDataStorage>();
DataManipulator dm = new DataManipulator(dataStorageMock);
dm.addData("abc", "abc");
dm.addData("def", "def");
dm.addData("ghi", "ghi");
dm.saveAllData();
dataStorageMock.Received().Store("abc", "abc");
dataStorageMock.Received().Store("def", "def");
dataStorageMock.Received().Store("ghi", "ghi");
//or
dataStorageMock.Received(3).Store(Arg.Any<string>(), Arg.Any<string>());
}
Most important here that you have not to test private method call. It's a bad practice! Unit testing is all about of testing of public contract, not private methods, which are more changeable in time. (Sorry, I miss that saveEntry(..) is public)
Using of DataManipulator as a mock
I think it's not a good idea, but... The only way to do that with NSubstitute is to make method saveEntry virtual:
public virtual void saveEntry(string entryKey, string entryValue)
{
//something useful
}
and test it:
[Test]
public void saveAllData_CallsSaveEntry_ForEachData()
{
var dm = Substitute.For<DataManipulator>();
dm.addData("abc", "abc");
dm.addData("def", "def");
dm.addData("ghi", "ghi");
dm.saveAllData();
dm.Received(3).saveEntry(Arg.Any<string>(), Arg.Any<string>());
}
The need to do some method virtual just for testing needs may be not very attractive but..
As soon as your tests are also the clients of your business logic, one can take it.
It is possible to use some "heavy" testing frameworks like MS Fakes in this certain case, but it seems to be an overkill.
Another solution is to test another unit of work, which covers depicted one (and probably looks like my first solution).
UPD: read it http://nsubstitute.github.io/help/partial-subs/ for better understanding of NSubstitute.

Related

I am trying to write Unit Test in C# for static methods

I am learning unit test for c# web application. I am stuck in above mention scenario. I am not sure if I am doing it in correct way. I have FakePath class for unit test. How do I write unit test for static method,Abc.log(), in MSTest?
public class Abc
{
public static void log(string msg)
{
//Read on Write on path;
string path = getPath(new ServerPath());
}
public static string getPath(IServerPath path)
{
return path.MapPath("file.txt");
}
}
interface IServerPath()
{
string MapPath(string file);
}
class ServerPath : IServerPath
{
string MapPath(string file)
{
return HttpContext.Current.Server.MapPath(file);
}
}
class FakeServerPath : IServerPath
{
string MapPath(string file)
{
return #"C:\"+file;
}
}
You are trying to test a void method, so one of your options of asserting this method is to verify if the method is called:
string expectedStr = "c:\file.txt";
[TestMethod]
public void FakeServerPath_VerifyMapPathWasCalled()
{
var fakeServerPath = Isolate.Fake.NextInstance<ServerPath>();
Isolate.WhenCalled(() => fakeServerPath.MapPath("")).WillReturn(expectedStr);
Abc.log("");
Isolate.Verify.WasCalledWithExactArguments(() => fakeServerPath.MapPath("file.txt"));
}
Another option is to test the return value of the getPath(IServerPath path) method, by modifying the return value of ServerPath's MapPath(string file) method to return a wanted value, and to assert if the return value is as expected.
string expectedStr = "c:\file.txt";
[TestMethod]
public void ModifyReturnValueFromMapPath_IsEqualToExpactedStr()
{
var fakeServerPath = Isolate.Fake.NextInstance<ServerPath>();
Isolate.WhenCalled(() => fakeServerPath.MapPath("")).WillReturn(expectedStr);
var result = Abc.getPath(fakeServerPath);
Assert.AreEqual(expectedStr, result);
}
Notice that by using TypeMock Isolator you will be able to fake the future instance of "ServerPath" without changing your original code.
And if necessary TypeMock is also able to mock HttpContext class as so:
string expectedStr = "c:\file.txt";
[TestMethod]
public void ModifyReturnValueFromHttpContext_IsEqualToExpactedStr()
{
var serverPath = new ServerPath();
Isolate.WhenCalled(() => HttpContext.Current.Server.MapPath("")).WillReturn(expectedStr);
var result = Abc.getPath(serverPath);
Assert.AreEqual(expectedStr, result);
}
Testing statics in itself is easy, just call them and assert on the results (the actual problem is testing code that uses statics, as they can't be mocked out). Testing in this particular case is complicated by a different thing.
The real problem of the Log method is that ti creates a ServerPath instance by itself, which precludes any chance of Dependency Injection (on the contrary, the GetPath method is totally friendly to testing, as it takes an interface as a parameter).
I would introduce a refactoring on the Abc class to enable better testing on it. I would modify it as such:
public static class Logger
{
public static void Log(IServerPath path, string msg)
{
//add parameter checking here
string path = path.MapPath("file.txt");
//actual log goes here
}
}
Note that now the test would be responsible to create the IServerPath instance, which can then use to inject the mock
In a case like this you need to expose a way to set the dependency. Currently you are using a new ServerPath() directly in the method which makes it difficult to inject your FakeServerPath for testing.
You can modify Abc
public class Abc
{
static Abc() { ServerPath = new ServerPath(); }
public static IServerPath ServerPath { get; set; }
public static void log(string msg) {
//Read on Write on path;
string path = getPath(ServerPath);
}
public static string getPath(IServerPath path) {
return path.MapPath("file.txt");
}
}
And a test could look like this
[TestMethod]
public void Abc_log_Test() {
//Arrange
string filename = "fakeFile.txt";
string expected = #"C:\" + filename;
var mockServerPath = new Mock<IServerPath>();
mockServerPath
.Setup(m => m.MapPath(filename))
.Returns(expected)
.Verifiable();
Abc.ServerPath = mockServerPath.Object;
var message = "Hello world";
//Act
Abc.log(message);
//Assert
mockServerPath.Verify();
}
Note I used Moq to mock up the server path
Here's a simple approach using dependency injection.
public class FileLogger
{
private readonly string _filePath;
public FileLogger(string filePath)
{
_filePath = filePath;
}
public void Log(string msg)
{
//write to the log
}
}
Now your logging class has a single responsibility - writing to the file. It is not responsible for figuring out which file to write to. It expects to have that value injected into it.
Also, I avoided using a static method. If the method is static then a similar problem occurs again: How do you test classes that depend on the logging class?
By making it non-static you can repeat the same pattern - mock the logger so that you can test classes that depend on it.
public interface ILogger
{
void Log(string msg);
}
Then your logging class can implement the interface and you can inject that interface (instead of a concrete class) into classes that might need to write to a log.
Here's a post which demonstrates injecting a logger into a class. There are often better ways to accomplish the same purpose (like using an interceptor) but at least it prevents your code from having dependencies everywhere on some concrete class.

How to use NSubstitute and/or AutoFixture to test a concrete class

I was hoping that by using AutoFixture and NSubstitue, I could use the best of what each have to provide. I have had some success using NSubstitute on its own, but I am completely confused on how to use it in combination with AutoFixture.
My code below shows a set of things I am trying to accomplish, but my main goal here is to accomplish the following scenario: Test the functionality of a method.
I expect the constructor to be called with random values (except maybe one - please read point 2.).
Either during construction or later, I want to change value of a property -Data.
Next call Execute and confirm the results
The test that I am trying to get working is: "should_run_GetCommand_with_provided_property_value"
Any help or reference to an article that shows how NSubstitue and AutFixture SHOULD be used, would be great.
Sample Code:
using FluentAssertions;
using NSubstitute;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoNSubstitute;
using Xunit;
namespace RemotePlus.Test
{
public class SimpleTest
{
[Fact]
public void should_set_property_to_sepecified_value()
{
var sut = Substitute.For<ISimple>();
sut.Data.Returns("1,2");
sut.Data.Should().Be("1,2");
}
[Fact]
public void should_run_GetCommand_with_provided_property_value()
{
/* TODO:
* How do I create a constructor with AutoFixture and/or NSubstitute such that:
* 1. With completely random values.
* 2. With one or more values specified.
* 3. Constructor that has FileInfo as one of the objects.
*
* After creating the constructor:
* 1. Specify the value for what a property value should be - ex: sut.Data.Returns("1,2");
* 2. Call "Execute" and verify the result for "Command"
*
*/
// Arrange
var fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
// var sut = fixture.Build<Simple>().Create(); // Not sure if I need Build or Freeze
var sut = fixture.Freeze<ISimple>(); // Note: I am using a Interface here, but would like to test the Concrete class
sut.Data.Returns("1,2");
// Act
sut.Execute();
// Assert (combining multiple asserts just till I understand how to use NSubstitue and AutoFixture properly
// sut.Received().Execute();
sut.Data.Should().Be("1,2");
sut.Command.Should().Be("1,2,abc");
// Fails with : FluentAssertions.Execution.AssertionFailedExceptionExpected string to be "1,2,abc" with a length of 7, but "" has a length of 0.
}
}
public class Simple : ISimple
{
// TODO: Would like to make this private and use the static call to get an instance
public Simple(string inputFile, string data)
{
InputFile = inputFile;
Data = data;
// TODO: Would like to call execute here, but not sure how it will work with testing.
}
// TODO: Would like to make this private
public void Execute()
{
GetCommand();
// Other private methods
}
private void GetCommand()
{
Command = Data + ",abc";
}
public string InputFile { get; private set; }
public string Data { get; private set; }
public string Command { get; private set; }
// Using this, so that if I need I can easliy switch to a different concrete class
public ISimple GetNewInstance(string inputFile, string data)
{
return new Simple(inputFile, data);
}
}
public interface ISimple
{
string InputFile { get; } // TODO: Would like to use FileInfo instead, but haven't figured out how to test. Get an error of FileNot found through AutoFixture
string Data { get; }
string Command { get; }
void Execute();
}
}
I haven't really used AutoFixture much, but based on some reading and a bit of trial and error, I think you're misinterpreting what it will and won't do for you. At a basic level, it'll let you create a graph of objects, filling in values for you based around the objects constructors (and possibly properties but I haven't looked into that).
Using the NSubstitute integration doesn't make all of the members of your class into NSubstitute instances. Instead, it gives the fixture framework the ability to create abstract / interface types as Substitutes.
Looking at the class you're trying to create, the constructor takes two string parameters. Neither of these is an abstract type, or an interface so AutoFixture is just going to generate some values for you and pass them in. This is AutoFixture's default behaviour and based on the answer linked to by #Mark Seemann in the comments this is by design. There are various work arounds proposed by him there that you can implement if it's really important for you to do so, which I won't repeat here.
You've indicated in your comments that you really want to pass a FileInfo into your constructor. This is causing AutoFixture a problem, since its constructor takes a string and consequently AutoFixture is supplying a random generated string to it, which is a non-existent file so you get an error. This seems like a good thing to try to isolate for testing so is something that NSubstitute might be useful for. With that in mind, I'm going to suggest that you might want to rewrite your classes and test something like this:
First up create a wrapper for the FileInfo class (note, depending on what you're doing you might want to actually wrap the methods from FileInfo that you want, rather than exposing it as a property so that you can actually isolate yourself from the filesystem but this will do for the moment):
public interface IFileWrapper {
FileInfo File { get; set; }
}
Use this in your ISimple interface instead of a string (notice I've removed Execute since you don't seem to want it there):
public interface ISimple {
IFileWrapper InputFile { get; }
string Data { get; }
string Command { get; }
}
Write Simple to implement the interface (I haven't tackled your private constructor issue, or your call to Execute in the constructor):
public class Simple : ISimple {
public Simple(IFileWrapper inputFile, string data) {
InputFile = inputFile;
Data = data;
}
public void Execute() {
GetCommand();
// Other private methods
}
private void GetCommand() {
Command = Data + ",abc";
}
public IFileWrapper InputFile { get; private set; }
public string Data { get; private set; }
public string Command { get; private set; }
}
And then the test:
public void should_run_GetCommand_with_provided_property_value() {
// Arrange
var fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
// create and inject an instances of the IFileWrapper class so that we
// can setup expectations
var fileWrapperMock = fixture.Freeze<IFileWrapper>();
// Setup expectations on the Substitute. Note, this isn't needed for
// this test, since the sut doesn't actually use inputFile, but I've
// included it to show how it works...
fileWrapperMock.File.Returns(new FileInfo(#"c:\pagefile.sys"));
// Create the sut. fileWrapperMock will be injected as the inputFile
// since it is an interface, a random string will go into data
var sut = fixture.Create<Simple>();
// Act
sut.Execute();
// Assert - Check that sut.Command has been updated as expected
Assert.AreEqual(sut.Data + ",abc", sut.Command);
// You could also test the substitute is don't what you're expecting
Assert.AreEqual("pagefile.sys", sut.InputFile.File.Name);
}
I'm not using fluent asserts above, but you should be able to translate...
I actually managed to find a solution by realizing that I don't need to use AutoFixture for my current scenario.
I had to make some changes to my code though:
Added a default constructor.
Marked the methods and properties I want to provide a default value for as "virtual".
Ideally, I do not want to do these things, but it is enough to get me started and keep me moving forward for now.
Links that helped a lot:
Partial subs and test spies
Partial subs with nsubstitute
Modified code:
using FluentAssertions;
using NSubstitute;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoNSubstitute;
using Xunit;
using Xunit.Abstractions;
namespace Try.xUnit.Tests
{
public class TestingMethodCalls
{
private readonly ITestOutputHelper _output;
public TestingMethodCalls(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void should_set_property_to_sepecified_value()
{
var sut = Substitute.For<ISimple>();
sut.Data.Returns("1,2");
sut.Data.Should().Be("1,2");
}
[Fact (Skip="Don't quite understand how to use AutoFixture and NSubstitue together")]
public void should_run_GetCommand_with_provided_property_value_old()
{
/* TODO:
* How do I create a constructor with AutoFixture and/or NSubstitute such that:
* 1. With completely random values.
* 2. With one or more values specified.
* 3. Constructor that has FileInfo as one of the objects.
*
* After creating the constructor:
* 1. Specify the value for what a property value should be - ex: sut.Data.Returns("1,2");
* 2. Call "Execute" and verify the result for "Command"
*
*/
// Arrange
var fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
// var sut = fixture.Build<Simple>().Create(); // Not sure if I need Build or Freeze
var sut = fixture.Freeze<ISimple>(); // Note: I am using a Interface here, but would like to test the Concrete class
sut.Data.Returns("1,2");
// Act
sut.Execute();
// Assert (combining multiple asserts just till I understand how to use NSubstitue and AutoFixture properly
// sut.Received().Execute();
sut.Data.Should().Be("1,2");
sut.Command.Should().Be("1,2,abc");
// Fails with : FluentAssertions.Execution.AssertionFailedExceptionExpected string to be "1,2,abc" with a length of 7, but "" has a length of 0.
}
/* Explanation:
* Create a construtor without any arguments.
* Had to create a parameterless constructor just for testing purposes (would like to improve on this)
* Specify a default value for the desired method or property.
* It is necessary that the property or method has to be virtual.
* To specify that the based mehod should be call use the "DoNotCallBase" before the "Returns" call
*/
[Fact]
public void should_run_GetCommand_with_provided_Method_value()
{
// Arrange
var sut = Substitute.ForPartsOf<Simple>();
sut.When(x => x.GetData()).DoNotCallBase();
sut.GetData().Returns("1,2");
// Act
sut.Execute();
// Assert
sut.Received().GetData();
sut.Data.Should().Be("1,2");
sut.Command.Should().Be("1,2,abc");
}
[Fact]
public void should_run_GetCommand_with_provided_Property_value()
{
// Arrange
var sut = Substitute.ForPartsOf<Simple>();
sut.When(x => { var data = x.Data; }).DoNotCallBase();
sut.Data.Returns("1,2");
// Act
sut.Execute();
// Assert
sut.Received().GetData();
_output.WriteLine(sut.Command);
sut.Data.Should().Be("1,2");
sut.Command.Should().Be("1,2,abc");
}
}
public class Simple : ISimple
{
public Simple(){}
// TODO: Would like to make this private and use the static call to get an instance
public Simple(string inputFile, string data)
{
InputFile = inputFile;
InputData = data;
// TODO: Would like to call execute here, but not sure how it will work with testing.
}
public virtual string GetData()
{
// Assume some manipulations are done
return InputData;
}
// TODO: Would like to make this private
public void Execute()
{
Data = GetData();
GetCommand();
// Other private methods
}
private void GetCommand()
{
Command = Data + ",abc";
}
string InputData { get; set; }
public string InputFile { get; private set; }
public virtual string Data { get; private set; }
public string Command { get; private set; }
// Using this, so that if I need I can easliy switch to a different concrete class
public ISimple GetNewInstance(string inputFile, string data)
{
return new Simple(inputFile, data);
}
}
public interface ISimple
{
string InputFile { get; } // TODO: Would like to use FileInfo instead, but haven't figured out how to test. Get an error of FileNot found through AutoFixture
string Data { get; }
string Command { get; }
void Execute();
}
}
I'm posting this as a separate answer because it's more a critique of approach, than direct answer to your original question. In my other answer I've tried to directly answer your AutoFixture/NSubstitute questions assuming that you are currently trying to learn these to frameworks.
As it stands, you don't really need to use either of these frameworks to achieve what you are doing and in some ways it's easier not to. Looking at this test:
public void should_set_property_to_sepecified_value()
{
var sut = Substitute.For<ISimple>();
sut.Data.Returns("1,2");
sut.Data.Should().Be("1,2");
}
This isn't actually testing your class at all (other than compilation checks), really you're testing NSubstitute. You're checking that if you tell NSubstitute to return a value for a property that it does.
Generally speaking, try to avoid mocking the class that you're testing. If you need to do it, then there is a good chance that you need to rethink your design. Mocking is really useful for supplying dependencies into your class that you can control in order to influence the behaviour of your class. If you start modifying the behaviour of the class you're testing using mocks then it's very easy to get confused about what you're actually testing (and to create very brittle tests).
Because you're dealing with basic types and not nested objects, at the moment it's easy to create + test your objects without using something like AutoFixture/NSubstitute. You code could look like this, which seems to be closer to what you're hoping for:
public interface ISimple {
string InputFile { get; }
string Data { get; }
string Command { get; }
}
public class Simple : ISimple {
private Simple(string inputFile, string data) {
InputFile = inputFile;
Data = data;
}
private void Execute() {
GetCommand();
}
private void GetCommand() {
Command = Data + ",abc";
}
public string InputFile { get; private set; }
public string Data { get; private set; }
public string Command { get; private set; }
// Note.. GetNewInstance is static and it calls the Execute method
static public ISimple GetNewInstance(string inputFile, string data) {
var simple = new Simple(inputFile, data);
simple.Execute();
return simple;
}
}
And your test would look like this:
[Test]
public void should_run_GetCommand_with_provided_property_value() {
// Arrange
var inputFile = "someInputFile";
var data = "1,2";
var expectedCommand = "1,2,abc";
// Act
// Note, I'm calling the static method to create your instance
var sut = Simple.GetNewInstance(inputFile, data);
// Assert
Assert.AreEqual(inputFile, sut.InputFile);
Assert.AreEqual(data, sut.Data);
Assert.AreEqual(expectedCommand, sut.Command);
}
I've left the Execute outside of the objects constructor because it feels a bit like it's going to be doing too much. I'm not a huge fan of doing a lot other than basic setup in constructors particularly if there's a chance you might end up calling virtual methods. I've also made GetNewInstance static so that it can be called directly (otherwise you have to create a Simple to call GetNewInstance on it which seems wrong)...
Whilst I've shown above how your code could work as you want it so, I'd suggest that you might want to change the Simple constructor to internal, rather than private. This would allow you to create a factory to create the instances. If you had something like this:
public interface IMyObjectFactory {
ISimple CreateSimple(string inputFile, string data);
}
public class MyObjectFactory {
ISimple CreateSimple(string inputFile, string data) {
var simple = new Simple(inputFile, data);
simple.Execute();
return simple;
}
}
This allows you to safely constructor objects that need methods called on them. You can also inject substitutes of the IMyObjectFactory that returns a substitute of ISimple in future classes that are dependent on the Simple class. This helps you to isolate your classes from the underlying class behaviour (which might access the file system) and makes it easy for you to stub responses.

How to test virtual methods using Moles?

How can I test the IsHappy function using Moles?
class SomeClass
{
protected virtual bool IsHappy(string mood)
{
return (mood == "Happy");
}
}
I tried to test if by using Stub:
SSomeClass stub = new SSomeClass();
stub.CallBase = true;
Assert.IsTrue(stub.IsHappyString("Happy"));
... but the IsHappyString method returns null thus throwing a NullReference exception.
So, how can I test the default implementation of IsHappy method?
I'd forget about stubs here. Stubs/mocks are for when you want to fake the behavior of a dependency. You'd stub your SomeClass if had SomeClassClient that you wanted to test and it used SomeClass:
public class Foo
{
public virtual int GetFoosInt()
{
return 12;
}
}
public class FooClient
{
private Foo _foo;
public FooClient(Foo foo)
{
_foo = foo;
}
public int AddOneToFoosInt()
{
return _foo.GetFoosInt() + 1;
}
}
In this example, when testing FooClient, what you want to test is that it returns one more than "GetFoosInt()". You don't actually care what FoosInt is for testing the FooClient. So, you create a Foo stub where you can setup GetFoosInt to return whatever you want.
In your case, testing a protected virtual member, I'd go with this:
[TestClass]
public class SomeClassTest
{
private class DummySomeClass : SomeClass
{
public bool IsHappyWrapper(string mood)
{
return IsHappy(mood);
}
}
[TestMethod]
public void SomeTest()
{
var myClass = new DummySomeClass();
Assert.IsTrue(myClass.IsHappyWrapper("Happy"));
}
}
This gives you 'direct' access to the protected virtual to test default behavior. Only word of caution is that if you start defining abstract members and adding to SomeClass in general, you'll have to add them to this dummy inheritor as well, adding to testing maintenance overhead.
The purist in me says that you should leave protected members alone and only test them through the public interface. But, that may or may not be practical in your situation, and I don't really see any harm in this approach.
Stubs and Moles are for isolating a class from any dependencies it has, either environmental dependencies or class dependencies. This class has no dependencies whatsoever, so why are you trying to mole or stub it?
If you want to make sure this base class works properly when people override it, then you'll need to create a test implementation. In that case this is more or less what your test cases should look like:
public SomeClassTestAdapter : SomeClass
{
public bool GetIsHappy(string mood)
{
return IsHappy(mood);
}
}
[Test]
public void ShouldReturnTrueWhenPassedHappy()
{
var classUnderTest = new SomeClassTestAdapter();
bool result = classUnderTest.IsHappy("Happy");
Assert.IsTrue(result, "Expected result to be true");
}
[Test]
public void ShouldReturnFalseWhenPassedLowerCaseHappy()
{
var classUnderTest = new SomeClassTestAdapter();
bool result = classUnderTest.IsHappy("happy");
Assert.IsFalse(result, "Expected result to be false");
}
[Test]
public void ShouldReturnFalseWhenPassedNull()
{
var classUnderTest = new SomeClassTestAdapter();
bool result = classUnderTest.IsHappy(null);
Assert.IsFalse(result, "Expected result to be false");
}
Etc.
There is no place in this code that stubs or moles should be squeezed in.
If you don't want to create an adapter class for this case, you can use built-in .Net features rather than a big, paid dependency like Moles. Reflections and dynamic let you get access to protected or private members. See this example:
http://igoro.com/archive/use-c-dynamic-typing-to-conveniently-access-internals-of-an-object/

How do I write context/specification style unit tests with an MSTest/xUnit framework?

I have been using MSpec to write my unit tests and really prefer the BDD style, I think it's a lot more readable. I'm now using Silverlight which MSpec doesn't support so I'm having to use MSTest but would still like to maintain a BDD style so am trying to work out a way to do this.
Just to explain what I'm trying to acheive, here's how I'd write an MSpec test
[Subject(typeof(Calculator))]
public class when_I_add_two_numbers : with_calculator
{
Establish context = () => this.Calculator = new Calculator();
Because I_add_2_and_4 = () => this.Calculator.Add(2).Add(4);
It should_display_6 = () => this.Calculator.Result.ShouldEqual(6);
}
public class with_calculator
{
protected static Calculator;
}
So with MSTest I would try to write the test like this (although you can see it won't work because I've put in 2 TestInitialize attributes, but you get what I'm trying to do..)
[TestClass]
public class when_I_add_two_numbers : with_calculator
{
[TestInitialize]
public void GivenIHaveACalculator()
{
this.Calculator = new Calculator();
}
[TestInitialize]
public void WhenIAdd2And4()
{
this.Calculator.Add(2).Add(4);
}
[TestMethod]
public void ThenItShouldDisplay6()
{
this.Calculator.Result.ShouldEqual(6);
}
}
public class with_calculator
{
protected Calculator Calculator {get;set;}
}
Can anyone come up with some more elegant suggestions to write tests in this way with MSTest?
What you think about this one:
[TestClass]
public class when_i_add_two_numbers : with_calculator
{
public override void When()
{
this.calc.Add(2, 4);
}
[TestMethod]
public void ThenItShouldDisplay6()
{
Assert.AreEqual(6, this.calc.Result);
}
[TestMethod]
public void ThenTheCalculatorShouldNotBeNull()
{
Assert.IsNotNull(this.calc);
}
}
public abstract class with_calculator : SpecificationContext
{
protected Calculator calc;
public override void Given()
{
this.calc = new Calculator();
}
}
public abstract class SpecificationContext
{
[TestInitialize]
public void Init()
{
this.Given();
this.When();
}
public virtual void Given(){}
public virtual void When(){}
}
public class Calculator
{
public int Result { get; private set; }
public void Add(int p, int p_2)
{
this.Result = p + p_2;
}
}
Mark Nijhof has an example of doing Given-When-Then style testing with NUnit in his Fohjin.DDD github repository.
Here's an excerpt from the example referenced above:
public class When_registering_an_domain_event : BaseTestFixture<PreProcessor>
{
/* ... */
protected override void When()
{
SubjectUnderTest.RegisterForPreProcessing<ClientMovedEvent>();
SubjectUnderTest.Process();
}
[Then]
public void Then_the_event_processors_for_client_moved_event_will_be_registered()
{
IEnumerable<EventProcessor> eventProcessors;
EventProcessorCache.TryGetEventProcessorsFor(typeof(ClientMovedEvent), out eventProcessors);
eventProcessors.Count().WillBe(1);
}
}
And you can see the Given in the base class implementation:
[Given]
public void Setup()
{
CaughtException = new NoExceptionWasThrownException();
Given();
try
{
When();
}
catch (Exception exception)
{
CaughtException = exception;
}
finally
{
Finally();
}
}
I've been giving this sort of question a lot of though recently. There are a lot of reasonable options out there, and you can create your own easily, as displayed in some of the answers in this post. I've been working on a BDD testing framework with the intent being to make it easily extended to any unit testing framework. I currently support MSTest and NUnit. Its called Given, and it's opensource. The basic idea is pretty simple, Given provides wrappers for common sets of functionality which can then be implemented for each test runner.
The following is an example of an NUnit Given test:
[Story(AsA = "car manufacturer",
IWant = "a factory that makes the right cars",
SoThat = "I can make money")]
public class when_building_a_toyota : Specification
{
static CarFactory _factory;
static Car _car;
given a_car_factory = () =>
{
_factory = new CarFactory();
};
when building_a_toyota = () => _car = _factory.Make(CarType.Toyota);
[then]
public void it_should_create_a_car()
{
_car.ShouldNotBeNull();
}
[then]
public void it_should_be_the_right_type_of_car()
{
_car.Type.ShouldEqual(CarType.Toyota);
}
}
I tried my best to stay true to the concepts from Dan North's Introducting BDD blog, and as such, everything is done using the given, when, then style of specification. The way it is implemented allows you to have multiple givens and even multiple when's, and they should be executed in order (still checking into this).
Additionally, there is a full suite of Should extensions included directly in Given. This enables things like the ShouldEqual() call seen above, but is full of nice methods for collection comparison and type comparison, etc. For those of you familiar with MSpec, i basically ripped them out and made some modifications to make them work outside of MSpec.
The payoff, though, I think, is in the reporting. The test runner is filled with the scenario you've created, so that at a glance you can get details about what each test is actually doing without diving into the code:
Additionally, an HTML report is created using t4 templating based on the results of the tests for each assembly. Classes with matching stories are all nested together, and each scenario name is printed for quick reference. For the above tests the report would look like this:
Failed tests would be colored red and can be clicked to view the exception details.
That's pretty much it. I'm using it in several projects I'm working on, so it is still being actively developed, but I'd describe the core as pretty stable. I'm looking at a way to share contexts by composition instead of inheritance, so that will likely be one of the next changes coming down the pike. Bring on the criticism. :)
You could use NUnit.Specifications and write tests like this:
using NUnit.Specifications;
using Should;
public class OrderSpecs
{
[Component]
public class when_a_customer_places_an_order : ContextSpecification
{
static OrderService _orderService;
static bool _results;
static Order _order;
Establish context = () =>
{
_orderService = new OrderService();
_order = new Order();
};
Because of = () => _results = _orderService.PlaceOrder(_order);
It should_successfully_place_the_order = () => _results.ShouldBeTrue();
}
}
MSTestEnhancer may help you, and you can get the package through NuGet.org.
Here is the sample code:
[TestClass]
public class TheTestedClassTest
{
[ContractTestCase]
public void TheTestedMethod()
{
"When Xxx happens, results in Yyy.".Test(() =>
{
// Write test case code here...
});
"When Zzz happens, results in Www.".Test(() =>
{
// Write test case code here...
});
}
}
And when you see your test result, you'll get this below:
I have written a post to present more information about it. See Introducing MSTestEnhancer to make unit test result easy to read - walterlv for more details.

Virtual Extension Methods?

I have a class that gets used in a client application and in a server application.
In the server application, I add some functionality to the class trough extension methods. Works great. Now I want a bit more:
My class (B) inherits from another class (A).
I'd like to attach a virtual function to A (let's say Execute() ), and then implement that function in B. But only in the server. The Execute() method would need to do stuff that is only possible to do on the server, using types that only the server knows about.
There are many types that inherit from A just like B does, and I'd like to implement Execute() for each of them.
I was hoping I could add a virtual extension method to A, but that idea doesn't seem to fly. I'm looking for the most elegant way to solve this problem, with or without extension methods.
No, there aren't such things as virtual extension methods. You could use overloading, but that doesn't support polymorphism. It sounds like you might want to look at something like dependency injection (etc) to have different code (dependencies) added in different environments - and use it in regular virtual methods:
class B {
public B(ISomeUtility util) {
// store util
}
public override void Execute() {
if(util != null) util.Foo();
}
}
Then use a DI framework to provide a server-specific ISomeUtility implementation to B at runtime. You can do the same thing with a central static registry (IOC, but no DI):
override void Execute() {
ISomeUtility util = Registry.Get<ISomeUtility>();
if(util != null) util.Foo();
}
(where you'd need to write Registry etc; plus on the server, register the ISomeUtility implementation)
You can use the new dynamic type functionality to avoid having to build a registry of types to methods:
using System;
using System.Collections.Generic;
using System.Linq;
using visitor.Extension;
namespace visitor
{
namespace Extension
{
static class Extension
{
public static void RunVisitor(this IThing thing, IThingOperation thingOperation)
{
thingOperation.Visit((dynamic)thing);
}
public static ITransformedThing GetTransformedThing(this IThing thing, int arg)
{
var x = new GetTransformedThing {Arg = arg};
thing.RunVisitor(x);
return x.Result;
}
}
}
interface IThingOperation
{
void Visit(IThing iThing);
void Visit(AThing aThing);
void Visit(BThing bThing);
void Visit(CThing cThing);
void Visit(DThing dThing);
}
interface ITransformedThing { }
class ATransformedThing : ITransformedThing { public ATransformedThing(AThing aThing, int arg) { } }
class BTransformedThing : ITransformedThing { public BTransformedThing(BThing bThing, int arg) { } }
class CTransformedThing : ITransformedThing { public CTransformedThing(CThing cThing, int arg) { } }
class DTransformedThing : ITransformedThing { public DTransformedThing(DThing dThing, int arg) { } }
class GetTransformedThing : IThingOperation
{
public int Arg { get; set; }
public ITransformedThing Result { get; private set; }
public void Visit(IThing iThing) { Result = null; }
public void Visit(AThing aThing) { Result = new ATransformedThing(aThing, Arg); }
public void Visit(BThing bThing) { Result = new BTransformedThing(bThing, Arg); }
public void Visit(CThing cThing) { Result = new CTransformedThing(cThing, Arg); }
public void Visit(DThing dThing) { Result = new DTransformedThing(dThing, Arg); }
}
interface IThing {}
class Thing : IThing {}
class AThing : Thing {}
class BThing : Thing {}
class CThing : Thing {}
class DThing : Thing {}
class EThing : Thing { }
class Program
{
static void Main(string[] args)
{
var things = new List<IThing> { new AThing(), new BThing(), new CThing(), new DThing(), new EThing() };
var transformedThings = things.Select(thing => thing.GetTransformedThing(4)).Where(transformedThing => transformedThing != null).ToList();
foreach (var transformedThing in transformedThings)
{
Console.WriteLine(transformedThing.GetType().ToString());
}
}
}
}
I would suggest something like the following. This code could be improved by adding support for detecting intermediate class hierarchy types that don't have a dispatch mapping and calling the nearest dispatch method based on the runtime hierarchy. It could also be improved by using reflection to detect overload of ExecuteInteral() and adding them automatically to the dispatch map.
using System;
using System.Collections.Generic;
namespace LanguageTests2
{
public class A { }
public class B : A {}
public class C : B {}
public static class VirtualExtensionMethods
{
private static readonly IDictionary<Type,Action<A>> _dispatchMap
= new Dictionary<Type, Action<A>>();
static VirtualExtensionMethods()
{
_dispatchMap[typeof(A)] = x => ExecuteInternal( (A)x );
_dispatchMap[typeof(B)] = x => ExecuteInternal( (B)x );
_dispatchMap[typeof(C)] = x => ExecuteInternal( (C)x );
}
public static void Execute( this A instance )
{
_dispatchMap[instance.GetType()]( instance );
}
private static void ExecuteInternal( A instance )
{
Console.WriteLine("\nCalled ToString() on: " + instance);
}
private static void ExecuteInternal(B instance)
{
Console.WriteLine( "\nCalled ToString() on: " + instance );
}
private static void ExecuteInternal(C instance)
{
Console.WriteLine("\nCalled ToString() on: " + instance);
}
}
public class VirtualExtensionsTest
{
public static void Main()
{
var instanceA = new A();
var instanceB = new B();
var instanceC = new C();
instanceA.Execute();
instanceB.Execute();
instanceC.Execute();
}
}
}
Virtual implies inheritance in a OOP way and extension methods are "just" static methods that through a bit a syntactic sugar the compiler allows you to pretend to call on an instance of the type of its first parameter. So no, virtual extension methods are out of the question.
Check out the answer by Marc Gravell for a possible solution to your problem.
You can implement a service register. Example (server side):
static IDictionary<Type, IService> serviceRegister;
public void ServerMethod(IBusinessType object)
{
serviceRegister[obect.GetType()].Execute(object);
}
What you need are rather services in your server, which implement server side functionality, instead of extension methods. I wouldn't put to much logic into extension methods.
Let me check: you have a class hierarchy inheriting from A, presumably structured according to your business domain. Then you want to add behaviours depending on where the classes execute. So far you've used extension methods, but now you find you cannot get them to vary with your class hierarchy. What kinds of behaviours are you attaching at the server?
If it's stuff like transaction management and security, policies implemented through dependency injection à la Marc's suggestion should work well. You could also consider implementing the Strategy pattern through delegates and lambdas, for a more limited version of DI. However, what's not clear is how client code currently uses your classes and their extension methods on the server. How dependent are other classes on how you add the server-side functionality? Are they server-side only classes that currently expect to find the extension methods?
In any case, it sounds like you're going to need a careful testability design and testing strategy since you are introducing variation along two simultaneous dimensions (inheritance hierarchy, execution environment). You are using unit testing, I trust? Check that whatever solution you choose (e.g. DI through configuration) interacts well with testing and mocking.

Categories

Resources