Skip to content

Instantly share code, notes, and snippets.

@rhwy
Last active March 11, 2020 22:51
Show Gist options
  • Save rhwy/2c9b2f29aefe4a9773ee0ff8176e6690 to your computer and use it in GitHub Desktop.
Save rhwy/2c9b2f29aefe4a9773ee0ff8176e6690 to your computer and use it in GitHub Desktop.
Refactored version of SmartHelloWorld.
public class Application
{
IOutput output;
public Application(IOutput output)
{
this.output = output;
}
public void Run(string name)
{
if (ApplicationTime.Now.Hour >= 6 && ApplicationTime.Now.Hour < 12 )
{
output.Send($"Good morning {name}"); return;
} else if (ApplicationTime.Now.Hour >= 12 && ApplicationTime.Now.Hour < 20)
{—
output.Send($"Good afternood {name}"); return;
}
output.Send($"Good night {name}");
}
}
public class ApplicationTime
{
public static Func<DateTime> SetNow {get; set;} = () => DateTime.Now;
//private Func<DateTime>
public static DateTime Now => SetNow();
}
public interface IOutput
{
void Send(string message);
}
public class ConsoleOutput : IOutput
{
public void Send(string message) => Console.WriteLine(message);
}
public static void Main(string[] args)
{
var name = args.Length > 0 ? args[0] : "World";
var app = new Application(new ConsoleOutput());
app.Run(name);
}
public class HelloTests
{
Func<StringWriter> GetWriterAndSetConsole = ()=>
{
var writer = new StringWriter();
Console.SetOut(writer);
Console.SetError(writer);
return writer;
};
[Fact]
public void GoldenMaster_with_all_defaults()
{
ApplicationTime.SetNow = () => DateTime.Now;
using var writer = GetWriterAndSetConsole();
Program.Main(new string[]{});
var sut = writer.ToString();
Check.That(sut).IsEqualTo($"Good afternood World{Environment.NewLine}");
}
[Fact]
public void refactored_should_return_morning_in_the_morning_with_defaults()
{
ApplicationTime.SetNow = () => new DateTime(2020,03,10,10,00,00);
using var writer = GetWriterAndSetConsole();
Program.Main(new string[]{});
var sut = writer.ToString();
Check.That(sut).IsEqualTo($"Good morning World{Environment.NewLine}");
}
[Fact]
public void refactored_should_return_morning_in_the_morning_with_name()
{
ApplicationTime.SetNow = () => new DateTime(2020,03,10,10,00,00);
var output = new InmemoryOutput();
var app = new Application(output);
app.Run("toto");
var result = output.Value;
Check.That(result).IsEqualTo("Good morning toto");
}
}
public class InmemoryOutput : IOutput
{
private string output = "";
public string Value => output;
public void Send(string message)
{
output += message;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment