Per this answer, I would like to know how to mock a StringBuilder class. The way they are mocking the Console class is brilliant:
You need an interface defining your dependency:
public interface IConsoleService
{
string ReadLine();
void WriteLine(string message);
}
You create a default implementation for it:
public class ConsoleService : IConsoleService
{
public string ReadLine()
{
return Console.ReadLine();
}
public void WriteLine(string message)
{
Console.WriteLine(message);
}
}
What would be the approach to mocking the StringBuilder.Append method?
So far what I have is this:
public interface IStringBuilderService
{
string Append(string line);
StringBuilder s
}
public class StringBuilderService : IStringBuilderService
{
public string Append(string line)
{
return this.ToString() += line;
}
}
Even though, there is rarely a need to mock StringBuilder, I'll assume you need it for trial purpose.. so here is one possible way to mock it.
Your default implementation class needs to wrap an instance of StringBuilder.
public interface IStringBuilderService
{
IStringBuilderService Append(string line); // mimic the StringBuilder Append signature
StringBuilder S { get; }
}
public class StringBuilderService : IStringBuilderService
{
private StringBuilder _actualStringBuilder;
public StringBuilder S
{
get { return _actualStringBuilder; }
}
public StringBuilderService() // you could also take in a parameter if you wish to initialize the variable
{
_actualStringBuilder = new StringBuilder();
}
public IStringBuilderService Append(string line)
{
_actualStringBuilder.Append(line);
return this;
}
public override string ToString()
{
return _actualStringBuilder.ToString();
}
}
The reason we need an instance of StringBuilder wrapped up in the concrete class is because Console is a static resource, and hence accessed without an instance variable requirement. StringBuilder will be per instance, and hence we need a variable encapsulating that.
Once you have this interface, you can use this interface wherever StringBuilder manipulation is required.
And for your tests, you could use a mock of this interface.
Related
I've read other threads and Eric Lippert's posts on the subject, but haven't seen this exact situation addressed anywhere.
C# optional parameters on overridden methods
Optional parameters and inheritance
I'm trying to implement the following situation:
public class BaseClass
{//ignore rest of class for now
public void DoThings(String str)
{
//dostuff
}
}
public class DerivedClass: BaseClass
{//ignore rest of class for now
new public void DoThings(String str, Int32 someint = 1)
{
//dostuff but including someint, calls base:DoThings in here
}
}
When I do this the compiler gives me the warning in the subject line that I do not need to use the new keyword because the method does not hide the inherited method. However I do not see a way to call the base method from the object instance, so it looks hidden to me.
I want it to actually be hidden. If it is not hidden, there is potential for some other user to some day call the base method directly and break the class (it involves thread safety).
My question is, does the new method actually hide the inherited method (compiler is wrong?) or is the compiler correct and I need to do something else to hide the original method? Or is it just not possible to achieve the desired outcome?
void DoThings(String str) accepts a single parameter
void DoThings(String str, Int32 someint = 1) accepts two parameters
=> the methods are distinct, unrelated methods, which incidentally share the name.
Default parameters are inserted at the call-sites during compilation.
Here is one possible solution:
public class BaseClass
{
public virtual void DoThings(String str)
{
//dostuff
}
}
public class DerivedClass: BaseClass
{
public override void DoThings(String str)
{
DoThings(str, 1); // delegate with default param
}
public void DoThings(String str, Int32 someint)
{
//dostuff
}
}
Note that new makes it possible to call base classes' virtual methods in the first place by having a reference with static type of the base class (e.g. by casting it to the base class):
public class Test
{
public static void Main()
{
var obj = new DerivedClass();
BaseClass baseObj = obj;
obj.DoThings("a");
baseObj.DoThings("b");
((BaseClass)obj).DoThings("c");
}
}
class BaseClass
{
public void DoThings(String str)
{
Console.WriteLine("base: " + str);
}
}
class DerivedClass: BaseClass
{
new public void DoThings(String str, Int32 someint = 1)
{
Console.WriteLine("derived: " + str);
base.DoThings(str);
}
}
Output:
derived: a
base: a
base: b
base: c
If you want callers to never call the overridden method of a base class, mark it virtual and override it (like already shown at the top of this answer):
public class Test
{
public static void Main()
{
var obj = new DerivedClass();
BaseClass baseObj = obj;
obj.DoThings("a");
baseObj.DoThings("b");
((BaseClass)obj).DoThings("c");
}
}
class BaseClass
{
public virtual void DoThings(String str)
{
Console.WriteLine("base: " + str);
}
}
class DerivedClass: BaseClass
{
// "hide" (override) your base method:
public override void DoThings(String str)
{
// delegate to method with default param:
this.DoThings(str);
}
public void DoThings(String str, Int32 someint = 1)
{
Console.WriteLine("derived: " + str);
base.DoThings(str);
}
}
Output:
derived: a
base: a
derived: b
base: b
derived: c
base: c
After discussion in the comments: you do not want to use inheratince here, but rather opt for compisition.
The code could look like the following:
public class Test
{
public static void Main()
{
var obj = new DerivedClass(new BaseClass());
obj.DoThings("a");
// baseObj.DoThings("b"); // not accessible
// ((BaseClass)obj).DoThings("c"); // InvalidCastException!
}
}
class BaseClass
{
public void DoThings(String str)
{
Console.WriteLine("base: " + str);
}
}
class Wrapper
{
private BaseClass original;
public Wrapper(BaseClass original) {
this.original = original;
}
public void DoThings(String str, Int32 someint = 1)
{
Console.WriteLine("wrapped: " + str);
original.DoThings(str);
}
}
Output:
base: a
wrapped: a
the 'new' keyword can't be used where you used it
To hide the member:
public class BaseClass
{ // ignore rest of class for now
public virtual void DoThings(String str)
{
// dostuff
}
}
public class DerivedClass: BaseClass
{ //ignore rest of class for now
public override void DoThings(String str)
{
// dostuff
}
public void DoThings(String str, Int32 someint = 1)
{
// do stuff but including some int, calls base:DoThings in here
}
}
//Program.cs
public interface TestVal
{
//Input Param
string Input { get; }
//will return output
TestValRes ValidateRe(string input);
}
class MyClass : ITestVal
{
static void Main(string[] args)
{
var instance = new MyClass();
instance.Run();
}
public void Run()
{
ValidateRe("test");
}
public ITestValRes ValidateRe(string input)
{
return null; // return an instance of a class implementing ITestValRes here.
}
}
//TestvalRes.cs
public interface TestvalRes
{
string Input { get; }
bool IsValid { get; }
}
So I just want to pass a string to the TestVal, do validation and call TestvalRes to return whether it is Valid or not, and if Invalid, why? So the validation will be done in the first public interface - TestVal, however I still need to call it inside the Main(), right?
First off, I'd recommend following C# naming conventions and name your interfaces ITestVal and ITestValRes respectively.
Next, static method cannot call instance methods in the same class (without creating an instance and using that). You need to create an instance of the class and pass control of the application flow to that:
class MyClass : ITestVal
{
static void Main(string[] args)
{
var instance = new MyClass();
instance.Run();
}
public void Run()
{
ValidateRe("test");
}
public ITestValRes ValidateRe(string input)
{
return null; // return an instance of a class implementing ITestValRes here.
}
}
I have created a class like this.
public class SimpleClass
{
public string myProp { get; set; }
public SimpleClass()
{
this.myProp = "";
}
public SimpleClass Method1()
{
this.myProp += "Method1";
return this;
}
public SimpleClass Method2()
{
this.myProp += "Method2";
return this;
}
public string GetProp()
{
return this.myProp;
}
}
I'm using it like this.
public class Worker
{
public Worker()
{
string Output = new SimpleClass().Method1().Method2().GetProp();
}
}
All functions return the container class and last method returns result.
I'm curious about this performance, is it bad thing to use methods like for performance or good?
Should i use it like that or could you suggesst another way.
Thanks
some suggestion :
how should user know First Call method1 then Method2 and finally GetProp()?
It's better to encapsulate your methods and hide all Complexity. For example User just call GetProp() and in GetProp() you can Do what you want .
your exmple can change like below :
public class SimpleClass
{
public string myProp { get; set; }
public SimpleClass()
{
this.myProp = "";
}
private string Method1()
{
this.myProp += "Method1";
return Method2();
}
private string Method2()
{
return this.myProp += "Method2";
}
public string GetProp()
{
Method1();
return this.myProp;
}
}
Finally call your Prop() Method like :
SimpleClass simple = new SimpleClass();
string Output = simple.GetProp();
And Another suggestion to have better Design is Make Your Mathod1 and Method2 as Private.
I think that you are reinventing the wheel in wrong way. you are probably looking for StringBuilder which does exactly same thing.
var builder = new StringBuilder();
var result = builder.Append("something").Append("something else").ToString();
but if you still want to have dedicated class to provide meaningful methods instead of just Append and also provide some abstraction over arguments being passed you can do this.
public class SimpleClass
{
private readonly StringBuilder _builder = new StringBuilder();
public SimpleClass Method1()
{
_builder.Append("Method1");
return this;
}
public SimpleClass Method2()
{
_builder.Append("Method2");
return this;
}
public string GetProp()
{
return _builder.ToString();
}
}
Note that using StringBuilder is efficient way of appending strings together. for small number of appends it may not show difference, but for large number of appends it will be faster and produces less garbage.
Hey I have two classes
class Main
{
public exLog exLog;
public Main()
{
}
}
and
class exLog
{
public exLog()
{
}
public exLog(String where)
{
}
public exLog(String where, String message)
{
}
}
i tried to call exLog direct without giving exLog a parameter. So I can call any class with the Main Method.
How should I do that?
public String ReadFileString(String fileType, String fileSaveLocation)
{
try
{
return "";
}
catch (Exception)
{
newMain.exLog("", "");
return null;
}
}
I like to call them like a funtion in Main
You can call it as soon as you instantiate it.
public Main()
{
exLog = new exLog();
exLog.MethodInClass();
}
Also, if you are not in the same assembly you'll need to make exLog public.
Finally, this is C# and the style dictates that class names should be PascalCased. It's a good habit to form.
Methinks you want something like Adapter Pattern
class Main
{
private exLog exLog;
public Main()
{
}
public void ExLog()
{
exLog = new exLog();
}
public void ExLog(String where)
{
exLog = new exLog(where);
}
public void ExLog(String where, String message)
{
exLog = new exLog(where, message);
}
}
I think you're confused about classes, instances, constructors, and methods. This does not work:
newMain.exLog("", "");
because exLog in this case is a property, not a method. (It's confusing because you use the same name for the class and the property, which is why most conventions discourage that).
You can call a method on the instance:
newMain.exLog.Log("", "");
but then you'll need to change the names of the methods (and add a return type) in your exLog class so they don't get interpreted as constructors:
class exLog
{
public void Log()
{
}
public void Log(String where)
{
}
public void Log(String where, String message)
{
}
}
class Main
{
public exLog exLog;
public Main()
{
exLog = new exLog();
exLog.ReadFileString("", "");
}
}
How to avoid a pair of repetitive lines before and after invocations in sample below ?
Details: This is compileable mock of what is real larger code. Generally it is a layer of proxy classes containing service clients with variety of APIs. The repetitive part is pre- and post- invocation for every method of every client. Unfortunately there is no single signature for all possible methods, the pre- and post- parts need a pointer to client's channel and context.
Is it possible to apply something advanced like AOP, Generics, Delegates, Attributes etc. ? Thank you
using System;
namespace ConsoleApplication
{
class ClassServiceClient: IDisposable
{
public Object channel()
{
return "something";
}
public Object context()
{
return "something other";
}
}
class ClassA : ClassServiceClient
{
public Object methodA()
{
return "something other";
}
}
class ClassB : ClassServiceClient
{
public void methodB(string param)
{
return;
}
}
class ClassAProxy
{
public Object methodA()
{
using (ClassA client = new ClassA())
{
Program.preparation(client.channel()); //<---- repetitive part
Object result = client.methodA();
Program.postinvocation(client.context());//<---- repetitive part
return result;
}
}
}
class ClassBProxy
{
public void methodB(string param)
{
using (ClassB client = new ClassB())
{
Program.preparation(client.channel()); //<---- repetitive part
client.methodB(param);
Program.postinvocation(client.context());//<---- repetitive part
return;
}
}
}
class Program
{
public static void preparation(Object channel)
{
// Do something with channel
}
public static void postinvocation(Object context)
{
// Do something with context
}
static void Main(string[] args)
{
}
}
}
If you can use a common base class, you can easily use a public sealed method that does the invocation and a protected abstract method that does the logic, e.g.
class ProxyBase{
public void Method(params object[] args){
PreConditions();
Invoke(args);
PostConditions();
}
protected abstract void Invoke(object[] args);
}
class ClassAProxy{
protected override void Invoke(object[] args){
client.Method(args[0]);
}
}
You can achieve similar results functionally by declaring a InvocationHandler in your Program class that takes an action:
class Program{
public static void Invoke(object[] args, Action action){
PreConditions();
action();
PostConditions();
}
}
class ClassAProxy{
public void MethodA(int i){
Program.Invoke(() => client.Something(i));
}
}