Only unit test observable behavior, not system requirements? - c#

I'm reading a book on unit testing, below is the code example:
public class User {
private string _name;
public string Name {
get => _name;
set => _name = NormalizeName(value);
}
private string NormalizeName(string name) {
/* Trim name down to 50 characters */
}
}
public class UserController {
public void RenameUser(int userId, string newName) {
User user = GetUserFromDatabase(userId);
user.Name = newName;
SaveUserToDatabase(user);
}
}
The author says
UserController in this example is an application service. Assuming that the external client doesn't have a specific goal of normalizing user names, and all names are normalized solely due to restrictions from the application itself, the NormalizeName method in the User class can't be traced to the client's needs. Therefore, it's an implementation detail and should be made private. Moreover, tests shouldn't check this method directly. They should verify it only as part of the class's observable behavior-the Name property's setter in this example.
So the author means we shouldn't write a test to test NormalizeName method, instead, we should write a test to test Name property. But image if the developer didn't write NormalizeName method properly and names more than 50 characters are allowed to be input, which will cause an exception thrown later, shouldn't we write a NormalizeName method test to guard this?

The author is saying that you should test for this scenario by designing an appropriate test , indirectly, through the public User.name property, not with a test that directly calls NormalizeName.

Of course, it is important to test NormalizeName. But you can test it indirectly by testing the property. See this test:
[TestMethod]
public void NameProperty_TrimsLongNames()
{
// arrange
User user = new User();
string name = "very very very long name... and even longer... and still longer";
string expectedName = "very very very long name... and even longer... an";
// act
user.Name = name;
// assert
Assert.AreEqual(user.Name, expectedName);
}
By calling the setter, you also call NormalizeName. If this method doesn't work correctly, this test will fail. The fact that the functionality to trim the name is in this method, is an implementation detail. It might also be directly in the setter of the property. Hence you only call the setter in the test, because that is your observable behaviour: If I set the Name property to a new value, long names should be truncated. It is not important, if this is done via a private method, an extension method for the string class or somehow else.

Related

Autofixtures "With"-Customizations for are ignored when using Build<T>

My goal is to be able to define only the parameters that are relevant for the specific tests, with immutable types in c# (strictly constructor injection, no set'ers), and have a customized fixture take care of valid values for parameters that is not specified in the test.
Scratching my head over this one - my "with" property-customations for strings, DateTime's and int's are disregarded. Example based on "Guest":
public class Guest
{
public readonly string GuestId;
public readonly string GivenName;
public readonly string SurName;
public readonly AgeCode AgeCategory;
public Guest(string guestid, AgeCode ageCategory, string givenName, string surName)
{
AgeCategory = ageCategory;
GivenName = givenName;
SurName = surName;
GuestId = guestid;
}
}
I customize a Fixture instance like so:
fixture.Customize<Guest>(composer =>
composer
.With(g => g.GivenName, "Finn")
.With(g => g.GuestId, "1")
.With(g => g.SurName, "Rasmussen")
);
...Which works when using fixture.Create<Guest>(), but not when using fixture.Build<Guest>().With(g=>g.Surname, "Olsen").
Looking at the AutoFixture signatures, i understand this is because Fixture.Build<T>() instantiates a new composer, and that composer is not injected as the 'composer' instance of the Customize<T> method.
Also - I understand that the first customization for a property "wins", so "overwrites" would have to be pushed in front of the customizations...
Any suggestions? Am I completely of track here, trying to use a screwdriver to hammer a nail? Or am I simply not seeing something clever and/or obvious here...
For anyone else finding this:
The default strategy for building a type can be changed with
Fixture.Register<TType>(Func<TType> creator)
Works like a charm...

C# - is this possible to declare a class where all fields are wrappers of another class's fields?

