Initial commit

This commit is contained in:
github-classroom[bot] 2024-11-08 15:45:55 +00:00 committed by GitHub
commit 2b1ce9b58f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 5065 additions and 0 deletions

3551
.editorconfig Normal file

File diff suppressed because it is too large Load diff

583
.gitignore vendored Normal file
View file

@ -0,0 +1,583 @@
# Created by https://www.toptal.com/developers/gitignore/api/csharp,visualstudio
# Edit at https://www.toptal.com/developers/gitignore?templates=csharp,visualstudio
### Csharp ###
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
### VisualStudio ###
# User-specific files
# User-specific files (MonoDevelop/Xamarin Studio)
# Mono auto generated files
# Build results
# Visual Studio 2015/2017 cache/options directory
# Uncomment if you have tasks that create the project's static files in wwwroot
# Visual Studio 2017 auto generated files
# MSTest test Results
# NUnit
# Build Results of an ATL Project
# Benchmark Results
# .NET Core
# ASP.NET Scaffolding
# StyleCop
# Files built by Visual Studio
# Chutzpah Test files
# Visual C++ cache files
# Visual Studio profiler
# Visual Studio Trace Files
# TFS 2012 Local Workspace
# Guidance Automation Toolkit
# ReSharper is a .NET coding add-in
# TeamCity is a build add-in
# DotCover is a Code Coverage Tool
# AxoCover is a Code Coverage Tool
# Coverlet is a free, cross platform Code Coverage Tool
# Visual Studio code coverage results
# NCrunch
# MightyMoose
# Web workbench (sass)
# Installshield output folder
# DocProject is a documentation generator add-in
# Click-Once directory
# Publish Web Output
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
# NuGet Packages
# NuGet Symbol Packages
# The packages folder can be ignored because of Package Restore
# except build/, which is used as an MSBuild target.
# Uncomment if necessary however generally it will be regenerated when needed
# NuGet v3's project.json files produces more ignorable files
# Microsoft Azure Build Output
# Microsoft Azure Emulator
# Windows Store app package directories and files
# Visual Studio cache files
# files ending in .cache can be ignored
# but keep track of directories ending in .cache
# Others
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
# RIA/Silverlight projects
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
# SQL Server files
# Business Intelligence projects
# Microsoft Fakes
# GhostDoc plugin setting file
# Node.js Tools for Visual Studio
# Visual Studio 6 build log
# Visual Studio 6 workspace options file
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
# Visual Studio 6 technical files
# Visual Studio LightSwitch build output
# Paket dependency manager
# FAKE - F# Make
# CodeRush personal settings
# Python Tools for Visual Studio (PTVS)
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
# Telerik's JustMock configuration file
# BizTalk build output
# OpenCover UI analysis results
# Azure Stream Analytics local run output
# MSBuild Binary and Structured Log
# NVidia Nsight GPU debugger configuration file
# MFractors (Xamarin productivity tool) working folder
# Local History for Visual Studio
# Visual Studio History (VSHistory) files
# BeatPulse healthcheck temp database
# Backup folder for Package Reference Convert tool in Visual Studio 2017
# Ionide (cross platform F# VS Code tools) working folder
# Fody - auto-generated XML schema
# VS Code files for those working on multiple tools
# Local History for Visual Studio Code
# Windows Installer files from build outputs
# JetBrains Rider
### VisualStudio Patch ###
# Additional files built by Visual Studio
# End of https://www.toptal.com/developers/gitignore/api/csharp,visualstudio

View file

