NUnit AreEqual always returns false - unit-testing

I'm sure I missing something simple here but I can't figure out why my NUnit object comparison test continues to fail.
I have a simple object:
public virtual int Id { get; private set; }
public virtual string Description { get; set; }
public virtual string Address { get; set; }
public virtual string Ports { get; set; }
public virtual string Password { get; set; }
public virtual ServerGroup ServerGroup { get; set; }
I am persisting an instance of this object to my database and then fetching it out using NHibernate. My NUnit unit test compares the object saved to the object retrieved and compares them. I understand that AreSame() would fail as they are not the same reference to an object but I would expect that AreEqual() pass.
If I debug the test I can see that both objects appear to have the same values in these properties my test still fails. Can someone tell me why?
Thanks!

You have to override Equals() method on your class. Otherwise NUnit will use the base implementation, which compares references (which is certainly not what you are after here)

As suggested you need to override Equals. You do need to be aware of the side effects.
You should also override GetHashCode or you could end up with objects where .Equals will be true, but using your Id class as the key in a Dictionary the hash would not match resulting in multiple entries with "Equal" Ids.
Also, you would need to override the == and != operators to maintain consistent behavior.
Imagine the confusion if .Equals were true but == were false.

You do need to override Equals as Grzenio suggests, but watch out for a subtle source of confusion that can occur with NHibernate. Specifically, when lazy loading is enabled, a type comparison test can fail. To illustrate, here is a piece of a well written Equals method:
// override object.Equals
public override bool Equals(object obj)
{
//
// See the full list of guidelines at
// http://go.microsoft.com/fwlink/?LinkID=85237
// and also the guidance for operator== at
// http://go.microsoft.com/fwlink/?LinkId=85238
//
if (GetType() != obj.GetType())
{
return false;
}
....
}
But when lazy loading is enabled, the way NHib works is to generate a proxy of the actual object (thereby deferring unnecessary database hits). If an equality check is made between one object that has been 'proxified' by NHib and another that hasn't been, it will fail because of the mismatch in Types. The solution (courtesy of the S#arp Architecture project, is to modify the type test to be something like this:
public override bool Equals(object obj) {
...
if (GetType() != obj.GetTypeUnproxied())
{
return false;
}
...
}
protected virtual Type GetTypeUnproxied() { return GetType(); }
This effectively returns the type of the underlying object in all cases, even when the compareTo object is a NHib proxy.
An Equals method can be as tricky as it is important to get just right, so ideally you can factor that into some sort of Layer Supertype (Fowler). Lots of open source projects, including the S#arp one I mentioned earlier, provide examples of how to do this.
HTH,
Berryl

Related

FakeItEasy - How to verify nested arguments value C#

