Differences between test spy implementations - c#

I am having some trouble defining which kind of test doubles these two classes are.
They both contain (basic) behaviour.
Their difference is that the first in a real context would not run, while the second would (it'd be basically a does-nothing class, but it'd work! The second would crash).
They both seem like Test Spies to me. They both provide a way to get whether the Run() method was called or not. (that is these classes' reason of being!).
I can't use the second one as it is in all the contexts, as I can't also use just the first one in all contexts.
I could refactor both of them into one, but maybe that'd turn things less clear when reading the code.
class FilterTestSpy : IFilter {
private bool hasBeenRan = false;
...
public bool HasBeenRan { get { return hasBeenRan; } }
public void Run() {
hasBeenRan = true;
}
}
class FilterTestSpy2: IFilter {
private bool hasBeenRan = false;
...
public bool HasBeenRan { get { return hasBeenRan; } }
public void Run() {
...some logic...
hasBeenRan = true;
}
}
I know there are mocking frameworks, blablabla, that is not what I am asking about here.
Thanks!

Could you create a strategy to delegate to in the Run() method? That way you will be able to have just one spy class, with a single responsibility, i.e, tell whether the method was called. So, for different contexts, you can inject different strategies.

Related

Mutually exclusive abstract methods in C#

I am developing a C# library where the user needs to write his/her own classes inheriting from given classes from the library. I don't think writing further details will be helpful, so please even if what I am asking for looks strange, consider it as such.
In one class, I would like the following behavior: two mutually exclusive "abstract" methods such that if one is implemented then there is no need to implement the other (so right, they are not really abstract).
I need to force the user to implement at least one of these methods, so declaring both methods virtual only is not enough. Actually I could declare both abstract, but it means the user should implement a method that would never be called afterwards and of course I want to avoid that.
Is there a trick or a C# idiom to do something close to what I want? Maybe with some reflection tricks I know almost nothing about?
I think what you're trying to do is violating a lot of Object-Oriented design goals.
"I need to force the user to implement at least one of these methods"
If the two classes need to have functionality that is is one thing or the other, why not just have 1 abstract method (or create an interface), and have the two classes override that method differently? Then you force each class to implement one part of the functionality and the other implement the other type.
I would recommend re-thinking your approach rather than spending tons of time trying to make a poor approach work.
EDIT:
Based on your comments I'll try to go into a bit more detail.
You could try something like the following. But I suspect you'll need to expand it significantly to get it working. But this should get you started anyway
public class ResultFromMethod1 {
public bool optimized = false;
// other results here
}
This stores the results from method 1 and tells you how method 1 was run.
public interface IInterfaceForMethod1 {
ResultFromMethod1 Method1 ();
}
public interface IInterfaceForMethod2 {
void Method2 (ResultFromMethod1 resultFromMethod1, Vector v);
}
These are the interfaces for the two methods. Note that they are not implemented yet. This is just a contract for classes that implement them.
public class UnoptomizedImplementation : IInterfaceForMethod1, IInterfaceForMethod2 {
#region IInterfaceForMethod1 implementation
public ResultFromMethod1 Method1 () {
ResultFromMethod1 resultFromMethod1 = new ResultFromMethod1 ();
resultFromMethod1.optimized = false;
// Method1 logic here
return resultFromMethod1;
}
#endregion
#region IInterfaceForMethod2 implementation
public void Method2 (ResultFromMethod1 resultFromMethod1, Vector v) {
if (!ResultFromMethod1.optimized) {
//if NOT optimized
//logic here
}
else {
//throw exception
}
}
#endregion
}
These class runs method1 not optimized, and then has a method2 that requires method 1 be not optimized. If you don't need method2 when it's not optimized then just don't implement the method2 interface.
public class OptimizedImplementation : IInterfaceForMethod1, IInterfaceForMethod2 {
#region IInterfaceForMethod1 implementation
public ResultFromMethod1 Method1 () {
ResultFromMethod1 resultFromMethod1 = new ResultFromMethod1 ();
resultFromMethod1.optimized = true;
// Method2 logic here
return resultFromMethod1;
}
#endregion
#region IInterfaceForMethod2 implementation
public void Method2 (ResultFromMethod1 resultFromMethod1, Vector v) {
if (ResultFromMethod1.optimized) {
//if optimized
//logic here
}
else {
//throw exception
}
}
#endregion
}
This class requires an output from method1 that is optimized or it throws an exception.
I hope that sends you down a more manageable track.
I suggest implementing interfaces
public interface IMyMethod1 {
void MyMethod1();
}
public interface IMyMethod2 {
void MyMethod2();
}
and inject a dependency
public class MyClass {
...
public MyClass(IMyMethod1 method1, IMyMethod2 method2) {
if ((null == method1) && (null == method2))
throw new ArgumentNullException("method1",
"You should provide either method1 or method2");
m_Method1 = method1;
m_Method2 = method2;
}
...
public void DoSomething() {
...
if (m_Method1 != null)
m_Method1.MyMethod1();
else if (m_Method2 != null)
m_Method2.MyMethod2();
...
}
}
To avoid reflection, create you base class (abstract) without either of those two methods.
Then, create separate classes (abstract) inheriting your base class for both of the "special" methods.
This will require some type-checking and casting, but it's all I got right now.

A better architecture then if(something) DoIt() else Dont()

I'm trying to create a mechanism that will allow the application to decide (in runtime) whether to execute some functionality.
"Some Functionality" can be anything, it can be c# code which is contained in several classes in several dlls, it can be UI, it can be database query execution, etc.
Most importantly, it should fit in the current existing infrastructure I have, which I cannot re-design and build from scratch.
The more I think of it, it seems like the only solution I can use would be to hold some table which will be the "functionality repository" and it will tell (by unique key) if a functionality is on / off.
Then in code, I will have to place in each spot which handles such functionality an if else statement.
E.g.
If(functionalityEnabled)?
DoFunctionality()
Else
DoTheUsusal()
Is there a better way or a better design to implement it? I would like to keep the solution as simple as possible, but on the other hand, this solution is really ugly and will eventually make my code looks like spaghetti code.
Your thoughts will be appreciated,
I'm using c# with sql server, web api for web services.
Edit:
I want to say that I appreciate the time and effort of everyone answering my question, there were some really interesting ideas that you brought up.
I eventually marked #dasblinkenlight answer since it suited by need the best, though other answers here are really good and may be useful to others.
Thank you.
If you have two classes that implement the same interface, your application can call the functionality (methods, properties) of the class without knowing exactly if it is calling the basic functionality or the alternative functionality:
IFunctionalityX {
DoIt();
}
class BasicFunctionalityX: IFunctionalityX {
public DoIt() {
// Default behaviour goes here
}
}
class PluginFunctionalityX: IFunctionalityX {
public DoIt() {
// Alternative functionality.
}
}
If PluginFunctionalityX shares parts of its implementation with BasicFunctionalityX, you may inherit it from the other, but whether you do or not doesn't really matter. As long as you use the interface, that is what counts, and you can use this method regardless of whether the classes are related or not.
In the initialization of your program, you can make the decision once and create an instance of the right class. You may store this class in some container that holds all your functionalities. FunctionalityX is a property of interface IFunctionalityX, and you can make other interfaces (and properties) for other functionalities.
if (functionalityXEnabled) {
FunctionalityContainer.FunctionalityX = new PluginFunctionality();
} else {
FunctionalityContainer.FunctionalityX = new BasicFunctionality();
}
Then, in the rest of your application, you can call your functionality through:
FunctionalityContainer.FunctionalityX.DoIt();
Instead of implementing this from scratch you may use a dependancy injection library, like Unity. This also allows you to more easily get an instance of the right functionality at the time you need it without having to create them all at the start of your program, and without writing elaborate constructor code for all fucntionalities.
You want to dispatch your code differently at runtime dependent on a configuration setting. Conditionals and polymorphism are two ways of doing so.
Conditionals
At runtime, check for values using if, switch or other lookup methods. You're already doing these.
if (configFile.cloudAccount == null) {
saveFileToDisk();
} else saveFileToCloud();
Advantages
They're conditionals, you really can't avoid having to do one at some point in any nontrivial development project
Disadvantages
Doing them at every point in your application would be painful, though. So they're best combined with other strategies to minimise their use
Polymorphism
When loading your application, read through the configuration file and construct your application's components accordingly:
interface IFileSaver { /* Used to save files in your application */ }
class DiskSaver : IFileSaver { /* The default file saving class */ }
class CloudSaver : IFileSaver { /* If they've configured a cloud account */ }
// EXAMPLE USE
int Main (...) {
// Setup your application, load a config file.
// You'll need to check the config with a conditional
// here (uh oh) but other components of your application
// will just use the IFileSaver interface
if (configFile.cloudAccount != null) {
YourApplication.FileSaver = new CloudSaver(configFile.cloudAccount);
} else {
YourApplication.FileSaver = new DiskSaver();
}
}
// Somewhere else in your application
void SaveCurrentDocument() {
// No if's needed, it was front loaded when initialising
// the application
YourApplication.FileSaver.Save();
}
Advantages
Fits in nicely with object-oriented design
All your configuration checks are front loaded. After loading in the correct classes the rest of your program will use them, oblivious to their actual implementation. Because of that, you don't need to do if checks throughout your code.
Compiler will be able to statically check type errors in your approach
Disadvantages
Only as flexible as your class's interface. Maybe you want some extra steps and checks to occur with a CloudSaver, they'd better fit into the pre-existing interface; otherwise, they won't happen.
Long story short - conditionals let you explicitly perform the checks whenever they're needed so, in principle, you get a lot of procedural flexibility. For example, maybe the SaveAs routine needs to save files slightly differently than the Save routine. However, as you've identified, this leads to long repetitive code. In those cases, structuring your code to use polymorphism might help out.
Either way, you will almost certainly need to have some amount of conditional checks wherever there is flexibility in your application.
Note: There are many other ways of achieving runtime config checks, I'm just pointing out the most common (and usually straightforward)
A once-popular quip among OO programmers has been that every conditional in the code indicate a missed opportunity to subclass. Although this rule is far from being universal, and it falls short when it comes to composition, there is a grain of truth to it, especially when you see the same condition popping up in multiple ifs across different methods of the same class.
A common way of dealing with ifs like that is using some combination of inheritance and composition, and moving the decision to a single place where your object is being created.
The inheritance way looks like this:
interface Doer {
void doSomething();
}
class BasicDoer implements Doer {
public void doSomething() {
...
}
}
class EnhancedDoer extends BasicDoer {
public void doSomething() {
base.doSomething();
...
}
}
// At construction time:
Doer doer;
if (someCondition)
doer = new BasicDoer();
else
doer = new EnhancedDoer();
The composition way looks like this:
interface Doer {
void doSomething();
}
// Create several implementations of Activity, then...
// At construction time:
List<Doer> doers = new ArrayList<>();
if (someCondition1)
doers.add(new SomeKindOfDoer());
if (someCondition2)
doers.add(new AnotherKindOfDoer());
if (someCondition3)
doers.add(new YetAnotherKindOfDoer());
Now instead of an if you do this:
for (Doer d : doers) {
d.doSomething();
}
If it's just a single condition then you have no choice but to use if else and is perfect for single conditions.
If you have more then 1 condition, you may think of using Switch statement.
As far as you are worried about your code going to look complicated with if else statement, put your code within functions,
if(condition)
{
DoThis();
}
else
{
DoSomethingElse();
}
Maybe something similar to strategy design pattern (incapsulation of behaviour) will make it more managable if functionality doesn't require lots of interaction with object data (though interaction is possible). Pros: readable extendable code, cons: lots of code.
namespace SomethingLikeStrategy
{
public interface Behaviour {
void doThis();
void changeM(ref int m);
void doThat();
}
public class BehaviourOriginal : Behaviour {
public void doThis() {
Console.WriteLine("foo");
}
public void changeM(ref int m) {
m = 20;
}
public void doThat() {
throw new Exception("not implemented");
}
}
public class BehaviourSpecial : Behaviour {
public void doThis() {
Console.WriteLine("bar");
}
public void changeM(ref int m) {
m = 10;
}
public void doThat() {
throw new Exception("not implemented");
}
}
public class MyClass {
Behaviour mBehaviour;
int mM = 0;
public MyClass() {
mBehaviour = new BehaviourOriginal();
}
public void setSpecialBehaviour(bool special) {
if (special) {
mBehaviour = new BehaviourSpecial();
} else {
mBehaviour = new BehaviourOriginal();
}
}
public void doThis() {
mBehaviour.doThis();
}
public void doThat() {
mBehaviour.doThat();
}
public void changeM() {
mBehaviour.changeM(ref mM);
}
public void printM() {
Console.WriteLine(mM);
}
}
class Program
{
public static void Main(string[] args)
{
MyClass myClass = new MyClass();
myClass.doThis();
myClass.setSpecialBehaviour(true);
myClass.doThis();
myClass.setSpecialBehaviour(false);
myClass.printM();
myClass.changeM();
myClass.printM();
myClass.setSpecialBehaviour(true);
myClass.changeM();
myClass.printM();
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}

Single-use object: yea or nay?

I'm thinking about creating some classes along a "single-use" design pattern, defined by the following features:
Instances are used for performing some task.
An instance will execute the task only once. Trying to call the execute method twice will raise an exception.
Properties can be modified before the execute method is called. Calling them afterward will also raise an exception.
A minimalist implementation might look like:
public class Worker
{
private bool _executed = false;
private object _someProperty;
public object SomeProperty
{
get { return _someProperty; }
set
{
ThrowIfExecuted();
_someProperty = value;
}
}
public void Execute()
{
ThrowIfExecuted();
_executed = true;
// do work. . .
}
private void CheckNotExcecuted()
{
if(_executed) throw new InvalidOperationException();
}
}
Questions:
Is there a name for this?
Pattern or anti-pattern?
This looks like a form of a balking pattern.
If it appears logical for your specific object to behave in this way, I don't see a problem with it.
Streams behave in somewhat similar way (also their use Dispose/Close to lock them for most operations). So it is not exactly surprising pattern.

OO design issue

I have a class which represents a step in a registration process. I have certain things that I want the step to perform when a user clicks save after filling out the step and then other things that I want the step to do when we are at the end of the registration process and save is invoked on the step at that stage. I have decided to use the idea of having a state but it seems to have a bad code smell about it. Any comments on how to improve this design?
public class Step1
{
public Enum State
{
InProcess = 1,
EndProcess
}
private State processState;
public Step1(State currentState)
{
processState = currentState;
}
public bool IsValid()
{
bool result;
if(processState = State.InProcess)
{
result = PerformCheck1();
}
else if(processState = State.EndProcess)
{
result = PerformCheck2();
result = PerformCheck3();
}
else
{
throw new Exception("Cannot determine process state");
}
return result;
}
public void Save()
{
if(processState = State.InProcess)
{
DoThing1();
}
else if(processState = State.EndProcess)
{
DoThing2();
DoThing3();
DoThing4();
}
else
{
throw new Exception("Cannot determine process state");
}
}
}
Disregarding other issues with the code, if you go with this design you are going to wind up with a single monolithic class for Step. I would create a IStep interface and make each step its own class:
public interface IStep
{
bool IsValid { get; }
void Save();
}
public class BeginStep : IStep
{
public bool IsValid
{
get
{
return PerformCheck1();
}
}
public void Save()
{
DoThing1();
}
}
public class EndStep : IStep
{
public bool IsValid
{
get
{
// Skipped PerformCheck2() since the result is directly overwritten
return PerformCheck3();
}
}
public void Save()
{
DoThing2();
DoThing3();
DoThing4();
}
}
If I undersdand your answer (+ your comment on Justin's answer) correctly, each step can be in a "processing" and a "completed" state and depending on which state it is in, you want to call different Save() and IsValid() methods.
Furthermore, every step is automatically "completed" once you reach the final step.
From the code you posted, it doesn't seem as if a step needs to know in which state he currently is. You just want to perform different actions depending on whether or not you are on the final page.
Is there a reason why you don't want to create specific methods that encapsulate the "completed" logic (e.g. SaveCompleted() and IsValidCompleted())?
I don't see why the Step class should decide which code to execute, since the decision is made outside the step, where you keep track of the active step.
"Magic methods" that automatically do the right thing based on some hidden state that can be modified from outside often lead to inconsistency, unexpected problems and long debugging sessions.
I would advise you to create an interface as Justin suggested, with 2 additional methods that contain the "completed" code. (There are many ways to achieve the same, like using an abstract base class instead (with the possible advantage that the "completed" methods can default to the "processing" methods) or a separate interface (to only expose the "completed" methods to the final page, without enabling it to call the regualr methods) etc. etc.)
As an addition to Justin’s answer, here is a Wikipedia link to Finite-state machine, as what you are trying to create is a Finite-state machine. The link gives theoretical background knowledge on the theme. If your registration process becomes more complicated, a State/Event table as mentioned in the article will help to formulate the flow of events.

How to use moq to test code that calls protected helpers

I currently run tests that look like the following:
// In Blah.cs
public class ClassUnderTest
{
public bool MethodUnderTest()
{
// Do a bunch of stuff...
return HelperMethod();
}
protected virtual bool HelperMethod()
{
bool success = false;
// Proprietary Hardware Access.
// Database Calls.
// File System Modifications.
return success;
}
}
// In TestBlah.cs
public class TestStub : ClassUnderTest
{
public bool HelperMethodReturnValue;
protected override bool HelperMethod()
{
return HelperMethodReturnValue;
}
}
[TestClass]
public class TestingClass
{
[TestMethod]
public void ClassUnderTest_MethodUnderTest_TestHelperReturnsTrue()
{
var stub = new TestStub();
stub.HelperMethodReturnValue = true;
Assert.IsTrue(stub.MethodUnderTest());
}
[TestMethod]
public void ClassUnderTest_MethodUnderTest_TestHelperReturnsFalse()
{
var stub = new TestStub();
stub.HelperMethodReturnValue = false;
Assert.IsFalse(stub.MethodUnderTest());
}
}
The above looks fine for simple things, however the stub class gets exponentially bigger and more complex quickly.
I'd like to replace the stub class using Moq. However this won't compile because for some reason I can't set a return value on a protected method.
[TestMethod]
public void ClassUnderTest_MethodUnderTest_TestHelperReturnsFalse()
{
var mockClass = new Mock<ClassUnderTest>();
mockClass.Protected().Setup("HelperMethod").Returns(false);
Assert.IsFalse(mockClass.Object.MethodUnderTest());
}
Anyone know how I'd go about doing this? Can I do this with moq?
Looking at the moq source code I'd guess you need to explicitly call the generic version of Setup. The non-generic version seems to be used for void methods. So try
mockClass.Protected().Setup<bool>("HelperMethod").Returns(false);
Beside this, I'd recommend re-thinking your class design. If HelperMethod() is doing such a bunch of things it would be worth its own class that is injected as a dependency into ClassUnderTest. Testing a mock object, instead of using a mock object to test something "real", is not what mocking frameworks are made for (not in the first place, at least).
Protected methods are not a great way of isolating dependencies, but it does sometimes come up, particularly when adapting legacy code for testability. One option that avoids the awkward string-based Moq syntax is to make the method 'protected internal' (or just 'internal' if you don't intend to override it in normal usage from other assemblies.) You then use InternalsVisibleTo on the assembly to expose the method. This is a bit of a hack, but using a protected method for this purpose is already a bit of a hack. In some ways I prefer the 'internal' approach, as it makes it clear that this is a backdoor method that you're not supposed to use (except for testing), as opposed to a protected method that you might expect to override in normal usage.

Categories