@ -0,0 +1,308 @@
using FluentAssertions;
using Xunit;
namespace CoffeeVendingMachines.Test;
public sealed class CoffeeVendingMachineTests
{
private const string Location = "Room 204a";
[Fact]
public void Construction_Default()
{
var machine = new CoffeeVendingMachine(Location);
machine.Location.Should()
.NotBeNullOrWhiteSpace()
.And.Be(Location);
machine.TotalMoneyCurrentlyInput
.Should().Be(0, "no coins have been inserted yet");
machine.TotalChangeAmountInMachine
.Should().Be(1155, "three pieces of each coin are the default set");
machine.AvailableProducts.Should()
.NotBeNullOrEmpty()
.And.HaveCount(3)
.And.BeEquivalentTo(new Product[]
{
new("Cappuccino", 85, 10),
new("Mocca", 100, 10),
new("Cacao", 60, 10)
}, "those three products are created by default if none are passed to the ctor");
}
[Fact]
public void Construction_Full()
{
Product[] products = GetDefaultProducts();
var machine = new CoffeeVendingMachine(GetDefaultCoinDepots(),
products, Location);
machine.Location.Should()
.NotBeNullOrWhiteSpace()
.And.Be(Location);
machine.TotalMoneyCurrentlyInput
.Should().Be(0, "no coins have been inserted yet");
machine.TotalChangeAmountInMachine
.Should().Be(1385, "sum of coin depot values");
machine.AvailableProducts.Should()
.NotBeNullOrEmpty()
.And.HaveCount(products.Length)
.And.BeEquivalentTo(products);
}
[Fact]
public void InsertCoin_Simple()
{
var machine = GetDefaultMachine();
machine.TotalMoneyCurrentlyInput.Should().Be(0);
machine.InsertCoin(CoinType.Cent20).Should().BeTrue();
machine.TotalMoneyCurrentlyInput.Should().Be(20);
}
[Fact]
public void InsertCoin_Multiple()
{
var machine = GetDefaultMachine();
machine.TotalMoneyCurrentlyInput.Should().Be(0);
machine.InsertCoin(CoinType.Cent20).Should().BeTrue();
machine.InsertCoin(CoinType.Cent50).Should().BeTrue();
machine.InsertCoin(CoinType.Cent50).Should().BeTrue();
machine.InsertCoin(CoinType.Euro02).Should().BeTrue();
machine.TotalMoneyCurrentlyInput.Should().Be(320, "20 + 2x50 + 200");
}
[Fact]
public void Cancel_Simple()
{
var machine = new CoffeeVendingMachine(Location);
Insert(CoinType.Cent10, 2);
Insert(CoinType.Cent20, 1);
Insert(CoinType.Cent50, 3);
Insert(CoinType.Euro01, 1);
machine.Cancel().Should().NotBeNull()
.And.HaveCount(4,
"only four kinds of coins have been inserted, the other two input depots were empty")
.And.BeEquivalentTo(new CoinDepot[]
{
new(CoinType.Cent10, 2),
new(CoinType.Cent20, 1),
new(CoinType.Cent50, 3),
new(CoinType.Euro01, 1)
});
return;
void Insert(CoinType coin, int times)
{
for (var i = 0; i < times; i++)
{
machine.InsertCoin(coin);
}
}
}
[Fact]
public void Cancel_Empty()
{
var machine = new CoffeeVendingMachine(Location);
machine.Cancel().Should().NotBeNull()
.And.BeEmpty("no coins have been inserted");
}
[Fact]
public void SelectProduct_Simple()
{
var machine = GetDefaultMachine();
machine.InsertCoin(CoinType.Euro01);
machine.SelectProduct("Coffee1", out CoinDepot[]? change, out int? losses)
.Should().BeTrue("enough money inserted, product exists and is in stock");
change.Should().NotBeNullOrEmpty("selected product less than money inserted, change returned")
.And.HaveCount(1, "change money returned in as few coins as possible and 10 cent coin available")
.And.BeEquivalentTo(new[] { new CoinDepot(CoinType.Cent10, 1) });
losses.Should().BeNull("change could be returned in total");
machine.TotalMoneyCurrentlyInput.Should().Be(0, "product bought, change returned");
machine.TotalChangeAmountInMachine.Should().Be(1475, "1385 + 100 - 10");
machine.AvailableProducts[2].NumberSold.Should().Be(1, "sale registered in product");
}
[Fact]
public void SelectProduct_ProductNotExists()
{
var machine = GetDefaultMachine();
machine.InsertCoin(CoinType.Euro02);
machine.SelectProduct("Potato Salad", out CoinDepot[]? change, out int? losses)
.Should().BeFalse("product does not exist");
change.Should().BeNull("no change return triggered");
losses.Should().BeNull("no change return triggered");
machine.TotalMoneyCurrentlyInput.Should().Be(200, "input unchanged");
machine.TotalChangeAmountInMachine.Should().Be(1385, "change money unchanged");
}
[Fact]
public void SelectProduct_NotEnoughMoney()
{
var machine = GetDefaultMachine();
machine.InsertCoin(CoinType.Cent50);
machine.SelectProduct("Milk", out CoinDepot[]? change, out int? losses)
.Should().BeFalse("product costs more than input");
change.Should().BeNull("no change return triggered");
losses.Should().BeNull("no change return triggered");
machine.TotalMoneyCurrentlyInput.Should().Be(50, "input unchanged");
machine.TotalChangeAmountInMachine.Should().Be(1385, "change money unchanged");
}
[Fact]
public void SelectProduct_ProductOutOfStock()
{
var machine = new CoffeeVendingMachine(GetDefaultCoinDepots(),
new Product[] { new("Soup", 80, 0) }, Location);
machine.InsertCoin(CoinType.Euro01);
machine.SelectProduct("Soup", out CoinDepot[]? change, out int? losses)
.Should().BeFalse("product is out of stock");
change.Should().BeNull("no change return triggered");
losses.Should().BeNull("no change return triggered");
machine.TotalMoneyCurrentlyInput.Should().Be(100, "input unchanged");
machine.TotalChangeAmountInMachine.Should().Be(1385, "change money unchanged");
}
[Fact]
public void SelectProduct_ProductGoingOutOfStock()
{
var machine = new CoffeeVendingMachine(GetDefaultCoinDepots(),
new Product[] { new("Soup", 80, 1) }, Location);
machine.InsertCoin(CoinType.Euro01);
machine.SelectProduct("Soup", out _, out _).Should().BeTrue();
machine.AvailableProducts.Should().BeEmpty("we had one product and that got sold");
}
[Fact]
public void SelectProduct_NotEnoughChange()
{
var machine = new CoffeeVendingMachine([
new CoinDepot(CoinType.Cent05),
new CoinDepot(CoinType.Cent10),
new CoinDepot(CoinType.Cent20),
new CoinDepot(CoinType.Cent50, 1),
new CoinDepot(CoinType.Euro01),
new CoinDepot(CoinType.Euro02)
],
GetDefaultProducts(), Location);
machine.InsertCoin(CoinType.Euro01);
machine.InsertCoin(CoinType.Euro02);
machine.SelectProduct("Soup", out CoinDepot[]? change, out int? losses)
.Should().BeTrue("product is in stock and customer inserted enough money");
change.Should()
.NotBeNull("customer entered more money than required so we return change")
.And.HaveCount(1, "we only have a single 50 cent coin")
.And.BeEquivalentTo(new[] { new CoinDepot(CoinType.Cent50, 1) });
losses.Should()
.NotBeNull("we are unable to return the full change of 70 cents")
.And.Be(20, "customer looses 20 cents which we are unable to return");
machine.TotalMoneyCurrentlyInput.Should().Be(0, "user input transferred to change depots");
machine.TotalChangeAmountInMachine.Should().Be(300,
"we were unable to return all the change but we kept all the input as future change money");
}
[Fact]
public void SelectProduct_InputAsChange()
{
var machine = new CoffeeVendingMachine(new CoinDepot[]
{
new(CoinType.Cent05),
new(CoinType.Cent10),
new(CoinType.Cent20),
new(CoinType.Cent50, 1),
new(CoinType.Euro01),
new(CoinType.Euro02)
},
GetDefaultProducts(), Location);
machine.InsertCoin(CoinType.Cent10);
machine.InsertCoin(CoinType.Cent05);
machine.InsertCoin(CoinType.Cent05);
machine.InsertCoin(CoinType.Cent20);
machine.InsertCoin(CoinType.Euro02);
machine.SelectProduct("Soup", out CoinDepot[]? change, out int? losses)
.Should().BeTrue("product is in stock and customer inserted enough money");
change.Should()
.NotBeNull("customer entered more money than required so we return change")
.And.HaveCount(1, "we return a 10 cent coin")
.And.BeEquivalentTo(new CoinDepot[]
{
new(CoinType.Cent10, 1)
});
losses.Should()
.BeNull("we are able to return the full change of 10 cents");
machine.TotalMoneyCurrentlyInput.Should().Be(0, "user input transferred to change depots");
machine.TotalChangeAmountInMachine.Should().Be(280,
"we used some of the input as change, but we kept the rest as future change money");
}
[Fact]
public void StringRepresentation_Simple()
{
var machine = GetDefaultMachine();
machine.InsertCoin(CoinType.Cent50);
machine.InsertCoin(CoinType.Cent20);
machine.InsertCoin(CoinType.Cent20);
machine.InsertCoin(CoinType.Cent20);
machine.SelectProduct("Cacao", out _, out _);
machine.ToString().Should()
.NotBeNullOrWhiteSpace()
.And.Be("""
|=======================================|
|Machine located at: Room 204a |
|=======================================|
|Cent05 x5 |
|Cent10 x9 |
|Cent20 x11 |
|Cent50 x7 |
|Euro01 x4 |
|Euro02 x2 |
|=======================================|
|Milk 0,75 [4 in stock | 0 sold]|
|Soup 2,30 [2 in stock | 0 sold]|
|Coffee1 0,90 [8 in stock | 0 sold]|
|Coffee2 0,85 [8 in stock | 0 sold]|
|Cacao 1,00 [4 in stock | 1 sold]|
|=======================================|
""");
}
private static CoffeeVendingMachine GetDefaultMachine() =>
new(GetDefaultCoinDepots(),
GetDefaultProducts(), Location);
private static Product[] GetDefaultProducts() =>
[
new("Milk", 75, 4),
new("Soup", 230, 2),
new("Coffee1", 90, 8),
new("Coffee2", 85, 8),
new("Cacao", 100, 5)
];
private static CoinDepot[] GetDefaultCoinDepots() =>
[
new(CoinType.Cent05, 05),
new(CoinType.Cent10, 10),
new(CoinType.Cent20, 08),
new(CoinType.Cent50, 06),
new(CoinType.Euro01, 04),
new(CoinType.Euro02, 02)
];
}