I need your help in order to find a way of verifying the value of nested objects passed as a parameter of the method under test invocation.
Assume this class:
public class AuditTrailValueObject
{
public ActionType Action { get; private set; }
public EntityType EntityType { get; private set; }
public long EntityId { get; private set; }
public DateTime StartTime { get; private set; }
public bool IsSuccess { get; private set; }
public string Remarks { get; private set; }
public AuditTrailValueObject(ActionType action, EntityType entityType, long entityId, DateTime startTime, bool isSuccess, string remarks = "")
{
Action = action;
EntityType = entityType;
EntityId = entityId;
StartTime = startTime;
IsSuccess = isSuccess;
Remarks = remarks;
}
}
And the following interface has this class as an injected dependency:
public interface IAuditTrailService
{
void WriteToAuditTrail(AuditTrailValueObject auditParamData);
}
Now I have the ScanService depending on the AuditTrailService (which implements IAuditTrailService):
public long CreateScanRequest(long projectId)
{
ScanRequestWriteModel scanRequest = _scanRequestWriteModelFactory.Create(projectDetails);
long scanRequestId = _scanRequestsWriteRepository.Insert(scanRequest);
_auditTrailService.WriteToAuditTrail(new AuditTrailValueObject(ActionType.Run, EntityType.SastScanRequest, scanRequestId, DateTime.UtcNow, true));
return scanRequestId;
}
The test I've written:
[TestMethod]
public void Scan_GivenProjectId_ShouldAuditSuccess()
{
//Given
var projectId = 100;
var scanService = CreateScanService();
...
A.CallTo(() => _scanRequestWriteModelFactory.Create(projectDetails)).Returns(new ScanRequestWriteModel());
A.CallTo(() => _scanRequestsWriteRepository.Insert(A<ScanRequestWriteModel>._)).Returns(1);
//When
var scanRequestId = scanService.CreateScanRequest(projectId);
//Then
A.CallTo(() => _auditTrailService.WriteToAuditTrail(
new AuditTrailValueObject(ActionType.Run, EntityType.SastScanRequest, scanRequestId, A<DateTime>._, true, A<string>._))).MustHaveHappened();
}
When running this test I'm getting:
System.InvalidCastException: Specified cast is not valid
How can I verify the value of a nested parameter in AuditTrailValueObject?
#tom redfern makes many good points, which you may want to address. But after rereading your code and comments, I think I an immediate way forward. Your code has at least one problem, and it may have another.
Let's look at
A.CallTo(() => _auditTrailService.WriteToAuditTrail(
new AuditTrailValueObject(ActionType.Run,
EntityType.SastScanRequest,
scanRequestId,
A<DateTime>._,
true
A<string>._)))
.MustHaveHappened();
The _ constructs are being used here inside the AuditTrailValueObject constructor, and they are not valid there. They'll result in default values being assigned to the AuditTrailValueObject, (DateTime.MinValue and null, I think), and are almost not what you want. if you extract the new out to the previous line, you'll see FakeItEasy throw an error when _ is used. I think that it should do a better job of helping you find the problem in your code, but I'm not sure it's possible. I've created FakeItEasy Issue 1177 -
Argument constraint That, when nested deeper in A.CallTo, misreports what's being matched to help FakeItEasy improve.
Related to this is how FakeItEasy matches objects. When provided with a value to compare, (the result of new AuditTrailValueObject(…)) FakeItEasy will use Equals to compare the object against the received parameter. Unless your AuditTrailValueObject has a good Equals, this will fail.
If you want to keep using AuditTrailValueObject and don't want to provide an Equals (that would ignore the startTime and the remarks), there are ways forward.
First, you could use That.Matches, like so:
A.CallTo(() => _auditTrailService.WriteToAuditTrail(A<AuditTrailValueObject>.That.Matches(
a => a.Action == ActionType.Run &&
a.EntityType == EntityType.SastScanRequest &&
a.EntityId == scanRequestId &&
a.IsSuccess)))
.MustHaveHappened();
Some people aren't wild about complex constraints in the Matches, so an alternative is to capture the AuditTrailValueObject and interrogate it later, as Alex James Brown has described in his answer to Why can't I capture a FakeItEasy expectation in a variable?.
Your problem is a symptom of a larger problem: you are trying to do too much with one test.
Because you're newing-up an instance of AuditTrailValueObject in your WriteToAuditTrail() method, you will have no means of accessing this object instance as it is created within the method scope and is therefore immune to inspection.
However, it appears that the only reason you wish to access this object in the first place is so that you can verify that the values being set within it are correct.
Of these values, only one (as far as your code sample allows us to know) is set from within the calling method. This is the return value from the call made to _scanRequestsWriteRepository.Insert(), which should be the subject of its own unit test where you can verify correct behaviour independently of where it is being used.
Writing this unit test (on the _scanRequestsWriteRepository.Insert() method) will actually address the underlying cause of your problem (that you are doing too much with a single test). Your immediate problem, however, still needs to be addressed. The simplest way of doing this is to remove the AuditTrailValueObject class entirely, and just pass your arguments directly to the call to WriteToAuditTrail().
If I'll remove AuditTrailValueObject where the place should I verify
what params are being passed to the auditTrailService? What I mean is
that also if I've tested the auditTrailService I need to know that
scan service call if with the right parameters (for example: with
ActionType.Run and not with ActionType.Update).
To verify that the correct parameters have been passed to the call to WriteToAuditTrail() you can inject a fake of IAuditTrailService and verify your call has happened:
A.CallTo(
() => _auditTrailService.WriteToAuditTrail(
ActionType.Run,
EntityType.SastScanRequest,
scanRequestId,
myDateTime,
true,
myString)
).MustHaveHappened();

DDD with webservices DTO as value object: how to handle them?

