I have class MyService that depends on ABCService (Nuget package/sdk)
public class MyService
{
private readonly ABCService _abc;
public MyService(ABCService abc)
{
this._abc = abc;
}
public async Task Run(string id)
{
// some logic
var result = await this._abc.DoSomething(id);
// some logic
}
}
ABCService looks something like this:
public class ABCService
{
internal ABCService(string someConnectionString, object someSettings)
{
// ... initialization
}
public static CreateFromConnectionString(string someConnectionString, object someSettings)
{
// some logic
return new ABCService(someConnectionString, someSettings);
}
}
Mocking class this way would not work and throws exception. "Parent does not have a default constructor."
var mock = new Mock<ABCService>();
var myService = new MyService(mock.Object);
How should I approach this? Is there a way to mock such classes?
The only thing that comes to my mind is creating interface IABCService and then injecting it in the constructor of MyService
public class IABCService
{
Task DoSomething(string id);
}
public class MyService
{
private readonly IABCService _abc;
public MyService(IABCService abc)
{
this._abc = abc;
}
}
And then I could do this:
var mock = new Mock<IABCService>();
var myService = new MyService(mock.Object);
Popular isolation frameworks such as Moq, NSubstitute or FakeItEasy are constrained. They can substitute only virtual methods. To use them, you will have to use the interface, as you already guessed. This is the recommended way to easily maintain loose coupling and testability.
There are bunch of unconstrained mocking frameworks: TypeMock Isolator, JustMock, Microsoft Fakes (all three are paid) and free open source Prig, Pose, Shimmy, Harmony, AutoFake, Ionad.Fody, MethodRedirect. They allow to mock non-virtual members, including private, static, etc.
Some of them allow you to work wonders, but you should not get too carried away with using them, because in the end it can lead to bad architecture.
Suppose I have the following classes from a third-party library:
public class ThirdPartyType { ... }
public class ThirdPartyFunction
{
public ThirdPartyType DoSomething() { ... }
}
The implementation details are not important, and they are actually outside of my control for this third-party library.
Suppose I write an adapter class for ThirdPartyFunction:
public class Adapter
{
private readonly ThirdPartyFunction f;
public Adapter()
{
f = new ThirdPartyFunction();
}
public string DoSomething()
{
var result = f.DoSomething();
// Convert to a type that my clients can understand
return Convert(result);
}
private string Convert(ThirdPartyType value)
{
// Complex conversion from ThirdPartyType to string
// (how do I test this private method?)
...
}
}
How can I test that my implementation of Convert(ThirdPartyType) is correct? It's only needed by the Adapter class, which is why it's a private method.
I would recommend extracting the code to a seprate class and then testing that class. Although it is only used by this Adapter it shouldn't be the responsibility of the adapter to do the conversion as well (in keeping with the Single Responsibility Principle).
By extracting it out it gives you the ability to test the converter in isolation from the third party code.
If the converter does not require any state you could also make it a static class and then reference it directly in your adapter without the need for registering it with dependency injection.
If you think about it, the adapter doesn't need testing (as it is just a wrapper) but the converter does - so extracting it to another class makes sense to allow it to be tested, even if it does mean another class in the code.
In addition, extracting the converter to a separate class means that if the ThirdPartyType or the format of your string changes then you can make the changes without affecting the Adapter implementation.
If you change your Adapter class to allow the ThirdPartyFunction f to be passed to it, then you can use a mock version of it in your test class. this will allow you to test the Convert function.
I'm not sure of the exact syntax as I am not familiar with the language, but I will give it a try:
public class Adapter
{
private readonly ThirdPartyFunction f;
// pass the function to the constructor when creating the adapter
public Adapter(ThirdPartyFunction inputF)
{
f = inputF;
}
public string DoSomething()
{
var result = f.DoSomething();
// Convert to a type that my clients can understand
return Convert(result);
}
private string Convert(ThirdPartyType value)
{
// Complex conversion from ThirdPartyType to string
// (how do I test this private method?)
...
}
}
In your real implementation, when you create the new Adapter, you can pass it a new ThirdPartyFunction.
In your test implementation, you can pass it a Mocked version of that ThirdPartyFunction which returns a fixed value for testing. Maybe like:
class MockThirdPartyFunction extends ThirdPartyFunction
{
private ThirdPartyType testData;
public MockThirdPartyFunction(ThirdPartyType data)
{
testData = data;
}
override public ThirdPartyType DoSomething()
{
// return a fixed third party type passed in on mock creation
return testData
}
}
You create the test adapter with the mocked value, where you can set the specific ThirdPartyType you want to test. Then in your test when you call DoSomething on the Adapter, you are controlling the input to your Convert function and can see the output and compare accordingly to expected results.
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.
I have a class that I would like to test with Unit tests. It has some logic to look for some values in the local xml file, and if the value is not found it will read some external source (SqlServer DB). But during Unit testing I don't want this component to interact with Sql Server at all. During unit testing I would like to replace SqlServer implementation of the External source reader to some Noop reader. What is the good approach to achieve that? Important note: I can't define constructor that accepts instance of reader type since it is client facing API and I want to limit what they can do with my classes.
I am currently using few ways in Unit tests:
Use reflection to set value of the private/protected property to my mocked implementation of the reader
Define factory that will create concrete class. Register factory in Unity container & class under test will get factory object from DI container and instantiate reader according to my needs
Subclass class-under-test and set property there.
But none of them seem to be clean enough to me. Are there any better ways to achieve that?
Here is the sample code to demonstrate example of the class-under-the-test:
namespace UnitTestProject1
{
using System.Collections.Generic;
using System.Data.SqlClient;
public class SomeDataReader
{
private Dictionary<string, string> store = new Dictionary<string, string>();
// I need to override what this property does
private readonly IExternalStoreReader ExternalStore = new SqlExternalStoreReader(null, false, new List<string>() {"blah"});
public string Read(string arg1, int arg2, bool arg3)
{
if (!store.ContainsKey(arg1))
{
return ExternalStore.ReadSource().ToString();
}
return null;
}
}
internal interface IExternalStoreReader
{
object ReadSource();
}
// This
internal class SqlExternalStoreReader : IExternalStoreReader
{
public SqlExternalStoreReader(object arg1, bool arg2, List<string> arg3)
{
}
public object ReadSource()
{
using (var db = new SqlConnection("."))
{
return new object();
}
}
}
internal class NoOpExternalStoreReader : IExternalStoreReader
{
public object ReadSource()
{
return null;
}
}
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var objectToTest = new SomeDataReader();
objectToTest.Read("", -5, false); // This will try to read DB, I don't want that.
}
}
In this case, you can use the InternalsVisibleTo attribute, which exposes all internal members to friend assemblies.
You could start by creating a separate internal constructor overload, which can accept a different instance of IExternalStoreReader:
public class SomeDataReader
{
// publicly visible
public SomeDataReader()
: this(new SqlExternalStoreReader(...))
{ }
// internally visible
internal SomeDataReader(IExternalStoreReader storeReader)
{
ExternalStore = storeReader;
}
...
}
And then allow the unit testing assembly to access internal members by adding the InternalsVisibleTo attribute to your AssemblyInfo.cs:
[assembly: InternalsVisibleTo("YourUnitTestingAssembly")]
If you're really concerned about people trying to access your internal members, you can also use strong naming with the InternalsVisibleTo attribute to ensure no one tries to impersonate your unit testing assembly.
The simple answer is: change your code. Because you have a private readonly field that creates its own value, you cannot change that behaviour without getting really hacky, if at all. So instead, don't do it that way. Change the code to:
public class SomeDataReader
{
private Dictionary<string, string> store = new Dictionary<string, string>();
private readonly IExternalStoreReader externalStore;
public SomeDataReader(IExternalStoreReader externalStore)
{
this.externalStore = externalStore;
}
In other words, inject the IExternalStoreReader instance into the class. That way you can create a noop version for unit tests and the real one for production code.
If you're compiling the complete code yourself, you could create a fake SqlExternalStoreReader with a stubbed implementation inside your unit test project.
This stub implementation allows you to access all fields and forward calls to your mocking framework/unit test
I want to write tests for a program that is coded by someone else. But I have some problems while writing tests. I can't understand exactly how to fake some objects. I searched and found Unit Test for n tier architecture but It doesn't help me. For example, I want to write a test for code below (I know It is a dummy code for just clarification)
public List<CustomerObject> FetchCustomersByName(CustomerObject obj)
{
DAL customerDal = new DAL();
//Maybe other operations
List<CustomerObject> list = customerDal.FetchByName(obj.Name);
//Maybe other operations over list
return list;
}
I just want to test FetchCustomersByName but there is connection with DAL. I think creating stub class but In this case I have to change my original code. And it was coded by someone else. How can I write a test for this method?
Thanks in advance.
Don't unit test the data access layer. Write integration tests for it.
Mocking the dependencies in the DAL isn't just worth the trouble as it doesn't guarantee anything.
If you think about it, the DAL have dependencies on the SQL dialect and the database schema. Therefore your unit tests might work just fine. But when you run the real solution it can still fail. The reason can be that your SQL queries are incorrect or that the one of the class property types doesn't match the table column types.
unit tests are typically written for business logic. One thing that they catch is errors that doesn't generate exceptions such as incorrect conditions or calculation errors.
Update
Ok. So your example actually contains business logic. The method name fooled me.
You have to change the way you create your DAL classes. But you don't have to use constructor injection like Jack Hughes suggests. Instead you can use the factory pattern:
public List<CustomerObject> FetchCustomersByName(CustomerObject obj)
{
var customerDal = DalFactory.Create<CustomerDal>();
//Maybe other operations
List<CustomerObject> list = customerDal.FetchByName(obj.Name);
//Maybe other operations over list
return list;
}
That's bit easier since now you can just use "replace all" to change all var customerDal = new CustomerDal() to var customerDal = DalFactory.Create<CustomerDal>();
In that factory class you can call different implementations
public class DalFactory
{
public static IDalFactory Factory { get set; }
static DalFactory()
{
Factory = new DefaultDalFactory();
}
public static T Create<T>() where T : class
{
return Factory.Create<T>();
}
}
public interface IDalFactory
{
T Create<T>() where T : class
}
public class DefaultDalFactory : IDalFactory
{
public T Create<T>() where T : class
{
return new T();
}
}
The code isn't beautiful, but it solves your case with minimal refactoring. I suggest that you start with that and then try to change your coding standards so that constructor injection is allowed.
To get it working in your tests you can use the following implementation. It uses [ThreadStatic] to allow multiple tests to run at the same time.
public class TestDalFactory : IDalFactory
{
[ThreadStatic]
private static Dictionary<Type, object> _instances;
public static Dictionary<Type, object> DalInstances
{
get
{
if (_instances == null)
_instances = new Dictionary<Type, Object>();
return _instances;
}
}
public static TestDalFactory Instance = new TestDalFactory();
public T Create<T>() where T : class
{
return (T)_instances[typeof(T)];
}
}
Next in your tests you can configure the DAL factory to return a mock by doing the following:
[TestClass]
public class MyBusinessTests
{
[TestInitialize]
public void Init()
{
DalFactory.Instance = TestDalFactory.Instance;
}
[TestMethod]
public void do_some_testing_in_the_business()
{
TestDalFactory.Instance.DalInstances[typeof(CustomerDal)] = new MyNewMock();
//do the testing here
}
}
Using constructor injection of the DAL would allow you to stub the DAL layer. Ideally you would inject an interface. Mocking concrete classes is a bit of a pain with the tools I've used. Commercial mocking tools may well be better suited to mocking concrete classes but I've not used any of those.
class YourClass
{
private DAL customerDal;
public YourClass(DAL theDal)
{
customerDal = theDal;
}
public List<CustomerObject> FetchCustomersByName(CustomerObject obj)
{
// don't create the DAL here...
//Maybe other operations
List<CustomerObject> list = customerDal.FetchByName(obj.Name);
//Maybe other operations over list
return list;
}
}
[Test]
public void TestMethodHere()
{
// Arrange
var dalMock = Mock.Of<DAL>();
// setup your mock DAL layer here... need to provide data for the FetchByName method
var sut = new YourClass(dalMock);
// Act
var actualResult = sut.FetchCustomersByName(new CustomerObject());
// Assert
// Your assert here...
}