View file

@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.12.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="6.0.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CoffeeVendingMachines\CoffeeVendingMachines.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,114 @@
using FluentAssertions;
using Xunit;
namespace CoffeeVendingMachines.Test;
public sealed class CoinDepotTests
{
private const CoinType Type = CoinType.Cent10;
private const int Count = 5;
[Fact]
public void Construction_Simple()
{
var depot = new CoinDepot(Type, Count);
depot.Coin.Should().Be(Type);
depot.Count.Should().Be(Count);
}
[Fact]
public void Construction_NoCountProvided()
{
var depot = new CoinDepot(Type);
depot.Coin.Should().Be(Type);
depot.Count.Should().Be(0, "initialized with default value");
}
[Fact]
public void Construction_Copy()
{
var depot = new CoinDepot(CoinType.Euro02, 12);
var copy = new CoinDepot(depot);
copy.Coin.Should().Be(depot.Coin);
copy.Count.Should().Be(depot.Count);
}
[Fact]
public void Add_Simple()
{
var depot = new CoinDepot(Type, Count);
depot.Add();
depot.Count.Should().Be(Count + 1);
}
[Fact]
public void Add_Multiple()
{
var depot = new CoinDepot(Type, Count);
depot.Add();
depot.Add();
depot.Count.Should().Be(Count + 2);
}
[Fact]
public void Withdraw_Simple()
{
var depot = new CoinDepot(Type, Count);
depot.Withdraw()
.Should().BeTrue("there are still coins left in the depot");
depot.Count.Should().Be(Count - 1);
}
[Fact]
public void Withdraw_Multiple()
{
var depot = new CoinDepot(Type, Count);
depot.Withdraw();
depot.Withdraw()
.Should().BeTrue("there are still coins left in the depot");
depot.Count.Should().Be(Count - 2);
}
[Fact]
public void Withdraw_NoCoins()
{
var depot = new CoinDepot(Type, 0);
depot.Withdraw()
.Should().BeFalse("no more coins left in the depot");
depot.Count.Should().Be(0, "unchanged, because withdrawal failed");
}
[Fact]
public void Clear_Simple()
{
var depot = new CoinDepot(Type, Count);
depot.Clear();
depot.Count.Should().Be(0);
}
[Fact]
public void StringRepresentation_Simple()
{
var depot = new CoinDepot(Type, Count);
depot.ToString().Should()
.NotBeNullOrWhiteSpace()
.And.Be("Cent10 x5");
}
}

