Create an Unit Test for Generic Method - c#

I have the following class:
public class Range<T> where T : IComparable<T> {
public T Minimum { get; set; }
public T Maximum { get; set; }
public Range(T minimum, T maximum) {
Minimum = minimum;
Maximum = maximum;
}
public Boolean Contains(T value) {
return (Minimum.CompareTo(value) <= 0) && (value.CompareTo(Maximum) <= 0);
}
}
I am using XUnit to create my Unit Tests ...
How should I test the Contains method that has T?

As has been stated, you could test it with an int which might look something like this:
var range = new Range<int>(minimum: 3, maximum: 7);
Assert.IsTrue(range.Contains(5));

You need to create an instance of an IComparable and for thoroughness (true unit testing) I would suggest a mocking library with the ability to verify calls. I would probably use something like Moq. You will need an object that implements the interface, which you might have already or you could create a test one with no actual implemetation.
public class YourObject : IComparable<YourObject>
{
public virtual int CompareTo(YourObject other)
{
throw new NotImplementedException();
}
}
I would make a subtle change your Range code just a bit for consistency:
public class Range<T> where T : IComparable<T>
{
public T Minimum { get; set; }
public T Maximum { get; set; }
public Range(T minimum, T maximum)
{
Minimum = minimum;
Maximum = maximum;
}
public Boolean Contains(T value)
{
return (Minimum.CompareTo(value) <= 0) && (Maximum.CompareTo(value) >= 0);
}
}
The end result is identical but it makes things a bit easier while setting up the mocks. Or you could go with value.CompareTo on both accounts. Either way it would add a little more consistency.
The test code would look a little like this:
var min = new Mock<YourObject>();
var max = new Mock<YourObject>();
var val = new Mock<YourObject>();
var range = new Range<YourObject>(min.Object, max.Object);
min.Setup(m => m.CompareTo(It.IsAny<YourObject>())).Returns(-1);
max.Setup(m => m.CompareTo(It.IsAny<YourObject>())).Returns(1);
Assert.True(range.Contains(val.Object));
min.Setup(m => m.CompareTo(It.IsAny<YourObject>())).Returns(0);
max.Setup(m => m.CompareTo(It.IsAny<YourObject>())).Returns(1);
Assert.True(range.Contains(val.Object));
min.Setup(m => m.CompareTo(It.IsAny<YourObject>())).Returns(-1);
max.Setup(m => m.CompareTo(It.IsAny<YourObject>())).Returns(0);
Assert.True(range.Contains(val.Object));
min.Setup(m => m.CompareTo(It.IsAny<YourObject>())).Returns(1);
max.Setup(m => m.CompareTo(It.IsAny<YourObject>())).Returns(1);
Assert.False(range.Contains(val.Object));
min.Setup(m => m.CompareTo(It.IsAny<YourObject>())).Returns(-1);
max.Setup(m => m.CompareTo(It.IsAny<YourObject>())).Returns(-1);
Assert.False(range.Contains(val.Object));
Now you are testing your Range class's Contains method and not the object's ability to return the correct value when it's CompareTo is called.
Happy Coding!

Related

Possible to declare an interface containing an extension?

