Inheritance in Specflow test steps cause Ambiguous Steps - c#

I've read that using inheritance is not possible when using Specflow, which makes sense most of the time. However, I've run across a situation that seems to require the proper the use of inheritance. Here are my classes:
Base Class:
public class StepBaseClass
{
protected readonly ScenarioContext scenarioContext;
public StepBaseClass(ScenarioContext scenarioContext)
{
this.scenarioContext = scenarioContext;
}
}
First Inherited Class:
[Binding]
public class StudioEnterpriseImportConnectorSteps:StepBaseClass
{
public StudioEnterpriseImportConnectorSteps(ScenarioContext scenarioContext) :base(scenarioContext)
{
}
[Given(#"I have a data record that I want to send to the import service")]
public void GivenIHaveADataRecordThatIWantToSendToTheImportService()
{
scenarioContext.Pending();
}
[When(#"I send the information to an invalid URL")]
public void WhenISendTheInformationToAnInvalidURL()
{
scenarioContext.Pending();
}
[Then(#"an error should be generated")]
public void ThenAnErrorShouldBeGenerated()
{
scenarioContext.Pending();
}
}
2nd inherited class:
[Binding]
public class SitemapSteps:StepBaseClass
{
public SitemapSteps(ScenarioContext scenarioContext):base(scenarioContext)
{
}
[When(#"I visit the URL (.*)")]
public void WhenIVisitTheSitemapURL(string URL)
{
scenarioContext.Add("result", TestUtilities.GetResponseCode(URL));
scenarioContext.Add("response", TestUtilities.GetResponseBody(URL));
}
[Then(#"the response code should be (.*)")]
public void ThenTheResponseCodeShouldBe(string responseCode)
{
HttpStatusCode result = scenarioContext.Get<HttpStatusCode>("result");
Assert.Equal(responseCode, result.ToString());
}
}
As you can see, the only thing that I'm inheriting the the scenarioContext, which is something that I need to do in order to write multi-threaded tests. So instead of repeating this piece of code for each of my classes, I would like to be able to inherit from a base class. What is the proper method of initializing that variable so that I can use it in each of my derived classes?

The proper way depends as always on your individual situaion.
I recommend always to not use base classes and use context injection everywhere. The small number of code that is repeated in the constructor is a small price for a good separation and splitting of your bindings and their implementation.
To get more info about this topic, Gaspar Nagy wrote a nice blog article about the pros and cons of step base classes in SpecFlow:
http://gasparnagy.com/2017/02/specflow-tips-baseclass-or-context-injection/

After initializing my Dependency Injection in the Specflow Test hooks, I would have a class called ApplicationContext with a static resolve method which would return me my ScenarioContext instance like so:
public class ApplicationContext
{
public static T Resolve<T>() where T: class
{
return container.GetInstance<T>();
}
}
Then in my steps class, I would resolve the ScenarioContext like this:
scenarioContext = (ScenarioContext)ApplicationContext.Resolve<IScenarioContext>();

Related

Calling abstract method in constructor of abstract class

As CA2214 states, one should not call an overridable method in a constructor. However, I've come across a case where I can't see another way to do what I'm trying to achieve and I can't see potential problems arising from breaking this rule:
I have an abstract base class for configurations. In this class, there is logic for how to fetch the values.
My applications have configs that can be made up of certain components. So my SpecificConfig would inherit from ConfigBase and be made up of ConfigComponentA and ConfigComponentB:
public abstract class ConfigBase
{
protected ConfigBase()
{
this.InitializeMembers();
this.SetConfigValues();
}
protected abstract void InitializeMembers();
private void SetConfigValues() {
// Set the config values
// Depends on members initialized in InitializeMembers
}
}
public class ConfigComponentA
{
public string FieldA1;
public string FieldA2;
}
public class ConfigComponentB
{
public string FieldB1;
public string FieldB2;
}
public sealed class SpecificConfig : ConfigBase
public SpecificConfig() : base() {}
public ConfigComponentA ConfigA;
public ConfigComponentB ConfigB;
protected override void InitializeMembers()
{
this.ConfigA = new ConfigComponentA();
this.ConfigB = new ConfigComponentB();
}
}
The main point is that the configs could be made up of different components, and I want to avoid code duplication by having the logic for fetching and setting the config values in SetConfigValues() in the base class.
I have a feeling there may be a better way of going about this altogether, but I don't really see any unexpected behaviour that could come of this. Is there a better approach?

Setting up Dependency Injection using StructureMap

Currently I am trying to set up Dependency Injection using StructureMap for my MVC 5 project.
Following the instructions to set up the design pattern, it continues to fail in the regard when I try and make a call to the controller using the Route Prefix the constructors are never hit, so the object is never initialized, so the program keeps stating the object needs initializing. Prior to this issue, the program would not compile without parameterless constructors but when I do add a parameterless constructor the Interface object I use in the controller is null.
I am following the naming convention that is required by the framework, so the objects should be picked up by the default methods provided by StructureMap, and that is initialized in the DefaultRegistry.cs which is prebuilt when you install StructerMap in the Nuget Packages.
The format for the classes that are using the Repository Design Pattern are below:
Controller Class:
[RoutePrefix("api/data")]
public class TrialController : Controller
{
private readonly ITeacherService _teacherService;
public TrialController(ITeacherService teacherService)
{
_teacherService = teacherService;
}
[Route("trial")]
[HttpGet]
public void Get()
{
_teacherService.GetTeacher();
}
}
Service Class
public interface ITeacherService
{
void GetTeacher();
}
public class TeacherService : ITeacherService
{
public ITeacherRepository _teacherRepository;
public TeacherService(ITeacherRepository teacherRepository)
{
_teacherRepository = teacherRepository;
}
public void GetTeacher()
{
_teacherRepository.GetTeacher();
}
}
Repository Class
public interface ITeacherRepository
{
bool GetTeacher();
}
public class TeacherRepository : ITeacherRepository
{
public readonly ITeacherRepository _teacherRepository;
public TeacherRepository(ITeacherRepository teacherRepository)
{
_teacherRepository = teacherRepository;
}
public bool GetTeacher()
{
return true;
}
}
Thank you for taking your time to read this, and if any advice on how to resolve issue much appreciated :)

Pass-through constructors from its base class

An external framework has the following classes:
public class Boatmaker
{
}
public class Wood
{
}
public class Axe
{
}
public class Lake
{
}
public class Boat
{
public Boat(Wood wood, Axe axe) {
}
public Boat (Boatmaker maker) {
}
public Boat (Lake lake) {}
}
I need to do a lot of subclassing of Boat. For each of my subclasses, I have to assume that the external framework may want to instantiate it via any of the above constructors. So my subclasses get pass-through constructors. Notice how they never go away:
public class SmallBoat: Boat
{
public void DoSmallBoatStuff() {
// some code here
}
private void Initialize() {
this.DoSmallBoatStuff();
}
public SmallBoat(Wood wood, Axe axe): base(wood, axe) {
this.Initialize();
}
public SmallBoat (Boatmaker maker): base(maker) {
this.Initialize();
}
public SmallBoat (Lake lake): base(lake) {
this.Initialize();
}
}
public class Canoe: SmallBoat
{
public void DoCanoeStuff() {
// some code here
}
private void Initialize() {
this.DoCanoeStuff();
}
public Canoe(Wood wood, Axe axe): base(wood, axe) {
this.Initialize();
}
public Canoe (Boatmaker maker): base(maker) {
this.Initialize();
}
public Canoe(Lake lake): base(lake) {
this.Initialize();
}
}
I am wondering if there is a way to simplify the appearance of the code. The only difference between the way the constructors are written in SmallBoat and Canoe is the word SmallBoat or Canoe. Everything else is the same.
So if there were a way to write a constructor without actually using the name of the class in the constructor, it would help a lot. I could use direct copy and paste without a .tt file (which is not really viable for me -- most of my work is not done in Visual Studio). Is there a way to do that?
No. There is not. You have to specify which constructors of the base class you want to make available from the current class. There is no way to write the constructor without mentioning the real class name.
It might be a simplification you are showing, but if Initialize is the only method called, you might want to move that call to the base class calling a protected Initialize method you can override from the implementing classes. (You have to take in consideration the order of calling that method and instantiating properties/fields. You can run into trouble there, so it might not be viable in your situation)
1. Automation of code typing
There is code snippet : ctor that helps create "only" default constructor.
To use it type ctor an tabulation twice.
The original code snippet can be copied to create your own.
In Visual Studio, go in Tools menu/Code snippet manager.
You can see here the directories of the snippet files.
You can copy a snippet ( ctor.snippet for instance ) to "My Code Snippets", rename it and edit.
2. Design of the boat hierarchy
The boat hierarchy can also be designed so there is only a default constructor in the base class, and you have public properties or public method(s) in the base class to provide Lake, Axe, BoatMaker, ...
If you can change the design, I highly recommend separate object instantiation from the object itself. This way, the Factory Method combining with Template Method design pattern comes very helpful:
public abstract class BoatFactory
{ protected abstract void Initialize();
protected Wood Wood;
protected Axe Axe
protected Boatmaker Boatmaker ;
public Boat MakeBoat(Wood wood, Axe axe)
{
this.Wood = wood;
this.Axe = axe;
Initialize();
}
public Boat MakeBoat(Boatmaker maker)
{
this.Boatmaker = Boatmaker ;
Initialize();
}
public Boat MakeBoat(Lake lake)
{
this.Lake = lake;
Initialize();
}
}
public class SmallBoatFactory : BoatFactory
{
protected override void Initialize()
{
// do customized init operations here
}
}

.NET Tools: Extract Interface and Implement Wrapper Class

Is there a tool that can generate extract and generate interfaces for existing classes?
I know Visual Studio will extract an Interface for an existing class. However, I would also like to generate a wrapper class that implements that functionality.
I believe this would help tremendously for unit testing.
Example Existing Class:
public class ThirdPartyClass
{
public void Method1(){}
public void Method2(){}
}
This can be generated by Visual Studio (Extract Interface):
public interface IThirdPartyClass
{
void Method1();
void Method2();
}
I would like to go one step further:
public class ThirdPartyClassWrapper : IThirdPartyClass
{
private tpc = new ThirdPartyClass();
public void Method1()
{
tpc.Method1();
}
public void Method2()
{
tpc.Method2();
}
}
Update:
This would be especially useful for static classes. As Morten points out I can just use a stub, however, I would like to break up my coupling if possible.
Found a way around it for non-sealed classes.
1 - Inherit from the external class
class MyWrapper : ExternalClass
2 - Extract interface for all public methods
class MyWrapper : ExternalClass, IExternalClass
3 - Remove the inheritance from the external class
class MyWrapper : IExternalClass
4 - You will get a hint on the class name about members from the interface not being implemented. Alt + Enter on it and let Resharper automatically implement them
5 - Use this code template to wrap properties
get { return $INNERCOMPONENT$.$NAME$; }
set { $INNERCOMPONENT$.$NAME$ = value; }
6 - Use this code template to wrap methods
return $INNERCOMPONENT$.$NAME$($SIGNATURE$);
I don't know a tool that would do that for you.
You probably know, but Visual Studio goes just half step further - it can provide empty implementation of interface. I would stop there if it is one time task.
Depending on actual goal using some other way may work - i.e. for testing you can use mocking frameworks - usually there is a way to wrap existing class and override some methods as needed.
Another really slick way of doing this is to use Resharper to generate the "Delegating members" for you as described here: https://stackoverflow.com/a/2150827/1703887
Steps:
Create a new class that inherits from the class you want to wrap with a private variable of that class' type:
public class ThirdPartyClassWrapper : ThirdPartyClass
{
private ThirdPartyClass _ThirdPartyClass;
}
Do a Alt-Insert in/on the class to use Resharper to generate "Delegating members". Choose the methods you want to expose and pass through to the private variable.
If you have the free version of the GhostDoc extension installed you can highlight all of the created properties, methods, etc. and do a Ctrl-D to automatically grab all of the documentation from the base class and put it on the new members. (Resharper can do this too but I think you'd have to put "new" on each item which would then allow you to Alt-Enter and choose "Add xml-doc comments" from the Resharper popup menu).
You can then delete the base class and do some additional cleanup in case the method/property signatures expose any other types that you need to wrap.
What you are looking for is a stub, this can be done either by making your own stub implementation of the interface, or by using a mocking framework like Rhinomocks. Wrapping a difficult class in another class for testpurposes does nothing good for you.
Regards
Morten
I strongly suggest you look into a mocking framework like Fakeiteasy.
But to give you exactly what you asked for see below. I suspect ReSharper didn't have this operation when others answered.
add the interface to the class you wish to be the wrapping class
class MyWebElement : IWebElement { }
Find/Click "Delegate implementation of "YourInterfaceHere" to a new field
Select your options
Click finish and enjoy your new class
class MyWebElement : IWebElement
{
private IWebElement _webElementImplementation;
public IWebElement FindElement(By #by)
{
return _webElementImplementation.FindElement(#by);
}
public ReadOnlyCollection<IWebElement> FindElements(By #by)
{
return _webElementImplementation.FindElements(#by);
}
public void Clear()
{
_webElementImplementation.Clear();
}
public void SendKeys(string text)
{
_webElementImplementation.SendKeys(text);
}
public void Submit()
{
_webElementImplementation.Submit();
}
public void Click()
{
_webElementImplementation.Click();
}
public string GetAttribute(string attributeName)
{
return _webElementImplementation.GetAttribute(attributeName);
}
public string GetCssValue(string propertyName)
{
return _webElementImplementation.GetCssValue(propertyName);
}
public string TagName
{
get { return _webElementImplementation.TagName; }
}
public string Text
{
get { return _webElementImplementation.Text; }
}
public bool Enabled
{
get { return _webElementImplementation.Enabled; }
}
public bool Selected
{
get { return _webElementImplementation.Selected; }
}
public Point Location
{
get { return _webElementImplementation.Location; }
}
public Size Size
{
get { return _webElementImplementation.Size; }
}
public bool Displayed
{
get { return _webElementImplementation.Displayed; }
}
}

How to auto generate Decorator pattern in C#

I have some interface, and a class implementing this interface, say:
interface IMyInterface
{
void Func1();
void Func2();
}
class Concrete : IMyInterface
{
public virtual void Func1() { //do something }
public virtual void Func2() { //do something }
}
Now, I want to create a class that decorates each of the concrete class methods with some specific logic, to be executed in non production environment, before and after the call.
class Decorator : Concrete
{
public override void Func1() { Pre(); base.Func1; Post(); }
public override void Func2() { Pre(); base.Func2; Post(); }
}
My question is there a simpler way to auto generate such class other than use reflection on the interface and create a text file with cs extension?
Personally I would just explicitly log where needed, but if you are set on using a decorator to do this you could use the RealProxy class.
It could look something like this:
public class DecoratorProxy<T> : RealProxy
{
private T m_instance;
public static T CreateDecorator<T>(T instance)
{
var proxy = new DecoratorProxy<T>(instance);
(T)proxy.GetTransparentProxy();
}
private DecoratorProxy(T instance) : base(typeof(T))
{
m_instance = instance;
}
public override IMessage Invoke(IMessage msg)
{
IMethodCallMessage methodMessage = msg as IMethodCallMessage;
if (methodMessage != null)
{
// log method information
//call method
methodMessage.MethodBase.Invoke(m_instance, methodMessage.Args);
return new ReturnMessage(retval, etc,etc);
}
}
}
Have you tried PostSharp? It can help you automatically "instrument" classes and achieve your logging scenario without actually creating decorators.
What about the Logging Application block?
http://msdn.microsoft.com/en-us/library/ff647183.aspx
I have written a T4 template capable of generating decorator for fairly complex classes based on some simple conventions. The project can be found on GitHub - T4Decorators. Works similar to T4MVC, that is where I got the idea.
Could you use T4 and reflection?
Maybe these other questions could help:
T4 Code generation: Access types in current project
How do you use .Net reflection with T4
We have the same requirement and wrote a Roslyn generator to do this, take a look here: https://github.com/proactima/ProxyGen
You need to modify the code slightly to fit your needs. Basically we wrap the methods of an interface (all from a certain namespace) in a 'ReliableServiceCall' method. It's trivial to modify this to do something else.
Best approach here is to use Decorator Pattern via interfaces. I know this is a very old post, but if you use an IoC injector, like SimpleInjector, you can setup these decorator calls in 1 line of code. Then you can do something like this:
public class Decorator : IMyInterface
{
private readonly IMyInterface _next;
public Decorator (IMyInterface next) { _next = next; }
public override void Func1() { Pre(); _next.Func1; Post(); }
public virtual void Func2() { Pre(); _next.Func2; Post(); }
}

Categories