View file

@ -0,0 +1,100 @@
using FluentAssertions;
using Xunit;
namespace CoffeeVendingMachines.Test;
public sealed class ProductTests
{
private const string Name = "Tea, Earl Grey, Hot";
private const int Price = 80;
private const int Stock = 6;
[Fact]
public void Construction_Simple()
{
var product = new Product(Name, Price, Stock);
product.Name.Should().Be(Name);
product.Price.Should().Be(Price, "valid price used");
product.InStock.Should().BeTrue("stock is >0");
product.NumberSold.Should().Be(0, "nothing sold yet");
}
[Fact]
public void Construction_NoStock()
{
var product = new Product(Name, Price, 0);
product.InStock.Should().BeFalse("stock 0");
}
[Fact]
public void Construction_InvalidStock()
{
var product = new Product(Name, Price, -3);
product.InStock.Should().BeFalse("stock set to 0, because invalid stock passed");
}
[Theory]
[InlineData(36, "not a multiple of 5")]
[InlineData(-5, "negative value")]
[InlineData(0, "too small value")]
public void Construction_InvalidPrice(int price, string reason)
{
var product = new Product(Name, price, Stock);
product.Price.Should().Be(Product.FallbackPrice, reason);
}
[Fact]
public void AddSale_Simple()
{
var product = new Product(Name, Price, Stock);
product.NumberSold.Should().Be(0);
product.AddSale().Should().BeTrue();
product.NumberSold.Should().Be(1);
}
[Fact]
public void AddSale_Multiple()
{
var product = new Product(Name, Price, Stock);
product.NumberSold.Should().Be(0);
for (var i = 0; i < 4; i++)
{
product.AddSale().Should().BeTrue();
}
product.NumberSold.Should().Be(4);
}
[Fact]
public void AddSale_OutOfStock()
{
var product = new Product(Name, Price, 1);
product.NumberSold.Should().Be(0);
product.AddSale().Should().BeTrue();
product.NumberSold.Should().Be(1);
product.AddSale().Should().BeFalse("out of stock");
product.NumberSold.Should().Be(1);
}
[Fact]
public void StringRepresentation_Simple()
{
var product = new Product("Tea", Price, Stock);
for (var i = 0; i < 4; i++)
{
product.AddSale();
}
product.ToString().Should()
.NotBeNullOrWhiteSpace()
.And.Be("Tea € 0,80 [2 in stock | 4 sold]");
}
}