I have a "MyUnits" application that let's manage Units (like meters, kilograms, pounds, miles, km/h...). The model is complex, it supports unit compatibilities, operations, conversions, etc.
I have another application (MyApp) that will need to use "units", so I want to make it use my "Units" application.
What I thought is to have a "Units" service (webservice) UnitService that consumes and returns a Unit DTO UnitDTO.
In MyApp, I have this model:
Operand
value: float
unit: UnitDTO
OperationAdd
operand1: Operand
operand2: Operand
execute()
The problem: in OperationAdd.execute(), I need to check that units are compatibles (for example).
So either:
UnitDTO has a method that will call UnitService::areCompatible, but that is wrong! How a DTO (that should only contain data) knows UnitService which is a webservice! It shouldn't
OperationAdd.execute() calls UnitService::areCompatible, but that is wrong! How OperationAdd (an entity) knows UnitService which is a webservice! It shouldn't
or I have a OperationService that does the work (and that can call services) but my Operation entities would be like data containers, entities with no methods, and that's not really what DDD is about
I don't want anemic entities, but in the case where I have an entity that uses a service, how can I do?
And: am I wrong thinking that UnitDTO can be used as a VO?
An Unit should "advertise" its compatibilities. I don't know if the language you're using supports generics but I would do it this way.
First of all, the UnitDto contains state for some Unit. Use UniDto to create the concrete Unit (which btw is a VO). Each Unit should know its compatibilities.UnitDTO should only be a DTO , create other VO that will do the work.
C#
public class UnitBase
{
public virtual bool IsCompatible(UnitBase unit)
{
return false;
}
}
public interface ICompatible<T>
{
bool IsCompatible(T unit);
}
public class UnitFeet {}
public class UnitMeter:UnitBase,ICompatible<UnitFeet>
{
bool IsCompatible(UnitFeet unit) { return true;}
}
public override bool IsCompatible(UnitBase unit)
{
return IsCompatible((UnitFeet)unit);
}
The compiler should chose the right overload depending on the compared unit. Also the ICompatbile interface can have conversion methods from one unit to another. But let's suppose you want things more abstract
public class OperandValue:ICompatbile<OperandValue>
{
public decimal Value {get;set;}
public UnitBase Unit {get;set;}
public bool IsCompatbile(OperandValue other)
{
return Unit.IsCompatbile(other.Unit);
}
public static OperandValue FromDto(Operand data)
{
return new OperandValue(data.Value,UnitBase.FromDto(data.Unit));
}
}
OperandValue first=OperandValue.FromDto(operand1);
OperandValue second=OperandValue.FromDto(operand2);
if (first.IsCompatbile(second)){
OperationService.Add(first,second)
}
So you don't need a UnitService::AreCompatbile method, just a LOT of polymorphism and careful object design.

Are void return methods that change the state of their argument an anti-pattern?

Are methods that return void but change the state of their arguments (ie. provide a hidden or implicit return value) generally a bad practice?
I find them difficult to mock, which suggests they are possibly a sign of a bad design.
What patterns are there for avoiding them?
A highly contrived example:
public interface IMapper
{
void Map(SourceObject source, TargetObject target);
}
public class ClassUnderTest
{
private IMapper _mapper;
public ClassUnderTest(IMapper mapper)
{
_mapper = mapper;
}
public int SomeOperation()
{
var source = new SourceObject();
var target = new TargetObject();
_mapper.Map(source, target);
return target.SomeMappedValue;
}
}
Yes to some extend.
What you describe is a typical side effect. Side effects make programs hard to understand, because the information you need to understand isn't contained in the call stack. You need additional information, i.e. what methods got called before (and in what) order.
The solution is to program without side effects. This means you don't change variables, fields or anything. Instead you would return a new version of what you normally would change.
This is a basic principle of functional programming.
Of course this way of programming has it's own challenges. Just consider I/O.
Your code whould be a lot easier to test if you do this:
public interface IMapper
{
TargetObject Map(SourceObject source);
}
public class ClassUnderTest
{
private IMapper _mapper;
public ClassUnderTest(IMapper mapper)
{
_mapper = mapper;
}
public int SomeOperation(SourceObject source )
{
var target = _mapper.Map(source, target);
return target.SomeMappedValue;
}
}
You can now test you Map opperation and SomeOperation seperatly. The problem is that you idd change the state of an object which makes it hard to provide a stub for testing. When returning the new object you are able to return a test stub of the target and test your caller method.

Partial Mock or new class or what else?