Please feel free to modify the title, I couldn't come up with any better one =\
Given the following example class
public class Person
{
public string Name;
public int ID;
public string City;
}
I need to create another mirror class, where every field is actually a wrapper of the original class:
public class PersonMirror
{
public FieldWrapper<string> Name;
public FieldWrapper<int> ID;
public FieldWrapper<string> City;
}
public class FieldWrapper<T>
{
public T Value;
public bool someBool;
public int someCounter;
// ..whatever
}
The thing is, I have many classes to mirror, and some of them have many fields! Moreover, the original class may be changed from time to time (add / remove / rename field), and every change must be applied to the mirrored class - not a good practice for maintainability.
My question is - is there a type safe way automate the decleration (rather then creation, such as generated code) of such mirrored classes?
EDIT:
Let's start from the beginning. In our SOA system, there is a resource access service (serviceX) responsible for updating items in the DB. Other services send it the modifications they would like to perform - in json that would be something like: {ID: 123, name : "myNewName"}. serviceX would then build an update query to send to the DB. However, there is a requirement that serviceX will expose a POCO interface, so that the interface will be language independent, so expressions such as (p=> p.name, "MyNewName") are not allowed. Another requirement is type safety, so json is not allowed either. Currently, the above solution is the best one we came up to answer all the requirements. Any better solutions are more then welcome!
IMO, there's no way to do what you want, except code generation.
Approaches for code generation could differ (this maybe source code generation + compilation, emitting IL code, either your own or existing one), but this is the only way.
use T4 to autogenerate your "WrapperClass".
Below, a proposition of how you could implement your FieldWrapper.
public class FieldWrapper<T, O>
{
private T _item;
private O _owner;
private PropertyInfo _setter;
public T Value
{
get { return _item; }
set {
if (!EqualityComparer<T>.Default.Equal(_item, value))
{
_item = value;
// do some personal check
_setter.SetValue(_owner, value);
}
}
}
public bool someBool;
public int someCounter;
// ..whatever
// CTOR
public FieldWrapper(O owner, Expression<Func<T, O>> propertyExpressionInTheOwner)
{
_owner = owner;
propertyName = (propertyExpressionInTheOwner.body as MemberExpression).Member.Name;
// get PropertyInfo using the owner and propertyName
}
}
Using the expression behavior permits you to create your fieldWrapper this way.
var p = new Person();
new FieldWrapper(p, (pers) => pers.Name);
The good point with this technique it is that if you person class change you will directly receive a compilation error.
With T4 the must is to load the assembly where all you class are, tag you class model with a specific attribute. Look into the assembly to found every class that have this attribute and generate the wrapper class associate.
You would have to run it after every code change, but you could create a code parsing application.
List desired keywords to substitute, such as " string ", " int ". Read the file, line by line. Find definition of classes (line contains "class"), then replace every instance of any given keyword in it with:
"FieldWrapper<" + keyword + ">"
You might want to drop keyword substitution inside methods (and perhaps in the method signatures / return types themselves) of by checking for "(" and ")", and the opening curly brace. Resume operation when you reach the closing curly brace. You can achieve that by storing the nesting level in an integer, incrementing it when hitting '{' and decrementing it when reaching '}'.

Seeking an elegant way for inherited classes to have a "StateName" property