31
CoffeeVendingMachines.sln Normal file
View file

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.3.32922.545
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CoffeeVendingMachines", "CoffeeVendingMachines\CoffeeVendingMachines.csproj", "{7D78E790-A876-4B47-B1EF-CE582EAAADB0}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CoffeeVendingMachines.Test", "CoffeeVendingMachines.Test\CoffeeVendingMachines.Test.csproj", "{E024702F-CC9C-47D6-98B4-97A5B12ADC33}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7D78E790-A876-4B47-B1EF-CE582EAAADB0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7D78E790-A876-4B47-B1EF-CE582EAAADB0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7D78E790-A876-4B47-B1EF-CE582EAAADB0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7D78E790-A876-4B47-B1EF-CE582EAAADB0}.Release|Any CPU.Build.0 = Release|Any CPU
{E024702F-CC9C-47D6-98B4-97A5B12ADC33}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E024702F-CC9C-47D6-98B4-97A5B12ADC33}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E024702F-CC9C-47D6-98B4-97A5B12ADC33}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E024702F-CC9C-47D6-98B4-97A5B12ADC33}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4BC72C42-3482-4430-85F7-6B56B062292D}
EndGlobalSection
EndGlobal

View file

@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,8 @@
using System.Globalization;
namespace CoffeeVendingMachines;
public static class Const
{
public static CultureInfo Culture => new CultureInfo("de-AT");
}

View file

@ -0,0 +1,8 @@
using System.Text;
// using CoffeeVendingMachines;
Console.OutputEncoding = Encoding.UTF8;
Console.WriteLine($"*** Coffee Slot Machine ***{Environment.NewLine}");
// TODO

BIN
pics/coffee_machine.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 830 KiB

BIN
pics/coin_dispenser.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

BIN
pics/sample_run.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

322
readme.adoc Normal file
View file