As part of a testing library, I would like to define an interface which says 'this object knows how to initialize itself randomly'. If members of the randomly filled object are references, the random initialization should be capable of assigning null to these members.
If I was doing this for one class, the code could look like this
public class QWorker
{
double mxVal = 0;
public void fillRandomly(System.Random xRng)
{
mxVal = xRng.NextDouble();
}
}
public class QBoss
{
public QWorker mxWorker;
void fillRandomly(System.Random xRng)
{
if (xRng.Next() % 2 == 1)
x1 = null;
else
{
x1 = new QWorker();
x1.fillRandomly(xRng);
}
}
}
Now if QBoss had mulitple reference-type members, if/else would have to be done for every member. It would look ugly and could be cumbersome to maintain. To cimrcumvent, I came up with the following sample code:
public interface QIRandomizable<T> where T : new()
{
static void fillRandomly(this System.Random xThis, ref T xRef); // XXX
}
class QWorker : QIRandomizable<QWorker>
{
public double mxDouble;
}
public static class QWorkerExtensions
{
public static void fillRandomly(this System.Random xThis, ref QWorker xRef)
{
if ((xThis.Next() % 2) == 1)
xRef = null;
else
{
xRef = new QWorker();
xRef.mxDouble = xThis.NextDouble();
}
}
}
public class QBoss : QIRandomizable<QBoss>
{
public QWorker mx1;
public QWorker mx2;
public static void fillRandomly(this System.Random xThis, ref QBoss xRef)
{
xRef = new QBoss();
xThis.fillRandomly(ref xRef.mxMember1); // can be null
xThis.fillRandomly(ref xRef.mxMember2); // can be null
}
}
However this does not compile and the first problem is on line marked XXX - the static keyword does not belong there.
As a result, I would like to ask the following:
Is it possible to declare an interface with an extension inside?
If yes, what should I change?
If not, is there a different way how to accomplish what I want?
Any help is much appreciated,
Daniel
No, you cannot. That's because you can only declare instance-methods on an interface, and extension methods must be static.
You can try something like this:
public interface IDoesSomething
{
void fillRandomly(Random r);
}
public class QBoss
{
public double mx1 { get; set; }
public double mx2 { get; set; }
public int mx3 { get; set; }
public object refType { get; set; }
public void fillRandomly(Random r)
{
FillRandom(GetProps(this), this, r);
}
}
public static IEnumerable<PropertyInfo> GetProps(object blah)
{
return blah.GetType().GetProperties();
}
public static void FillRandom(IEnumerable<PropertyInfo> obj, object onObj, Random r)
{
Action<PropertyInfo, object> setVal = (prop, val) => { prop.SetValue(onObj, val); };
foreach (var o in obj)
{
if (!o.PropertyType.IsValueType)
{
if (r.Next() % 2 != 1)
{
var v = Activator.CreateInstance(o.PropertyType);
setVal(o, v);
var id = v as IDoesSomething;
if (id != null)
id.fillRandomly(r);
}
}
if (o.PropertyType == typeof(double))
setVal(o, r.NextDouble());
if (o.PropertyType == typeof(int))
setVal(o, (int)(r.NextDouble() * 100));
//etc, etc
}
}
Here, you decide what to do once, and set the properties. This currently only works for properties, not fields, so you might want to refactor it a little to take both FieldInfo and PropertyInfo
Testing it yields:
mx1 0.786868741170908
mx2 0.434705327001729
mx3 51
refType Object

Too many calculated properties in my class

I have class which have too many related calculated properties.
I have currently kept all properties are read only.
some properties need long calculation and it is called again when its related properties are needed.
How can create this complex object .Also i want these properties should not be set from external code. I need show hide as i am binding properties for UI. Also i think order is also important.
My Class is something like
public string A
{
get
{
return complexMethod();
;
}
}
public string B
{
get
{
if (A == "value")
return "A";
else return "B";
;
}
}
public bool ShowHideA
{
get
{
return string.IsNullOrEmpty(A);
;
}
}
public bool ShowHideB
{
get
{
return string.IsNullOrEmpty(B);
;
}
}
public string complexMethod()
{
string value = "";
// calculation goes here
return value;
}
}
Thanks
You need to use Lazy type provided by .net:
Lazy<YourType> lazy = new Lazy<YourType>();
Make your properties internal to not be set from external code.
Well tall order isn't it?
One of the coolest things about extension methods is you can use types. This is perfect for writing external programs to calculate property values. Start like this...
public static class XMLibrary
{
public static MC CalculateValues(this MC myclass)
{
//for each property calculate the values here
if (myclass.Name == string.Empty) myclass.Name = "You must supply a name";
if (myclass.Next == 0) myclass.Next = 1;
//when done return the type
return myclass;
}
}
public class MC
{
public string Name { get; set; }
public int Next { get; set; }
}
public class SomeMainClass
{
public SomeMainClass()
{
var mc = new MC { Name = "test", Next = 0 };
var results = mc.CalculateValues();
}
}
There are many other ways to do class validation on a model, for example dataannotations comes to mind, or IValidatableObject works too. Keeping the validation separate from the class is a good idea.
//Complex properites are simple
public class MyComplextClass{
public List<MyThings> MyThings {get;set;}
public List<FileInfo> MyFiles {get;set;}
public List<DateTime> MyDates {get;set;}
}

