My C# classes are generally structured this way:
public class MyDummyService
{
private readonly MyConfigClass _config;
public MyDummyService(IOptions<MyConfigClass> options)
{
_config = options.Value;
}
public string DoSomethingWithTheNumber()
{
if (_config.SomeValue % 2 == 0)
return "foo";
return "bar";
}
}
public class MyConfigClass
{
public int SomeValue{get; set;}
public string SomeName {get; set;}
}
Clearly, IOptions<MyConfigClass> is used to map configurations from the appSettings.json file.
Then, I can test such classes like this:
class MyDummyServiceTests
{
protected AutoFixture.Fixture _fixture;
protected MyDummyService _sut;
protected MyConfigClass _simpleConfig;
protected Mock<IOptions<MyConfigClass>> _mockConfig;
public MyDummyServiceTests()
{
_fixture = new AutoFixture.Fixture();
_mockConfig = new Mock<IOptions<MyConfigClass>>();
_simpleConfig = _fixture.Build<MyConfigClass>()
.With(i => i.SomeValue, 4)
.With(i => i.SomeName, "Pippo")
.Create();
}
[SetUp]
public void Setup()
{
_mockConfig.SetupGet(m => m.Value).Returns(_simpleConfig);
_sut = new MyDummyService(_mockConfig.Object);
}
[TearDown]
public void TearDown()
{
_mockConfig.Reset();
}
public class DoSomethingWithTheNumber : MyDummyServiceTests
{
[Test]
public void Should_ReturnFoo_WhenNumberIsEven()
{
_simpleConfig = _fixture.Build<MyConfigClass>()
.With(_ => _.SomeValue, 10)
.Create();
var s = _sut.DoSomethingWithTheNumber();
Assert.AreEqual("foo", s);
}
[Test]
public void Should_ReturnBar_WhenNumberIsOdd()
{
_simpleConfig = _fixture.Build<MyConfigClass>()
.With(_ => _.SomeValue, 69)
.Create();
var s = _sut.DoSomethingWithTheNumber();
Assert.AreEqual("bar", s);
}
}
}
Yes, I know, I should use [TestCase] - you got the point
Now, when I set up tests for such classes, and I want to test a specific behavior that depends on the MyConfigClass.SomeValue value, I don't want to re-initialize everything. I can clearly just add _mockConfig.SetupGet(m => m.Value).Returns(_simpleConfig); or _sut = new MyDummyService( Options.Create(_simpleConfig)); but I want to keep my tests as small as possible, and only set the configuration value I need.
If I run the tests as such, DoSomethingWithTheNumber() does not see MyConfigClass.SomeValue with the correct value, because it is initialized and assigned to _config during StartUp phase, so before I set the correct value in my tests.
How can I improve my approach and set only the values necessary to have the specific test pass?
Note: I do not expect my configurations to change at runtime. Therefore, I can use IOptions<T>, IOptionsMonitor<T>, or IOptionsSnapshot<T> - even if they are different meanings, as explained here.
Thanks in advance!
We have some Automation tests using the selenium web driver which are great and provide a really good regression pack.
The problem is now we have feature toggles in our code. So I need to say ignore these tests unless that feature toggle is turned On/ Off. I can't find anything really searching Google.
Ideally I don't want a 'if' statement at the top of the Feature tests but it looks like it's going to be the main way. My initial thoughts where to create a custom attribute
public class IsFeatureFlagTurnedOn : Attribute
{
public IsFeatureFlagTurnedOn(string featureToggleName)
{
FeatureToggleName = featureToggleName;
}
public string FeatureToggleName {get;}
}
public class MyTests
{
[TestMethod]
[IsFeatureFlagTurnedOn("MyFeature1")]
public void ItShould()
{
// only run if MyFeature1 is turned on
}
}
I some how need to hook into the MSTest pipeline and say if this attribute is present and the logic for MyFeature1 is turned off then don't run this test - Looked at dynamically adding the [Ignore] but with no luck.
This is running through VSTS and I could use [TestCategories] but I'd have to keep updating the pipeline to which feature is turned on/off which I don't want to do.
Any help or suggestions would be great!
MSTest v2 now has a lot of extensibility points, and you can achieve this by extending the TestMethodAttribute. First we add two attribute arguments, a string for a property name and a Type that has the property. Then we override the Execute method and invoke the property via reflection. If the result is true, we'll execute the test as normal, otherwise we return an 'inconclusive` test result.
public class TestMethodWithConditionAttribute : TestMethodAttribute
{
public Type ConditionParentType { get; set; }
public string ConditionPropertyName { get; set; }
public TestMethodWithConditionAttribute(string conditionPropertyName, Type conditionParentType)
{
ConditionPropertyName = conditionPropertyName;
ConditionParentType = conditionParentType;
}
public override TestResult[] Execute(ITestMethod testMethod)
{
if (ConditionParentType.GetProperty(ConditionPropertyName, BindingFlags.Static | BindingFlags.Public)?.GetValue(null) is bool condiiton && condiiton)
{
return base.Execute(testMethod);
}
else
{
return new TestResult[] { new TestResult { Outcome = UnitTestOutcome.Inconclusive } };
}
}
}
Now we can use our new attribute like this:
[TestClass]
public class MyTests
{
[TestMethodWithCondition(nameof(Configuration.IsMyFeature1Enabled), typeof(Configuration))]
public void MyTest()
{
//...
}
}
public static class Configuration
{
public static bool IsMyFeature1Enabled => false;
}
The above is a very generic solution. You could also customize it a little more to your particular use case to perhaps avoid quite so much verbosity in the attribute declaration:
public class TestMethodForConfigAttribute : TestMethodAttribute
{
public string Name { get; set; }
public TestMethodForConfigAttribute(string name)
{
Name = name;
}
public override TestResult[] Execute(ITestMethod testMethod)
{
if (IsConfigEnabled(Name))
{
return base.Execute(testMethod);
}
else
{
return new TestResult[] { new TestResult { Outcome = UnitTestOutcome.Inconclusive } };
}
}
public static bool IsConfigEnabled(string name)
{
//...
return false;
}
}
And use it like:
[TestClass]
public class MyTests
{
[TestMethodForConfig("MyFeature1")]
public void MyTest()
{
//...
}
}
Based on my reading of this, you may need to use Assert.Inconclusive
In my .NET 4.0 application I'm accessing application properties through the interface ISettings I prepared:
public interface ISettings
{
int Quota { get; }
string Property2 { get; }
// ...
int PropertyN { get; }
}
// code generated by Visual Studio
public sealed partial class Settings :
global::System.Configuration.ApplicationSettingsBase
{
// application properties generated from app.config
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("123")]
public int Quota {
get {
return ((int)(this["Quota"]));
}
}
// and so on...
}
// my code to apply the interface to the Settings class
public sealed partial class Settings : ISettings
{
}
In some scenarios I would like to override the values from the config file depending on the organization I'm processing the data for, in example I would like to increase the quota for some organization. Of course, I could create the method similar to:
public int GetQuotaByOrgId(int orgId);
and implement the logic there, but I would like to avoid passing the orgId among the code. The better solution for me would be to create a proxy class overriding only the values I want to change, something like:
public class OverridenSettings : ISettings
{
private ISettings instance;
private int orgId;
private int[] orgsWithBiggerQuota = {1, 2, 132, 6542};
public OverridenSettings(ISettings instance, int orgId)
{
this.instance = instance;
this.orgId = orgId;
}
public override int Quota
{
get
{
int quota = this.instance.Quota;
if (this.orgsWithBiggerQuota.Contains(this.orgId))
{
quota += 1000;
}
return quota;
}
}
// all other properties should be taken from the default instance
}
Is there an elegant way to generate such class without having to explicitely implement all the interface's members just to redirect them to the default instance?
You can use any of the frameworks out there to create a dynamic proxy of your Settings class.
For example using Unity I can create an object of a class(in your case Settings class) like this
ISettings settings = (ISettings)Intercept.NewInstance(typeof(Settings), new VirtualMethodInterceptor(), new IInterceptionBehavior[] { new OrganizationInterceptor(orgId)});
The OrganizationInterceptor has the ability to 'intercept' method calls(including property getters/setters) and could have an implementation like:
public class OrganizationInterceptor : IInterceptionBehavior
{
private int OrgId { get; set; }
private List<int> orgsWithBiggerQuota;
public OrganizationInterceptor(int orgId)
{
OrgId = orgId;
WillExecute = orgId > 0;
}
public IEnumerable<Type> GetRequiredInterfaces()
{
return Type.EmptyTypes;
}
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
var ret = getNext()(input, getNext);
if (input.MethodBase.IsSpecialName && input.MethodBase.Name == "get_Quota" &&
this.orgsWithBiggerQuota.Contains(OrgId))
ret.ReturnValue = (int)ret.ReturnValue + 100;
return ret;
}
public bool WillExecute { get; set; }
}
I haven't ran this myself so you might need to debug it a bit(especially the Invoke method).
If you want to use the VirtualMethodInterceptor you need to declare your property virtual. There is also TransparentProxyInterceptor which doesnt require this but will create another object that will call into your object(2 objects in total vs 1 in the virtual case).
I'm experimenting with an API for publishing values at a given time (tuples of value and time). These samples will be used by a data viewer (e.g. a graph).
I want to associate the value with a Quantity and a Unit, for example length in meters. That way my "viewer" can scale it appropriately.
I'm looking for a sort of hierarchical enum, like this:
enum Quantity
{
Mass.Kg,
Mass.g,
Length.m,
Length.mm
}
But this doesn't exist in C#.
I'm not sure the best pattern to express this and I've come up with the following. Is there a recognised, or better way to do this?
using System;
using Moq;
namespace ConsoleApplication26
{
class Program
{
static void Main(string[] args)
{
//use a Mock to play with the API
Mock<ITelemetryPublisherFactory> mockTelemetryPublisherFactory = new Mock<ITelemetryPublisherFactory>();
var telemetryPublisherFactory = mockTelemetryPublisherFactory.Object;
//example usages
var massTelemetryPublisher = telemetryPublisherFactory.GetChannelSamplePublisher<Double>("My Mass", Mass.Kg);
massTelemetryPublisher.PublishChannelSampleAtTimeNow(83.4);
var lengthTelemetryPublisher = telemetryPublisherFactory.GetChannelSamplePublisher<Int32>("My Height", Length.μm);
lengthTelemetryPublisher.PublishChannelSampleAtTimeNow(1800000);
//10 years time..
lengthTelemetryPublisher.PublishChannelSampleAtTimeNow(1800000);
massTelemetryPublisher.PublishChannelSampleAtTimeNow(120.1);
}
}
public interface ITelemetryPublisherFactory
{
ITelemetryPublisher<T> GetChannelSamplePublisher<T>(String channelName, Quantity quantity);
}
public interface ITelemetryPublisher<T>
{
void PublishChannelSampleAtTimeNow(T sampleValue);
}
public abstract class Quantity {}
public class Mass : Quantity
{
private enum Unit
{
g,
Kg
}
private readonly Unit _unit;
private Mass(Unit unit)
{
_unit = unit;
}
public static Quantity Kg {get { return new Mass(Unit.Kg); }}
public static Quantity g { get { return new Mass(Unit.g); } }
public override string ToString()
{
return String.Format("Mass.{0}", _unit);
}
}
public class Length : Quantity
{
private enum Unit
{
m,
mm,
μm,
beardSecond
}
private readonly Unit _unit;
private Length(Unit unit)
{
_unit = unit;
}
public static Quantity m { get { return new Length(Unit.m); } }
public static Quantity mm { get { return new Length(Unit.mm); } }
public static Quantity μm { get { return new Length(Unit.μm); } }
public static Quantity beardSecond { get { return new Length(Unit.beardSecond); } }
public override string ToString()
{
return String.Format("Length.{0}", _unit);
}
}
}
I think it's better to create a Unit class for the unit of measure and a Quantity class that associates a unit of measure with an amount. Look at the Quantity pattern for the idea. Since you also want to record the "type" of the unit of measure, you could create a UnitType class that records that information:
public sealed partial class UnitType {
public string Name { get; private set; }
public UnitType(string name) {
Name = name;
}
}
public sealed partial class Unit {
public string Name { get; private set; }
public UnitType Type { get; private set; }
public Unit(string name, UnitType type) {
Name = name;
Type = type;
}
}
(You should make them proper value types by overriding Equals and GetHashCode)
The Unit class can be extended to provide for e.g. conversions, compound units, formatting and parsing.
Then, you can define the common cases inside the classes:
public partial class UnitType {
public static readonly UnitType Mass = new UnitType("Mass");
public static readonly UnitType Length = new UnitType("Length");
}
public partial class Unit {
public static readonly Unit Grams = new Unit("g", UnitType.Mass);
public static readonly Unit Kilos = new Unit("kg", UnitType.Mass);
// ...
}
Or define your "hierarchies" with static classes:
public static class Mass {
public static readonly UnitType Type = new UnitType("Mass");
public static readonly Unit Grams = new Unit("g", Type);
public static readonly Unit Kilos = new Unit("kg", Type);
...
}
public static class Length ...
The Quantity class would also be an immutable value type (just showing its usage):
var eniacWeight = new Quantity(27, Mass.Tons);
Or you could use extension methods to create Quantitys:
var eniacWeight = 27.Tons();
(from ENIAC)
This is not possible. Enums are primitive types and cannot inherit from other enums, as inheritance is a property of objects.
Hierarchical enum isn't possible, as noted above. If you're exclusively using metric, though, you can utilise standard prefixes if it helps.
enum MeasurementUnits
{
Gram,
Metre,
Litre,
Hectare
// etc
}
enum MeasurementPrefix
{
Milli,
Natural,
Kilo,
Mega
// etc
}
This may not be precisely what you want, but it will provide the type of 'grouping' that you might be looking for (e.g. group measurements that are about length, weight etc by checking their 'units' value).
Your suggested approach seems reasonable to me, and I use something similar in a project of mine. However, I keep the actual value part of the object, and I use struct instead of class, since they are naturally value types. Inheritance is not necessary here (and not possible with structs, anyways), so I use an interface to create a contract and act as a constraint when needed (I called it IUnitOfMeasure).
I do not recommend creating one enum with all the units of the various types of measurement combined; it is hell validating the unit to make sure someone didn't reference a Mass unit when working with Length.
public interface IUnitOfMeasure<TThis>
where TThis : IUnitOfMeasure<TThis>
{
TThis ConvertTo(TThis value);
}
public struct Mass : IUnitOfMeasure<Mass>
{
public enum Units
{
Gram,
Kilogram
}
private double _value;
private Mass.Units _unit;
public double Value { get { return _value; } }
public Mass.Units Unit { get { return _unit; } }
public Mass(double value, Mass.Units unit)
{
_value = value;
_unit = unit;
}
public Mass ConvertTo(Mass value)
{
switch(value.Unit)
{
case Units.Gram:
return new Mass(Unit == Units.Gram ? Value : Value/1000, Units.Gram);
case Units.Kilogram:
return new Mass(Unit == Units.Gram ? Value*1000 : Value, Units.Kilogram);
default:
throw new NotImplementedException();
}
}
public override string ToString()
{
return string.Format("{0} {1}", Value, Unit);
}
public static readonly Mass G = new Mass(0, Units.Gram);
public static readonly Mass Kg = new Mass(0, Units.Kilogram);
}
Usage:
var kg = new Mass(5.0, Mass.Units.Kilogram);
Console.WriteLine(kg); // writes "5 Kilogram"
var g = kg.ConvertTo(Mass.G);
Console.WriteLine(g); // writes ".005 Gram"
If you don't care about keeping the value, and just want to keep enum/static values in a central place:
public static class UnitOfMeasure
{
public enum Mass
{
Gram,
Kilogram
}
public enum Length
{
Meter,
Kilometer
}
// etc.
}
Usage: var unit = UnitOfMeasure.Mass.Kilogram;
You cannot introduce inheritance with enums. Enums are just a convenience mechanism to allow you to use meaningful textual identifiers in your code. From The code you have, I suggest you either use an enum like;
public enum UnitOfMeasure
{
MassGrams,
MassKg,
LengthMM,
LengthCM,
. . .
}
Or split it out to where it's appropriate, so that Mass and Length are defined separately for example.
The 'inheritance' is just something you've introduced in your thinking about this problem, but it isn't necessary to your solution. When you want to deal with Mass, you only look at the flags/enums appropriate to mass.
I have the following:
List<IReport> myList = new List<IReport>();
Report myReport = TheirApi.GetReport();
myReport meets all the qualifications of IReport, but cannot implement IReport because I do not have access to the source of TheirApi. Casting to type IReport obviously results in null, and I read that I cannot cast an anonymous type to an interface.
Do I have any options here?
A wrapper class was just what the doctor ordered:
ReportServices.GetAllCustomReports().ToList().ForEach(customReport => _customReports.Add(new ReportWrapper(customReport)));
public class ReportWrapper : IReport
{
private Report inner;
public int ID
{
get { return inner.ID; }
set { inner.ID = value; }
}
public string Name
{
get { return inner.Name; }
set { inner.Name = value; }
}
public ReportWrapper(Report obj)
{
inner = obj;
}
}
You will need to wrap this object inside another one that implements the interface, and then you will need to implement it calling the inner object's properties and methods.
For example:
public class ReportWrapper : IReport
{
MyObjectIsLikeReport inner;
public ReportWrapper(MyObjectIsLikeReport obj) {
this.inner = obj;
}
public void ReportMethod(int value) {
this.inner.ReportMethod(value);
}
public int SomeProperty {
get { return this.inner.SomeProperty; }
set { this.inner.SomeProperty = value; }
}
}
To use it, you can do this:
List<IReport> myList = new List<IReport>();
MyObjectIsLikeReport myReport = TheirApi.GetReport();
myList.Add(new ReportWrapper(myReport));
Consider Adapter Design Pattern.
Definition: Convert the interface of a class into another interface
clients expect. Adapter lets classes work together that couldn't
otherwise because of incompatible interfaces.
good reference: http://www.dofactory.com/Patterns/PatternAdapter.aspx
interface IReport
{
void DoSomething();
}
class ReportApdapter : IReport
{
private readonly Report _report;
public ReportApdapter(Report report)
{
_report = report;
}
public void DoSomething()
{
_report.DoSomething();
}
}
class Report
{
public void DoSomething()
{
}
}
//You can use like this.
IReport report = new ReportApdapter(TheirApi.GetReport());