@ -0,0 +1,322 @@
:sectnums:
:nofooter:
:toc: left
:icons: font
:data-uri:
:source-highlighter: highlightjs
:stem: latexmath
= OOB.05 -- Coffee Vending Machine
The goal of this assignment is to implement a vending machine for coffee and similar beverages like we have them at school.
NOTE: Look carefully at the following diagram to better understand which state & behaviour is `readonly`, `private` etc. This will help you implement the application.
[plantuml,id=class_diagram]
----
@startuml
hide empty methods
enum CoinType
{
Cent05
Cent10
Cent20
Cent50
Euro01
Euro02
}
class Product
{
+int FallbackPrice [const]
-int _price [readonly]
-int _stock
+bool InStock [readonly]
+string Name [readonly]
+int NumberSold [private set]
+int Price [private init]
+Product(string, int, int)
+bool AddSale()
+string ToString() [override]
}
class CoinDepot
{
+CoinType Coin [readonly]
+int Count [private set]
+CoinDepot(CoinType, int [default 0])
+CoinDepot(CoinDepot)
+void Add()
+void Clear()
+string ToString() [override]
+bool Withdraw()
}
class CoffeeVendingMachine
{
{static} -CoinType[] withdrawalOrder [readonly]
-CoinDepot[] _currentChangeCoins [readonly]
-CoinDepot[] _currentInputCoins [readonly]
-Product[] _products [readonly]
+string Location [readonly]
+int TotalChangeAmountInMachine [readonly]
+int TotalMoneyCurrentlyInput [readonly]
+Product[] AvailableProducts [readonly]
+CoffeeVendingMachine(CoinDepot[], Product[], string)
+CoffeeVendingMachine(string)
+CoinDepot[] Cancel()
+bool InsertCoin(CoinType)
+bool SelectProduct(string, out CoinDepot[]?, out int?)
+string ToString() [override]
-void AddInputToChange()
{static} -CoinDepot[] CreateCoinDepots(int)
{static} -Product[] CreateDefaultProducts()
{static} -CoinDepot? GetDepotByType(CoinDepot[], CoinType)
-int? PrepareChangeCoins(int, out CoinDepot[])
{static} -int SumDepotValue(CoinDepot[])
-bool TryFindProduct(string, out Product?)
}
CoinDepot "n" -l- "1" CoinType: contains
CoinDepot "12" -- "1" CoffeeVendingMachine: has
Product "n" --r "1" CoffeeVendingMachine: offers
@enduml
----
WARNING: As usual make sure to define the contract correctly or the unit tests won't work. Also, you might have to comment tests and enable them while you go to ensure your application always compiles.
== `Product`
Represents an article which is sold by the vending machine.
For example tea or coffee.
Each product is defined by a name, has a price and also keeps track of its stock.
Requirements:
* The price has to be a multiple of 5 (cents)
** If a different price is set fall back to a price of 50 (cents)
* The stock cannot become negative
=== String Representation
A `Product` can represent itself as a `string`.
* Pattern: <name> <price> [<stock> in stock | <sales> sold]
* Example: `Cappuccino € 0,85 [9 in stock | 1 sold]`
CAUTION: To ensure uniform _locale_ formatting, make sure to use the specified `CultureInfo` available via the `Culture` property of the `Const` class
== `CoinDepot`
Each coin depot holds coins of a specific type, and one type only.
It can contain none, one or more coins -- for simplicity we do not specify an upper bound.
Imagine something like this (several depots for various coins) just inside the vending machine:
image::pics/coin_dispenser.jpg[Coin Dispenser, width=400]
Requirements:
* Each depot accepts only a single type of coin
* Coins can be added to it
* Coins can be withdrawn from it *if* there are coins left in the depot
* The depot can be emptied (cleared)
* It can copy another depot
** The new one then contains the same type and amount of coins
** => Useful for some implementation details
=== `CoinType`
Each coin belongs to a specific _type_.
This `CoinType` is implemented as an `enum`.
IMPORTANT: Use a specific property of the `enum` to 'encode' the value of the coin _within_ the type.
.Values
----
Cent05: 5
Cent10: 10
Cent20: 20
Cent50: 50
Euro01: 100
Euro02: 200
----
=== String Representation
A `CoinDepot` can represent itself as a `string`.
* Pattern: <coin type> x<count>
* Example: `Cent50 x3`
== `CoffeeVendingMachine`
A `class` which simulates (omitting _a lot_ of details) such a machine:
image::pics/coffee_machine.png[Coffee Vending Machine, width=200]
This is the major part of the application so the specifications & requirements provided to you are much more exhaustive.
You'll still have to _think_ about what you are doing to successfully complete this assignment.
=== State
* When returning change money we start with the coins with the biggest denomination.
This behaviour is the same for _all_ machines, so we can store the order of coins in a `static` field.
* The array of products is set on construction
** Each product defines its own price
** It cannot be restocked
* We have _two_ arrays of coin depots
** One for the money the customer inputs into the machine
** A second one for the change money
** _The logic could also be implemented with only one set of depots, but we'll do it with two, because that's a little easier_
* It has a location
** For example '2nd floor'
* Information that can be calculated on the fly:
** How much change money is currently in the machine
*** This does _not_ include the money input by the customer _until_ a product selection has been made
** How much money did the customer put into the machine
** Which products are currently available
=== Construction
There are two ways to create an instance of `CoffeeVendingMachine`:
. Only provide a location
** This will initialize products and change money with <<default_values,default values>>
** Will utilize the _other_ constructor to avoid code duplication
. Also provide products and initial change money values
==== Default Values [[default_values]]
Use the following default values.
* For each type of coin (there are six in total) 'load' 3 coins into the change money depots
* Create the following products:
|===
|Name |Price |Stock
|Cappuccino
|0.85€
|10
|Mocca
|1.00€
|10
|Cacao
|0.60€
|10
|===
=== Behaviour
In the following find some explanation what it is supposed to do for each `public` method.
TIP: Also look at the provided unit tests! They very clearly define the expected behaviour.
.In alphabetical order
* `Cancel`
** Aborts the current sale process
** All input coins are returned
* `InsertCoin`
** A new coin is inserted by the customer
** We can only accept coins for which we have a depot
* `SelectProduct`
** Customer selects a product to buy
** Only works if they input enough money _and_ the product ist still in stock
*** We also have to notify the product that it got sold
** If they input too much money we _attempt_ to give as much change as possible
*** We can use the coins in the change money depots _and_ the coins the user put into the machine at this point
**** The remaining coins are added to the change depots for future use
*** We cannot give out more change than the customer 'deserves'
**** => If we do not have enough of use able coins (e.g. we cannot hand out a 1€ coin if we only want to hand out 20 cents) we simply keep the difference and the user looses -- we are a business after all 😉
==== Private Methods
In the <<class_diagram,class diagram>> up top several `private` methods are listed:
* These are _just a suggestion_
* There are no tests for them
** Because we test the `public` interface/contract, not the `private` implementation details
* => You don't have to implement _those_ methods
** But you'll probably need some additional, `private` methods, otherwise your `public` ones will get much too large
==== String Representation
* Meant to be printed to the terminal
** So it includes lines breaks, borders, alignment,...
** _This is not something you would usually do in a `ToString` implementation_
* Makes use of the string representations of `CoinDepot` & `Product`
* Look at the <<sample_run,sample run>> to see how the string representation of the vending machine is supposed to look.
=== Hints
Some coding tips that we already learnt and that might be useful in your implementation, but you might not have used for some time.
.You probably forgot about ranges
[source,csharp]
----
int[] numbers = [1,2,3,4,5];
var firstPart = numbers[..3]; // {1,2,3}
----
.Remember: enums are just named integers
[source,csharp]
----
var result1 = (int) Numbers.Zero + (int) Numbers.Eleven;
var result2 = (int) Numbers.One + (int) Numbers.Two;
Console.WriteLine(result1 + result2); // 14
enum Numbers {
Zero,
One = 1,
Two,
Eleven = 11
}
----
.Parameters can be optional (at the end of the parameter list)
[source,csharp]
----
Foo(2, true); // 4
Foo(2, false); // 2
Foo(2); // 2
void Foo(int aRequiredParam, bool anOptionalParam = false)
{
var result = anOptionalParam ? aRequiredParam * 2 : aRequiredParam;
Console.WriteLine(result);
}
----
== `Program`
Implement _at least_ the minimal version.
Also implement the extended version for _extra credit_.
=== Minimal Version
. Create an instance of `CoffeeVendingMachine`
. Insert some coins (enough to buy something)
. Select a product
. Print the state of the machine to the terminal
==== Sample Run [[sample_run]]
image::pics/sample_run.png[Sample Run]
=== Extended Version
Implement user interaction which allows the user to insert coins & select a product via the terminal.
You can re-use the string representation of the minimal version here to display the state of the vending machine, but you'll need additional input and output logic.
WARNING: _With_ proper retry/error handling of course
== XML Doc
Write _proper_ XML Doc for _at least_ all your `public` members.
This task is *not* optional!