I have a question about testing.
I have a class that returns anomalies. in this class I have two different method that simply returns two different types of anomalies and one that return all anomalies (of both types)
this is the example code:
public interface IAnomalyService
{
IList<Anomaly> GetAllAnomalies(object parameter1, object parameter2);
IList<Anomaly> GetAnomalies_OfTypeA(object parameter1);
IList<Anomaly> GetAnomalies_OfTypeB(object parameter2);
}
public class AnomalyService : IAnomalyService
{
public IList<Anomaly> GetAllAnomalies(object parameter1, object parameter2)
{
var lstAll = new List<Anomaly>();
lstAll.AddRange(GetAnomalies_OfTypeA(parameter1));
lstAll.AddRange(GetAnomalies_OfTypeB(parameter2));
return lstAll;
}
public IList<Anomaly> GetAnomalies_OfTypeA(object parameter1)
{
//some elaborations
return new List<Anomaly> { new Anomaly { Id = 1 } };
}
public IList<Anomaly> GetAnomalies_OfTypeB(object parameter2)
{
//some elaborations
return new List<Anomaly> { new Anomaly { Id = 2 } };
}
}
class Anomaly
{
public int Id { get; set; }
}
I've created the tests for the two method that retrieve the anomalies of type A and type B (GetAnomalies_OfTypeA and GetAnomalies_OfTypeB).
Now I want to test the function GetAllAnomalies but I'm not sure what I have to do.
I think I have to way for testing it:
1) declare GetAnomalies_OfTypeA and GetAnomalies_OfTypeB in class AnomalyService as virtual, make a mock of the Class AnomalyService, and using Moq I can set CallBase as true and mock the two method GetAnomalies_OfTypeA and GetAnomalies_OfTypeB.
2)move the method GetAllAnomalies in another class called AllAnomalyService (with interface IAllAnomalyService) and in its constructor I will pass an interface of IAnomalyService and after I can test the GetAllAnomalies mocking the IAnomalyService interface.
I'm new at unit testing, so I don't know which solution is better, if is one of the mines or another one.
Can you help me?
thank you
Luca
Mocking is a good tool when a class resists testing. If you have the source, mocking is often not necessary. Try this approach:
Create a factory which can return AnomalyServices with various, defined anomalies (only type A, only type B, both, none, only type C, ...)
Since the three types are connected in some way, you should check all three in each test. If only anomalies of type A are expected, you should check that GetAllAnomalies returns the same result as GetAnomalies_OfTypeA and GetAnomalies_OfTypeB returns an empty list.

Should class methods accept parameters or use class properties

Consider the following class
public class Class1
{
public int A { get; set; }
public int B { get; set; }
public int GetComplexResult()
{
return A + B;
}
}
In order to use GetComplexResult, a consumer of this class would have to know to set A and B before calling the method. If GetComplexResult accesses many properties to calculate its result, this can lead to wrong return values if the consumer doesn't set all the appropriate properties first. So you might write this class like this instead
public class Class2
{
public int A { get; set; }
public int B { get; set; }
public int GetComplexResult(int a, int b)
{
return a + b;
}
}
This way, a caller to GetComplexResult is forced to pass in all the required values, ensuring the expected return value is correctly calculated. But if there are many required values, the parameter list grows as well and this doesn't seem like good design either. It also seems to break the point of encapsulating A, B and GetComplexResult in a single class. I might even be tempted to make GetComplexResult static since it doesn't require an instance of the class to do its work. I don't want to go around making a bunch of static methods.
Are there terms to describe these 2 different ways of creating classes? They both seem to have pros and cons - is there something I'm not understanding that should tell me that one way is better than the other? How does unit testing influence this choice?
If you use a real-world example the answer becomes clearer.
public class person
{
public string firstName { get; set; }
public string lastName { get; set; }
public string getFullName()
{
return firstName + " " + lastName;
}
}
The point of an entity object is that it contains information about an entity, and can do the operations that the entity needs to do (based on the information it contains). So yes, there are situations in which certain operations won't work properly because the entity hasn't been fully initialized, but that's not a failure of design. If, in the real world, I ask you for the full name of a newborn baby who hasn't been named yet, that will fail also.
If certain properties are essential to an entity doing its job, they can be initialized in a constructor. Another approach is to have a boolean that checks whether the entity is in a state where a given method can be called:
while (person.hasAnotherQuestion()) {
person.answerNextQuestion();
}
A good design rule is to make sure that all constructors initializes objects to valid states and that all property setters and methods then enforces the valid state. This way there will never be any objects in invalid states.
If the default values for A and B, which is 0 is not a valid state that yields a valid result from GetComplexResult, you should a constructor that initialized A and B to valid a state.
If some of the fields are never allowed to be null then you would typically make them parameters to the class constructor. If you don't always have all of the required values available at once then using a builder class may be helpful.
For example:
public Builder {
private int a;
private int b;
public Class1 create() {
// some validation logic goes here
// to make sure we have everything and
// either fill in defaults or throw an error
// if needed
return new Class1(a, b)
}
public Builder a(int val) { a = val; }
public Builder b(int val) { b = val; }
}
This Builder can then be used as follows.
Class1 obj1 = new Builder().a(5).b(6).create();
Builder builder = new Builder();
// do stuff to find value of a
builder.a(valueOfA);
// do stuff to find value of b
builder.b(valueOfB);
// do more stuff
Class1 obj2 = builder.create();
Class2 obj3 = builder.create();
This design allows you to lock down the Entity classes to whatever degree is appropriate while still allowing for a flexible construction process. It also opens the door to customizing the construction process with other implementations without changing the entity class contract.