See my solution below -- search for UPDATE.
I have an extensive state machine architecture, which I'm implementing by creating a class for each state (there are multiple machines, but the states for all inherit from the same 'MachineState' class). Each state has a static property "StateName":
public class SomeState: MachineState
{
// THIS BLOCK SHOULD BE COPIED TO ALL STATE CLASSES!!
private static string _StateName;
public static string StateName
{
get {
if (_StateName == null)
{
_StateName = MethodBase
.GetCurrentMethod()
.DeclaringType
.ToString()
.Split(new char[] { '.' })
.ToList()
.Last();
}
return _StateName;
}
}
// END OF BLOCK
public SomeState(Queue<string> messages) //
: base(messages)
{
...
}
...
}
Ugh.
At least I'll call the processor-intensive stuff to get the name only once per class -- for my purposes, that's an acceptable cost. But I would really like to find some way for them to "inherit" this code -- or at least some way for them to include it something like a macro. I have an abstract property, so if it's not implemented I'll catch it at compile time; but still, there's got to be a way to avoid copying that mess into EVERY class -- and then having to CHANGE it in every class if the need ever arises.
Any ideas?
Thanks.
------------ UPDATE ---------------------------------------
Life is full of compromises; this one I can live with. #Tallek suggested this in the base class:
public static string GetStateName<T>() where T : MachineState
{
return typeof(T).Name;
}
I integrated that with my static property, like this (for class 'SomeState'):
// THIS BLOCK SHOULD BE COPIED TO ALL STATE CLASSES!!
public static string StateName { get { return GetStateName<SomeState>(); } }
It isn't perfect; I'll have to be sure to get the correct state name in the GetStateName call for each class. But it does two things I was anxious to do: it moves the logic into a single location, and it is easier to read. Keeping StateName abstract will help me catch any state that hasn't implemented StateName.
Thanks again, to all.
You have a state
Your states are classes
You want to compare that state to another
You don't want to instanciate states in order to compare
I don't see you doing it easier than:
if(state.GetType() == typeof(SomeState))
I potentially agree with CodeCaster. 20 or 30 states is not that large for an enum.
Based on your description of receiving a message and identifying the handler for that message, combined with looking at your example:
if(stateName == SomeState.StateName) { }
This implies you have stateName as a parameter. So you have an if block for every state so you can identify which one the message applies to?
if(stateName == SomeState.StateName) {
}
if(stateName == OtherState.StateName) {
}
If that is the case...
(big if given limited use case information, the rest of this answer is based on that premise so don't flame me if the rest of this doesn't apply)
You desire to have all classes automatically have this StateName property. This seems DRY, but then we see you still have to have an if block for each state, which is less DRY since there's more code to that IMO. You've traded a DRY for another DRY.
I would have enums which each have a
public enum States {
...
[Handler(typeof(SomeState))]
SomeState = 5,
...
Combined with a factory pattern, and now you throw out all the if blocks and only need a call to your factory:
MachineState newState = StateFactory.Create(stateName);
The factory uses Enum.Parse to convert the stateName into an enum, from which you access the attribute to get the type you need to instantiate. No switch/case/if/else needed.
This means every time you implement a new state class, you only need to touch one place, and that is the enum, and that has minimal code repetition.
If each if block has specific logic in it for that particular State
Move that code into a HandleMessage method defined in a MachineState or IMachineState interface, which has an implementation for each SomeState to do the stuff specific for that state. Let's assume your message indicates the stateName and maybe there's some "content" or "data" in the message that needs to be processed:
MachineState newState = StateFactory.Create(stateName);
newState.HandleMessage(messageContent);
I realize it's probably more complicated than that. You might need to seperate state from state handling into separate classes to make this work well. It's hard say. I would certainly mull this over pretty heavily though if I were in your shoes.
Its not great, but maybe worth considering...
public class MachineState
{
public static string GetStateName<T>() where T : MachineState
{
return typeof(T).Name;
}
}
Use like this:
if("MyState" == MachineState.GetStateName<MyState>()) { ... }
You could accomplish this with an extension method:
public static string GetStateName(this MachineState state) {
return state.GetType().Name;
}
Use it like this:
if(state.GetStateName() == "SomeState") { /* Do something */ }
Bake in your own caching if you want: you have access to any static structures you want here.

C#: is there a way to access the name of the current field?

In C#, I am defining a static field of a specific class. From within the class, I want to be able to display the name of the static field, pretty much like this:
public class Unit {
public string NameOfField { get { return ...; } }
}
public static Unit Hectare = new Unit();
If I now access:
Hectare.NameOfField
I want it to return:
Hectare
I know there is a static function System.Reflection.MethodBase.GetCurrentMethod(), but as far as I can tell there is no way to get the name of the instance containing this current method?
There is also the System.RuntimeFieldHandle structure, but I have not been able to identify any GetCurrentFieldHandle() method.
I am not sure if I am missing something obvious?
Any help on this is very much appreciated.
You should not count on variable names in you developments as they do not exits at runtime.
It's better to initialize Unit with a name directly:
public class Unit {
public Unit(string name)
{
NameOfField = name;
}
public string NameOfField { get; private set;} }
}
public static Unit Hectare = new Unit("Hectare");
Only way around this will be to store that information in the class:
public static Unit Hectare = new Unit("Hectare");
When your code is compiled all variable names are lost and replaced by internal references. There is no way to get that name again.
You can use Reflection to obtain class Fields and properties. Like below:
Suppose you have class with one property:
class Test
{
public static string MySupperField
{
get
{
return "Some symbols here";
}
}
}
......
You can read the property name in such way:
public string[] GetClassStaticNames(Type T)
{
string[] names;
System.Reflection.PropertyInfo[] props = T.GetProperties(); // This will return only properties not fields! For fields obtaining use T.GetFields();
names = new string[props.Count()];
for (int i = 0; i < props.Count(); i++)
{
names[i] = props[i].Name;
}
return names;
}
Hope this will help.
[EDIT]
Returning to your question - No you cant obtain name of current variable.
What you are asking about cant be done because of classes nature, they are objects in memory and reference to one object can be held in many variables, and when you are requesting value of instance field or property it will be actually performed operation with object in memory not with variable wich holds reference to that object. So obtaining name of variable wich holds reference to current instance have no sence
Thanks everyone who has taken the time to answer and discuss my question.
Just to let you know, I have implemented a solution that is sufficient for my needs. The solution is not general, and it has some pitfalls, but I'd thought I share it anyway in case it can be of help to someone else.
This is in principle what the class that is used when defining fields looks like:
public class Unit : IUnit {
public NameOfField { get; set; }
...
}
As you can see, the class implements the IUnit interface, and I have provided a public setter in the NameOfField property.
The static fields are typically defined like this within some containing class:
public static Unit Hectare = new Unit();
My solution is to set the NameOfField property through reflection before the field is used in the implementation.
I do this through a static constructor (that of course needs to be invoked before the Unit fields are accessed.
I use Linq to traverse the executing assembly for the relevant fields, and when I have detected these fields (fields which type implements the IUnit interface), I set the NameOfField property for each of them using the Any extension method:
Assembly.GetExecutingAssembly().GetTypes().
SelectMany(type => type.GetFields(BindingFlags.Public | BindingFlags.Static)).
Where(fieldInfo => fieldInfo.FieldType.GetInterfaces().Contains(typeof(IUnit))).
Any(fieldInfo =>
{
((IUnit)fieldInfo.GetValue(null)).NameOfField= fieldInfo.Name;
return false;
});
There are some shortcomings with this approach:
The static constructor has to be invoked through manual intervention before any Unit fields can be accessed
The NameOfField setter is public. In my case this is no problem, but it might be when applied in other scenarios. (I assume that the setter could be made private and invoked through further reflection, but I have not taken the time to explore that path further.)
... ?
Either way, maybe this solution can be of help to someone else than me.

How to create tests for poco objects

I'm new to mocking/testing and wanting to know what level should you go to when testing. For example in my code I have the following object:
public class RuleViolation
{
public string ErrorMessage { get; private set; }
public string PropertyName { get; private set; }
public RuleViolation( string errorMessage )
{
ErrorMessage = errorMessage;
}
public RuleViolation( string errorMessage, string propertyName )
{
ErrorMessage = errorMessage;
PropertyName = propertyName;
}
}
This is a relatively simple object. So my question is:
Does it need a unit test?
If it does what do I test and how?
Thanks
it doesn't contain any logic => nothing to test
I would say probably not. The only thing that you would probably want to verify if it is extremely important are the access modifiers:
public string ErrorMessage { get; private set; }
public string PropertyName { get; private set; }
If it is really really important that code outside the class cannot modify them that might be the only thing I would try and verify.
Here is how you can get the accessors in a property:
class Program
{
static void Main(string[] args)
{
var property = typeof(Test).GetProperty("Accessor");
var methods = property.GetAccessors();
}
}
public class Test
{
public string Accessor
{
get;
private set;
}
}
With the property.GetAccessors();
You can see if the setter is there. If it is, then the setter is public. (There is also properties IsPrivate and IsPublic you can use to verify the other Accessors as well).
If it were my code and my object I would have tests for it, no matter how simple or complicated the class is, period. Even if the class seems unlikely to break, tests are where, IMO, you document your assumptions, design decisions, and proper usage.
By doing so, you not only validate that what you have works as intended, but you have the opportunity to think through typical scenarios (what happens if the ctor params are null or empty or have white space at the end? Why is the PropertyName optional in an immutable class?).
And IF (when?) requirements change you have a solid starting point for addressing that. And IF this trivial class somehow doesn't interact nicely with all of the other classes, you may have a test to catch that before your customers do.
It's just the right way to engineer your code.
HTH,
Berryl
You could unit test this object, but it's so simple as to not require it. The test would be something like (NUnit example)
[Test]
public void TestRuleViolationConstructorWithErrorMessageParameterSetsErrorMessageProperty() {
// Arrange
var errorMessage = "An error message";
// Act
var ruleViolation = new RuleViolation(errorMessage);
// Assert
Assert.AreEqual(errorMessage, ruleViolation.ErrorMessage);
}
There's little value to writing tests like these, however, as you are testing that the .NET framework's properties work correctly. Generally you can trust Microsoft to have got this right :-)
Regarding mocking, this is useful when your class under test has a dependency, perhaps on another class in your own application, or on a type from a framework. Mocking frameworks allow you call methods and properties on the dependecy without going to the trouble of building the dependency concretely in code, and instead allow you to inject defined values for properties, return values for methods, etc. Moq is an excellent framework, and a test for a basic class with dependency would look something like this:
[Test]
public void TestCalculateReturnsBasicRateTaxForMiddleIncome() {
// Arrange
// TaxPolicy is a dependency that we need to manipulate.
var policy = new Mock<TaxPolicy>();
bar.Setup(x => x.BasicRate.Returns(0.22d));
var taxCalculator = new TaxCalculator();
// Act
// Calculate takes a TaxPolicy and an annual income.
var result = taxCalculator.Calculate(policy.Object, 25000);
// Assert
// Basic Rate tax is 22%, which is 5500 of 25000.
Assert.AreEqual(5500, result);
}
TaxPolicy would be unit tested in its own fixture to verify that it behaves correctly. Here, we want to test that the TaxCalculator works correctly, and so we mock the TaxPolicy object to make our tests simpler; in so doing, we can specify the behaviour of just the bits of TaxPolicy in which we're interested. Without it, we would need to create hand-rolled mocks/stubs/fakes, or create real instances of TaxPolicy to pass around.
There's waaaaay more to Moq than this, however; check out the quick-start tutorial to see more of what it can do.
Even if simple, there's logic in your constructors. I would test that:
RuleViolation ruleViolation = new RuleViolation("This is the error message");
Assert.AreEqual("This is the error message", ruleViolation.ErrorMessage);
Assert.IsEmpty(ruleViolation.PropertyName);
RuleViolation ruleViolation = new RuleViolation("This is the error message", "ThisIsMyProperty");
Assert.AreEqual("This is the error message", ruleViolation.ErrorMessage);
Assert.AreEqual("ThisIsMyProperty", ruleViolation.PropertyName);

Categories