Ultimately I want to have an internal interface with a setter and a public one with a getter. The code that replicates this scenario is roughed below:
[TestMethod]
public void TestMethod3()
{
var fake1 = A.Fake<IInterface1>(a => a.Implements(typeof(IInterface2)));
string backingString = null;
IInterface2 fake2 = (IInterface2)fake1;
A.CallTo(fake1)
.Where(a => a.Method.Name.Equals("set_Property"))
.Invokes((string param) => { backingString = param; });
A.CallTo(fake1)
.Where(a => a.Method.Name.Equals("get_Property"))
.WithReturnType<string>().Returns(backingString); //doesn't work
A.CallTo(fake2)
.Where(a => a.Method.Name.Equals("set_Property"))
.Invokes((string param) => { backingString = param; });
A.CallTo(fake2)
.Where(a => a.Method.Name.Equals("get_Property"))
.WithReturnType<string>().Returns(backingString); //doesn't work
fake1.Property = "asdf";
Assert.AreEqual("asdf", fake1.Property); //fails -> fake1.Property is null
Assert.AreEqual(fake1.Property, fake2.Property); //fails -> fake2.Property is null
}
}
public interface IInterface1
{
string Property { get; set; }
}
public interface IInterface2
{
string Property { get; }
}
I could get as far as using backingString to store the setter, but when setting up the getter it doesn't work as I wanted it to.
I also tried something in the line of A.CallTo(() => fake1.Property).Returns(backingString) to no avail.
Would appreciate assistance of them experts :)
When you set up your
A.CallTo(fake1)
.Where(a => a.Method.Name.Equals("get_Property"))
.WithReturnType<string>().Returns(backingString);
(and similarly for fake2),
the value of backingString is null, so that's what's returned later on when you access the Property getter.
In order to return the value of backingString at the time the Property getter is called, you want ReturnsLazily.
Make this change in each place and the tests pass:
A.CallTo(fake1)
.Where(a => a.Method.Name.Equals("get_Property"))
.WithReturnType<string>().ReturnsLazily(() => backingString);
Related
I create ValidatableModelBase class and have some troubles. I need subscribe to SourceCache changes and cast Count collection to IObservable bool . How can i do it?
private readonly SourceCache<ValidationResult, string> _results;
public IObservalbe<bool> IsValid { get; }
public ValidatableModelBase()
{
_results = new SourceCach<ValidationResult, string>(x => x.PropertyName);
//Doesn't work. I think because i dont .Subscribe() to changes?
IsValid = _results.Connect().IsEmpty();
}
upd:
HasErrors = collection.CountChanged.Subscribe(x => {Count = x;});
IsValid = this.WhenAnyValie(x => x.HasErrors).Select(x => x == 0);
You can do something like this:
var databasesValid = collectionOfReactiveObjects
.Connect().Count().Select(x => x == 0);
// Then you can convert that IObservable<bool> to a view model
// property declared as ObservableAsPropertyHelper<bool>.
_databasesValid = databasesValid.ToProperty(this, x => x.DatabasesValid);
You'll need to include the DynamicData.Aggregation namespace.
See https://github.com/reactiveui/DynamicData/blob/63960b0fa7bd0362c40e137498cd0014ba02f3dc/src/DynamicData/Aggregation/CountEx.cs#L57 here for code reference.
I want to map 2 objects based on a condition, if true mapp else ignore, the condition is not a part of source neither destination
var mapperconfig = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>()
.ForMember(source => source.Titulaires,
opt => opt.Condition(titulaires.HasValue && titulaires == true));
....
});
the extension method Condition() accepts just a type related to source or destination.
AutoMapper allows you to add conditions to properties that must be met before that property will be mapped.
Eg.
public class Foo
{
public int baz;
}
public class Bar
{
public uint baz;
}
public class Program
{
public static void Main()
{
Mapper.CreateMap<Foo,Bar>().ForMember(dest => dest.baz, opt => opt.Condition(src => (src.baz >= 0)));
var foo1 = new Foo { baz=-1 };
var bar1 = Mapper.Map<Bar>(foo1);
Console.WriteLine("bar1.baz={0}", bar1.baz);
var foo2 = new Foo{ baz=100 };
var bar2 = Mapper.Map<Bar>(foo2);
Console.WriteLine("bar2.baz={0}", bar2.baz);
}
}
Also, they give Preconditions functionality
See this link Conditional Mapping
thank you all for your help, I find a way to test my conditions into my automapper configuration : MapperConfiguration mappConf = new MapperConfiguration(config => {
config.CreateMap()
.ForMember(destination => destination.member, option => option.Condition(item => _condition == true))........});
I have this abstract class
public abstract class DisposableList<T> : List<T>, IDisposable
{
protected DisposableList();
public virtual void Dispose();
}
and this Interface
public interface IGroup : IDisposable
{
string Name { get; }
}
I need to test this method
public class MyClass
{
public void MyMethod(IConnection connection)
{
var groups = connection.GetGroups();
var grps = groups.ToDictionary(x => x?.Name); //Here gets System.NullReference exception
}
}
In testing, so far what I did is:
var group1 = new Mock<IGroup>();
group1.SetupGet(c => c.Name).Returns("abc");
var groups = new Mock<DisposableList<IGroup>>();
groups.Object.Add(group1.Object);
Mock<IConnection> connection.Setup(c => c.GetGroups()).Returns(() => groups.Object);
new MyClass().MyMethod(connection);
but var grps = groups.ToDictionary(x => x?.Name); gets System.NullReferenceException: 'Object reference not set to an instance of an object.'
Name is not null and groups is not null. Something happens inside.
how can I fix this?
You can't set null value as dictionary key like this; (It is possible to be null)
groups.ToDictionary(x => x?.Name);
Eliminate the items which is null or has null Name value.
groups.Where(x => x != null && !string.IsNullOrEmpty(x.Name)).ToDictionary(x => x.Name);
Suppose a mapping using AutoMapper like bellow:
mapItem.ForMember(to => to.SomeProperty, from =>
{
from.Condition(x => ((FromType)x.SourceValue).OtherProperty == "something");
from.MapFrom(x => x.MyProperty);
});
What's difference of substitute Condition by PreCondition:
from.PreCondition(x => ((FromType)x.SourceValue).OtherProperty == "something");
What's the practical difference between this two methods?
The diference is that PreCondition is executed before acessing the source value and also the Condition predicate, so in this case, before get the value from MyProperty the PreCondition predicate will run, and then the value from property is evaluated and finally Condition is executed.
In the following code you can see this
class Program
{
static void Main(string[] args)
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Person, PersonViewModel>()
.ForMember(p => p.Name, c =>
{
c.Condition(new Func<Person, bool>(person =>
{
Console.WriteLine("Condition");
return true;
}));
c.PreCondition(new Func<Person, bool>(person =>
{
Console.WriteLine("PreCondition");
return true;
}));
c.MapFrom(p => p.Name);
});
});
Mapper.Instance.Map<PersonViewModel>(new Person() { Name = "Alberto" });
}
}
class Person
{
public long Id { get; set; }
private string _name;
public string Name
{
get
{
Console.WriteLine("Getting value");
return _name;
}
set { _name = value; }
}
}
class PersonViewModel
{
public string Name { get; set; }
}
The output from this program is:
PreCondition
Getting value
Condition
Because the Condition method contains a overload that receives a ResolutionContext instance, that have a property called SourceValue, the Condition evaluate the property value from source, to set the SourceValue property on ResolutionContext object.
ATTENTION:
This behavior work properly until version <= 4.2.1 and >= 5.2.0.
The versions between 5.1.1 and 5.0.2, the behavior is not working properly anymore.
The output in those versions is:
Condition
PreCondition
Getting value
I have an object lets call it ObjectA
and that object has 10 properties and those are all strings.
var myObject = new {Property1="",Property2="",Property3="",Property4="",...}
is there anyway to check to see whether all these properties are null or empty?
So any built-in method that would return true or false?
If any single of them is not null or empty then the return would be false. If all of them are empty it should return true.
The idea is I do not want to write 10 if statement to control if those properties are empty or null.
Thanks
You can do it using Reflection
bool IsAnyNullOrEmpty(object myObject)
{
foreach(PropertyInfo pi in myObject.GetType().GetProperties())
{
if(pi.PropertyType == typeof(string))
{
string value = (string)pi.GetValue(myObject);
if(string.IsNullOrEmpty(value))
{
return true;
}
}
}
return false;
}
Matthew Watson suggested an alternative using LINQ:
return myObject.GetType().GetProperties()
.Where(pi => pi.PropertyType == typeof(string))
.Select(pi => (string)pi.GetValue(myObject))
.Any(value => string.IsNullOrEmpty(value));
I suppose you want to make sure that all properties are filled in.
A better option is probably by putting this validation in the constructor of your class and throw exceptions if validation fails. That way you cannot create a class that is invalid; catch exceptions and handle them accordingly.
Fluent validation is a nice framework (http://fluentvalidation.codeplex.com) for doing the validation. Example:
public class CustomerValidator: AbstractValidator<Customer>
{
public CustomerValidator()
{
RuleFor(customer => customer.Property1).NotNull();
RuleFor(customer => customer.Property2).NotNull();
RuleFor(customer => customer.Property3).NotNull();
}
}
public class Customer
{
public Customer(string property1, string property2, string property3)
{
Property1 = property1;
Property2 = property2;
Property3 = property3;
new CustomerValidator().ValidateAndThrow();
}
public string Property1 {get; set;}
public string Property2 {get; set;}
public string Property3 {get; set;}
}
Usage:
try
{
var customer = new Customer("string1", "string", null);
// logic here
} catch (ValidationException ex)
{
// A validation error occured
}
PS - Using reflection for this kind of thing just makes your code harder to read. Using validation as shown above makes it explicitly clear what your rules are; and you can easily extend them with other rules.
The following code returns if any property is not null.
return myObject.GetType()
.GetProperties() //get all properties on object
.Select(pi => pi.GetValue(myObject)) //get value for the property
.Any(value => value != null); // Check if one of the values is not null, if so it returns true.
Here you go
var instOfA = new ObjectA();
bool isAnyPropEmpty = instOfA.GetType().GetProperties()
.Where(p => p.GetValue(instOfA) is string) // selecting only string props
.Any(p => string.IsNullOrWhiteSpace((p.GetValue(instOfA) as string)));
and here's the class
class ObjectA
{
public string A { get; set; }
public string B { get; set; }
}
A slightly different way of expressing the linq to see if all string properties of an object are non null and non empty:
public static bool AllStringPropertyValuesAreNonEmpty(object myObject)
{
var allStringPropertyValues =
from property in myObject.GetType().GetProperties()
where property.PropertyType == typeof(string) && property.CanRead
select (string) property.GetValue(myObject);
return allStringPropertyValues.All(value => !string.IsNullOrEmpty(value));
}
Note if you've got a data structural hierarchy and you want to test everything in that hierarchy, then you can use a recursive method. Here's a quick example:
static bool AnyNullOrEmpty(object obj) {
return obj == null
|| obj.ToString() == ""
|| obj.GetType().GetProperties().Any(prop => AnyNullOrEmpty(prop.GetValue(obj)));
}
To only check if all properties are null:
bool allPropertiesNull = !myObject.GetType().GetProperties().Any(prop => prop == null);
you can use reflection and extension methods to do this.
using System.Reflection;
public static class ExtensionMethods
{
public static bool StringPropertiesEmpty(this object value)
{
foreach (PropertyInfo objProp in value.GetType().GetProperties())
{
if (objProp.CanRead)
{
object val = objProp.GetValue(value, null);
if (val.GetType() == typeof(string))
{
if (val == "" || val == null)
{
return true;
}
}
}
}
return false;
}
}
then use it on any object with string properties
test obj = new test();
if (obj.StringPropertiesEmpty() == true)
{
// some of these string properties are empty or null
}
No, I don't think there is a method to do exactly that.
You'd be best writing a simple method that takes your object and returns true or false.
Alternatively, if the properties are all the same, and you just want to parse through them and find a single null or empty, perhaps some sort of collection of strings would work for you?
You can try the following query :
if the object is "referenceKey" (where few properties may be null )
referenceKey.GetType().GetProperties().Where(x => x.GetValue(referenceKey) == null)
I need to count the properties where the value is set to not Null, so I have used the following query :
var countProvidedReferenceKeys = referenceKey.GetType().GetProperties().Where(x => x.GetValue(referenceKey) != null).Count();