How to share all the properties of two interfaces with the same properties

I have two interfaces and the both have the same exact properties.
Just in case you're wondering why I've got two interfaces like these it's a long story, but yes, it has to be this way.
Based on a condition a List is returned if condition is the other way a List will be returned.
By looking at my interfaces and my code below I need to be able to make use of one object, in other words if doesn't matter which interface is returned I need to be able to work with one object and not looping one List interface and setting properties of the other.
I need something like this
compParts = genCompParts;
--- Code usage
public class ComponentParts : IComponentParts
{
public ComponentParts() { }
public ComponentParts(Guid userID, int compID, bool isGeneric)
{
List<IComponentPart> compParts = null;
List<IComponentPart_Max> genCompParts = null;
if (isGeneric)
{
genCompParts = GenericCatalogBL.GenericCatalogManagerBL.GetComponentPartsMax(compID);
}
else
{
compParts = CatalogManagerDL.GetComponentParts(userID, compID);
}
var verParts = compParts.Where(x => x.CompTypeName.ToLower().Contains("vertical"));
if (verParts.Count() > 0) { this.Vertical = verParts.ToList<IComponentPart>(); }
var horParts = compParts.Where(x => x.CompTypeName.ToLower().Contains("horizontal"));
if (horParts.Count() > 0) { this.Horizontal = horParts.ToList<IComponentPart>(); }
//... redundant code omitted
---Interface Snapshots---
I ended up creating a class library call Interfaces and I just share those interfaces across different programs in my solution.
It's what I should of done in the first place, just being lazy.
The totally brute-force way, assuming you don't own either IComponentPart or IComponentPart_Max and can't fix one of them.
Make a new interface that you control
interface IComponentPart {
string BrandGroup {get; set;}
int BrandID {get; set;}
// ...
}
Make wrappers for both of the existing interfaces that adapt them to your interface
class IComponentPartWrapper : IComponentPart {
private readonly CatelogDL.IComponentPart _underlyingPart;
public IComponentPartWrapper(CatelogDL.IComponentPart underlyingPart) {
_underlyingPart = underlyingPart
}
public string BrandGroup {
get {return _underlyingPart.BrandGroup;}
set {_underlyingPart.BrandGroup = value;}
}
public int BrandID {
get {return _underlyingPart.BrandID ;}
set {_underlyingPart.BrandID = value;}
}
// ...
}
class IComponentPart_MaxWrapper : IComponentPart {
private readonly GenericCatalogDL.IComponentPart_Max _underlyingPart;
public IComponentPartWrapper(GenericCatalogDL.IComponentPart_Max underlyingPart) {
_underlyingPart = underlyingPart
}
public string BrandGroup {
get {return _underlyingPart.BrandGroup;}
set {_underlyingPart.BrandGroup = value;}
}
public int BrandID {
get {return _underlyingPart.BrandID ;}
set {_underlyingPart.BrandID = value;}
}
// ...
}
Make your code use your interface, and wrap the results from either library in the corresponding wrapper
public class ComponentParts : IComponentParts
{
public ComponentParts() { }
public ComponentParts(Guid userID, int compID, bool isGeneric)
{
List<IComponentPart> compParts;
if (isGeneric)
{
compParts = GenericCatalogBL.GenericCatalogManagerBL.GetComponentPartsMax(compID)
.Select(x => new IComponentPart_MaxWrapper(x))
.ToList();
}
else
{
compParts = CatalogManagerDL.GetComponentParts(userID, compID)
.Select(x => new IComponentPartWrapper(x))
.ToList();
}
// ...

Is there a structure that handles Timeblocks?

I want to handle Timeblocks, that means a set of two DateTimes which represent for example the presence of employees. Is there already any structure that i can use to search for a block before or after a specific time?
There are many ways i can imagine to express the situation, like i said with two DateTimes for start and end or with a Datetime for start and a TimeSpan. But i want them to be handled in a kind of Collection. So is there anything similar that i can use or do i have to implement it completely on my own?
Thanks
this library is a great thing - may you get inspired
Time Period Library for .NET
The class:
public class TimePeriod
{
public DateTime Oldest { get; set; }
public DateTime Newest { get; set; }
public TimePeriod(DateTime oldest, DateTime newest)
{
Oldest = oldest;
Newest = newest;
}
public bool Contains (DateTime time)
{
return Oldest.CompareTo(time) <= 0 && Newest.CompareTo(time) >= 0;
}
public bool IsAfter(DateTime time)
{
return Newest.CompareTo(time) <= 0;
}
public bool IsBefore(DateTime time)
{
return Oldest.CompareTo(time) >= 0;
}
}
The Test:
class Program
{
static void Main(string[] args)
{
var period = new TimePeriod(
DateTime.Now.AddDays(-2),
DateTime.Now.AddDays(1));
var date = DateTime.Now;
var contains = period.Contains(date); // true
var isBefore = period.IsBefore(date); // false
var isAfter = period.IsAfter(date); // false
date = DateTime.Now.AddDays(-10);
contains = period.Contains(date); // false
isBefore = period.IsBefore(date); // true
isAfter = period.IsAfter(date); // false
date = DateTime.Now.AddDays(10);
contains = period.Contains(date); // false
isBefore = period.IsBefore(date); // false
isAfter = period.IsAfter(date); // true
}
}
Now you can use collections and linq with extensions methods and lambda expression to look for time blocks.
This is not built-in. If you want to implement this yourself you probably want to create a struct. This will give you value-type copy semantics. Such a value behaves just like built-in types like int or DateTime. Very intuitive to use.
You may take a look at TimeSpan. Thats a struct to handle a "Timeblock"
I've used a DateSpan structure before. You can extend is a much as one likes, but this will give you a starting point.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace StackOverFlowDateSpan
{
[StructLayout(LayoutKind.Auto)]
[Serializable]
public struct DateSpan : IComparable, IComparable<DateSpan>, IEquatable<DateSpan>
{
public DateSpan(DateTime start, DateTime end)
: this()
{
Start = start;
End = end;
}
#region Properties
public TimeSpan Duration
{
get { return TimeSpan.FromTicks((End - Start).Ticks); }
}
public DateTime End { get; private set; }
public DateTime Start { get; private set; }
#endregion
public int CompareTo(DateSpan other)
{
long otherTicks = other.Duration.Ticks;
long internalTicks = Duration.Ticks;
return internalTicks > otherTicks ? 1 : (internalTicks < otherTicks ? -1 : 0);
}
public bool Equals(DateSpan other)
{
return End.Equals(other.End) && Start.Equals(other.Start);
}
public int CompareTo(object other)
{
if (other == null)
{
return 1;
}
if (!(other is DateSpan))
{
throw new ArgumentNullException("other");
}
return CompareTo((DateSpan)other);
}
public override bool Equals(object other)
{
if (ReferenceEquals(null, other))
{
return false;
}
return other is DateSpan && Equals((DateSpan)other);
}
public override int GetHashCode()
{
unchecked
{
return (End.GetHashCode() * 397) ^ Start.GetHashCode();
}
}
public static bool operator ==(DateSpan left, DateSpan right)
{
return left.Equals(right);
}
public static bool operator !=(DateSpan left, DateSpan right)
{
return !left.Equals(right);
}
private sealed class EndStartEqualityComparer : IEqualityComparer<DateSpan>
{
#region IEqualityComparer<DateSpan> Members
public bool Equals(DateSpan x, DateSpan y)
{
return x.End.Equals(y.End) && x.Start.Equals(y.Start);
}
public int GetHashCode(DateSpan obj)
{
unchecked
{
return (obj.End.GetHashCode() * 397) ^ obj.Start.GetHashCode();
}
}
#endregion
}
private static readonly IEqualityComparer<DateSpan> _endStartComparerInstance = new EndStartEqualityComparer();
public static IEqualityComparer<DateSpan> EndStartComparer
{
get { return _endStartComparerInstance; }
}
}
}
Thanks for the help! I will tae a closer look at the TimePeriod Library and do some experiments with Linq. I already have an approch that implements binary search, so if someones interested you can write me ;)

What pattern should I use to express a Hierarchical Enum?

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.

Categories

Resources