How do I test "Parameters Passed In Final Call" using RhinoMocks? - rhino-mocks

What's the best way in Rhino Mocks to test that a particular parameter is passed on the FINAL call to a method? Eg mockview.SetSomething(myObj) might be called any number of times by mockview.Init, but I want to test that the last time it's called as mockview.SetSomething(inParticular).
Now I know I can use GetArgumentsForCallsMadeOn with this, but my problem is that it doesn't work if I've subsequently changed the parameter holding variable. e.g
public interface IView
{
void SetSomething(ViewData data);
}
public class ViewData
{
public int Age { get; set; }
public string Name { get; set; }
public ViewData Person(int age, string name)
{
Age = age;
Name = name;
return (this);
}
}
public class WorkingPresenter
{
public void Init(IView view)
{
var data = new ViewData {Age = 1, Name = "One"};
view.SetSomething(data);
data = new ViewData {Age = 2, Name = "Two"};
view.SetSomething(data);
data = new ViewData {Age = 3, Name = "Three"};
}
}
public class NotWorkingPresenter
{
private ViewData _data;
public void Init(IView view)
{
_data = new ViewData();
view.SetSomething(_data.Person(1, "One"));
view.SetSomething(_data.Person(2, "Two"));
_data.Person(3, "Three");
}
}
then my tests are ...
[Test]
public void GetDataOfLastCall()
{
ViewData dummydata=null;
var view = MockRepository.GenerateStub<IView>();
//Approach 1 : This works
var workingPresenter = new WorkingPresenter();
workingPresenter.Init(view);
var lastCall = view.GetArgumentsForCallsMadeOn(v => v.SetSomething(dummydata)).Count - 1;
var lastParams = view.GetArgumentsForCallsMadeOn(v => v.SetSomething(dummydata))[lastCall];
var lastData = (ViewData)lastParams[0];
//Approach 2: This doesn't
var notWorkingPresenter = new NotWorkingPresenter();
notWorkingPresenter.Init(view);
lastCall = view.GetArgumentsForCallsMadeOn(v => v.SetSomething(dummydata)).Count - 1;
lastParams = view.GetArgumentsForCallsMadeOn(v => v.SetSomething(dummydata))[lastCall];
lastData = (ViewData)lastParams[0];
What I want is to verify that the last call to SetSomething was with {name="Two", age=2}. Now workingPresenter does this but wouldn't you expect notWorkingPresenter to do so too?

There must be something else going on in your code (outside of the mocking). I just threw together a few items:
public interface IView
{
void SetSomething(ViewData data);
}
public class ViewData
{
public int Age { get; set; }
public string Name { get; set; }
}
And I tested it with:
[TestMethod]
public void GetDataOfLastCall()
{
var view = MockRepository.GenerateStub<IView>();
var data = new ViewData {Age = 1, Name = "One"};
view.SetSomething(data);
data = new ViewData { Age = 2, Name = "Two" };
view.SetSomething(data);
data = new ViewData { Age = 3, Name = "Three" };
var lastCall = view.GetArgumentsForCallsMadeOn(v => v.SetSomething(data)).Count - 1;
var lastParams = view.GetArgumentsForCallsMadeOn(v => v.SetSomething(data))[lastCall];
var lastData = (ViewData) lastParams[0];
}
And I got the values of 2 and "Two" inside the ViewData. It appears Rhino.Mocks supports what you want to do. Could you create a failing test case that shows the issue identified in your original question (where you got a reference to the most recent information)?

Related

Autocad.net Save complex Object

I'm working on a project in AutoCAD using c#, my application data is stored in complex objects
(String, double, objectId, arrays, list...) and I would like to save data for later using (serialize or saved in AutoCAD drawing) and if I re-open AutoCAD and reload my project, I can find all data in my object
Sorry for my English
So You need to use XData.
Details and sample You can find here:
https://www.keanw.com/2007/04/adding_xdata_to.html
You could serialize your class into a binary stream and then you can save it in the drawing as a bunch of binary chunks (see this topic)
But most of the time you should directly store data in Xrecords of a DBDictionary.
public abstract class RecordableObject
{
protected ObjectId dictionaryId;
protected Database database;
public string Key { get; }
protected RecordableObject(string key, Database db = null)
{
database = db ?? HostApplicationServices.WorkingDatabase;
Key = key;
using (var tr = database.TransactionManager.StartOpenCloseTransaction())
{
var NOD = (DBDictionary)tr.GetObject(database.NamedObjectsDictionaryId, OpenMode.ForRead);
DBDictionary dictionary;
if (NOD.Contains(Key))
{
dictionaryId = NOD.GetAt(Key);
}
else
{
NOD.UpgradeOpen();
dictionary = new DBDictionary();
dictionaryId = NOD.SetAt(Key, dictionary);
tr.AddNewlyCreatedDBObject(dictionary, true);
}
tr.Commit();
}
}
public abstract void SavePropertiesToDictionary();
public abstract void SetPropertiesFromDictionary();
protected void SaveData(string key, params TypedValue[] values)
{
using (var tr = database.TransactionManager.StartOpenCloseTransaction())
{
var dictionary = (DBDictionary)tr.GetObject(dictionaryId, OpenMode.ForRead);
Xrecord xrecord;
if (dictionary.Contains(key))
{
xrecord = (Xrecord)tr.GetObject(dictionary.GetAt(key), OpenMode.ForWrite);
}
else
{
xrecord = new Xrecord();
dictionary.UpgradeOpen();
dictionary.SetAt(key, xrecord);
tr.AddNewlyCreatedDBObject(xrecord, true);
}
xrecord.Data = new ResultBuffer(values);
tr.Commit();
}
}
protected T GetData<T>(string key)
{
using (var tr = database.TransactionManager.StartOpenCloseTransaction())
{
var dictionary = (DBDictionary)tr.GetObject(dictionaryId, OpenMode.ForRead);
if (dictionary.Contains(key))
{
var xrecord = (Xrecord)tr.GetObject(dictionary.GetAt(key), OpenMode.ForRead);
if (xrecord.Data != null)
return (T)xrecord.Data.AsArray()[0].Value;
}
return default;
}
}
protected T[] GetDataArray<T>(string key)
{
using(var tr = database.TransactionManager.StartOpenCloseTransaction())
{
var dictionary = (DBDictionary)tr.GetObject(dictionaryId, OpenMode.ForRead);
if (dictionary.Contains(key))
{
var xrecord = (Xrecord)tr.GetObject(dictionary.GetAt(key), OpenMode.ForRead);
if (xrecord.Data != null)
return xrecord.Data.AsArray().Select(tv => (T)tv.Value).ToArray();
}
return default;
}
}
}
Derived class example:
public class RecordableExample : RecordableObject
{
public double Size { get; set; }
public ObjectId ObjectId { get; set; }
public int[] Ints { get; set; }
public RecordableExample(string key, Database db = null) : base(key, db) { }
public override void SavePropertiesToDictionary()
{
SaveData(nameof(Size), new TypedValue((int)DxfCode.Real, Size));
SaveData(nameof(ObjectId), new TypedValue((int)DxfCode.Handle, ObjectId.Handle));
if (Ints != null)
SaveData(nameof(Ints), Ints.Select(i => new TypedValue((int)DxfCode.Int32, i)).ToArray());
}
public override void SetPropertiesFromDictionary()
{
Size = GetData<double>(nameof(Size));
Ints = GetDataArray<int>(nameof(Ints));
var handle = new Handle(Convert.ToInt64(GetData<string>(nameof(ObjectId))));
if (database.TryGetObjectId(handle, out var id))
ObjectId = id;
}
}

Using NUnit testing with C# Collection Class Library project

/Using NUnit testing with C# Collection Class Library project
I am not able to figure out the TestFixture in this code
any help will be a great help
I have a below Test Class/
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using ScoringExercise;
using ScoringExercise.Entities;
namespace ScoringExerciseTests
{
[TestFixture]
public class ScoringTests
{
readonly List<MultiChoiceItem> _assessmentItems;
public ScoringTests()
{
// Assessment items
_assessmentItems = new List<MultiChoiceItem>
{
new MultiChoiceItem()
{
ItemText = "Which city is the capital of Sweden?",
Options = new string[] {"Helsinki", "Stockholm", "Malmö", "Oslo"},
CorrectAnswerIndex = 1,
MarksAwardedIfCorrect = 1
},
new MultiChoiceItem()
{
ItemText = "Which of these cheeses normally has large round holes?",
Options = new string[] {"Emmental", "Feta", "Danish Blue", "Gruyere"},
CorrectAnswerIndex = 0,
MarksAwardedIfCorrect = 1
},
new MultiChoiceItem()
{
ItemText = "Which of the following is not a root vegetable?",
Options = new string[] {"Carrot", "Parsnip", "Turnip", "Shallot"},
CorrectAnswerIndex = 3,
MarksAwardedIfCorrect = 4
},
new MultiChoiceItem()
{
ItemText = "What colour is the outmost archery target ring?",
Options = new string[] {"White", "Yellow", "Red", "Black"},
CorrectAnswerIndex = 0,
MarksAwardedIfCorrect = 1
},
new MultiChoiceItem()
{
ItemText = "What is the chemical symbol for silver?",
Options = new string[] {"Au", "Sr", "Si", "Ag"},
CorrectAnswerIndex = 3,
MarksAwardedIfCorrect = 2
}
};
}
[Test]
public void AllCorrect()
{
// create test data where all items have corresponding responses
// and all responses are correct
Dictionary<int, int> responses = new Dictionary<int, int>();
int i = 0;
foreach (MultiChoiceItem item in _assessmentItems)
{
responses.Add(i, item.CorrectAnswerIndex);
i++;
}
// check that actual results are in line with expected results
AssessmentResults expected = new AssessmentResults()
{
ItemsAttempted = _assessmentItems.Count,
ItemsCorrect = _assessmentItems.Count,
TotalMarksAwarded = _assessmentItems.Sum(item => item.MarksAwardedIfCorrect)
};
AssessmentResults actual = ScoringEngine.GetResults(_assessmentItems, responses);
AssertValueEquality(expected, actual);
}
[Test]
public void AllWrong()
{
// create test data where all items have corresponding responses
// and all responses are wrong
Dictionary<int, int> responses = new Dictionary<int, int>();
int i = 0;
foreach (MultiChoiceItem item in _assessmentItems)
{
if ((item.CorrectAnswerIndex + 1) < item.Options.Length)
responses.Add(i, item.CorrectAnswerIndex + 1);
else
responses.Add(i, item.CorrectAnswerIndex - 1);
i++;
}
// check that actual results are in line with expected results
AssessmentResults expected = new AssessmentResults()
{
ItemsAttempted = responses.Count,
ItemsCorrect = 0,
TotalMarksAwarded = 0
};
AssessmentResults actual = ScoringEngine.GetResults(_assessmentItems, responses);
AssertValueEquality(expected, actual);
}
private void AssertValueEquality(AssessmentResults expected, AssessmentResults actual)
{
CollectionAssert.AreEqual(
new int[] { expected.ItemsAttempted, expected.ItemsCorrect,
expected.TotalMarksAwarded },
new int[] { actual.ItemsAttempted, actual.ItemsCorrect,
actual.TotalMarksAwarded }
);
}
}
}
/How can I implement GetResults method in my Class Library project which is as below
I am not able to figure out the TestFixture in this code
any help will be a great help/
using System.Collections.Generic;
using ScoringExercise.Entities;
using System.Linq;
using System.Collections;
namespace ScoringExercise
{
public static class ScoringEngine
{
/// <summary>
/// Calculates the results of an assessment based upon the test content and candidate
/// responses.
/// </summary>
public static AssessmentResults GetResults(List<MultiChoiceItem> multiChoiceItems,
Dictionary<int, int> responses)
{
//return null;
}
}
}
namespace ScoringExercise.Entities
{
/// <summary>
/// Represents a single multi-choice item in an assessment
/// </summary>
public class MultiChoiceItem
{
// the text associated with the item aka the question
public string ItemText { get; set; }
// the option strings from which the candidate chooses a response
public string[] Options { get; set; }
// the index of the correct answer from within the Options array
public int CorrectAnswerIndex { get; set; }
// the number of marks awarded if the correct response is chosen
public int MarksAwardedIfCorrect { get; set; }
}
}
namespace ScoringExercise.Entities
{
/// <summary>
/// Represents the results of a single assessment instance
/// </summary>
public class AssessmentResults
{
public int ItemsAttempted { get; set; }
public int ItemsCorrect { get; set; }
public int TotalMarksAwarded { get; set; }
}
}
public static AssessmentResults GetResults(List<MultiChoiceItem> multiChoiceItems, Dictionary<int, int> responses)
{
int i = 0;
int ItemsCorrect = 0;
int TotalMarksAwarded = 0;
foreach (var item in multiChoiceItems.Where(c => responses.ContainsKey(c.CorrectAnswerIndex)))
{
if (item.CorrectAnswerIndex == responses[i])
{
ItemsCorrect++;
TotalMarksAwarded += item.MarksAwardedIfCorrect;
}
i++;
}
return new AssessmentResults
{
ItemsAttempted = responses.Count,
ItemsCorrect = ItemsCorrect,
TotalMarksAwarded = TotalMarksAwarded
};
}
}

There is no table accessible from sqlline.bat in ApacheIgnite

I have this code and I expected that when I run !table command in sqlline.bat I will see table called Person, but there is no table.
What I have to do to see the table there?
Am I expecting correctly, that there should be created table automatically for each cache?
Thank you
class Program
{
static void Main()
{
var cfg = new IgniteConfiguration
{
BinaryConfiguration = new BinaryConfiguration(typeof(Person),
typeof(PersonFilter))
};
IIgnite ignite = Ignition.Start(cfg);
ICache<int, Person> cache = ignite.GetOrCreateCache<int, Person>("persons");
cache[1] = new Person { Name = "John Doe", Age = 27 };
cache[2] = new Person { Name = "Jane Moe", Age = 43 };
var scanQuery = new ScanQuery<int, Person>(new PersonFilter());
IQueryCursor<ICacheEntry<int, Person>> queryCursor = cache.Query(scanQuery);
foreach (ICacheEntry<int, Person> cacheEntry in queryCursor)
Console.WriteLine(cacheEntry);
Console.ReadKey();
}
}
class Person
{
[QuerySqlField]
public string Name { get; set; }
[QuerySqlField]
public int Age { get; set; }
public override string ToString()
{
return $"Person [Name={Name}, Age={Age}]";
}
}
class PersonFilter : ICacheEntryFilter<int, Person>
{
public bool Invoke(ICacheEntry<int, Person> entry)
{
return entry.Value.Age > 30;
}
}
SQL table shouldn't be created automatically for the cache. To add SQL table, you should define the schema: https://apacheignite-sql.readme.io/docs/schema-and-indexes
It can be done using annotations, QueryEntiny configuration, or by creating the cache using DDL(CREATE TABLE command).

RavenDB lazy search against Index returns uninitialized statistiscs

I am trying to run lazy queries against raven db and get the counts on total matching results. I am finding when I query against a static index, a lazy search does not initialize the statistics when the query is materialized, but otherwise it comes back all right.
Below is the test to prove this behaviour.
[TestFixture]
public class CanSearchLazily
{
private const int ServerPort = 8085;
private readonly string _serverAddress = #"http://localhost:{0}".For(ServerPort);
[Test]
public void CanGetTotalResultsFromStatisticsOnLazySearchAgainstDynamicIndex()
{
CanGetTotalResultsFromStatisticsOnLazySearchAgainstAnIndex();
}
[Test]
public void CanGetTotalResultsFromStatisticsOnLazySearchAgainstStaticIndex()
{
CanGetTotalResultsFromStatisticsOnLazySearchAgainstAnIndex("UserByFirstName");
}
private void CanGetTotalResultsFromStatisticsOnLazySearchAgainstAnIndex(string indexName = "")
{
BuilderSetup.DisablePropertyNamingFor<User, string>(x => x.Id);
var users = Builder<User>.CreateListOfSize(2000).All()
.With(x => x.FirstName = GetRandom.FirstName())
.With(x => x.LastName = GetRandom.LastName())
.Build();
using (GetNewServer())
using (var store = new DocumentStore { Url = _serverAddress }.Initialize())
{
using (var session = store.OpenSession())
{
users.ForEach(session.Store);
session.SaveChanges();
IndexCreation.CreateIndexes(typeof(UserByFirstName).Assembly, store);
session.Query<User, UserByFirstName>().Customize(x => x.WaitForNonStaleResults()).ToList();
}
using (var session = store.OpenSession())
{
var names = session.Query<User>().Select(u => u.FirstName).Distinct().Take(15).ToList();
RavenQueryStatistics stats;
var query = string.IsNullOrEmpty(indexName)
? session.Query<User>().Statistics(out stats).Where(x => x.FirstName.In(names))
: session.Query<User>(indexName).Statistics(out stats).Where(x => x.FirstName.In(names));
var results = query.Take(8).Lazily();
Assert.AreEqual(8, results.Value.ToList().Count);
Assert.AreEqual(DateTime.Now.Year, stats.IndexTimestamp.Year, "the index should have the current year on its timestamp");
Assert.IsTrue(stats.TotalResults > 0, "The stats should return total results");
}
}
}
protected RavenDbServer GetNewServer(bool initializeDocumentsByEntitiyName = true)
{
var ravenConfiguration = new RavenConfiguration
{
Port = ServerPort,
RunInMemory = true,
DataDirectory = "Data",
AnonymousUserAccessMode = AnonymousUserAccessMode.All
};
if (ravenConfiguration.RunInMemory == false)
IOExtensions.DeleteDirectory(ravenConfiguration.DataDirectory);
var ravenDbServer = new RavenDbServer(ravenConfiguration);
if (initializeDocumentsByEntitiyName)
{
using (var documentStore = new DocumentStore
{
Url = _serverAddress
}.Initialize())
{
new RavenDocumentsByEntityName().Execute(documentStore);
}
}
return ravenDbServer;
}
}
[Serializable]
public class User
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class UserByFirstName : AbstractIndexCreationTask<User>
{
public UserByFirstName()
{
Map = users => from user in users
select new {user.FirstName};
}
}

Serializing object graph using MongoDB Bson serializer

I've been playing a little with the MongoDB Bson serializer, using the following piece of code:
class Program
{
public class myValue
{
public int Id = 0;
public string Label = "";
}
public class myValueMap : Dictionary<string, myValue>
{
}
public class myProdData
{
public myValueMap Mapping { get; set; }
}
public class mySystemPosition
{
public string Text { get; set; }
public myProdData ProdData { get; set; }
}
static void Main(string[] args)
{
BsonClassMap.RegisterClassMap<mySystemPosition>();
BsonClassMap.RegisterClassMap<myProdData>();
BsonClassMap.RegisterClassMap<myValueMap>();
BsonClassMap.RegisterClassMap<myValue>();
var o = new mySystemPosition()
{
ProdData = new myProdData()
{
Mapping = new myValueMap()
{
{"123", new myValue() {Id = 1, Label = "Item1"}},
{"345", new myValue() {Id = 2, Label = "Item2"}},
}
}
};
var bson = o.ToBson();
var text = Encoding.ASCII.GetString(bson);
}
}
however I don't seem to be able to get the myProdData.Mapping serialized....
Do I need to configure the MongoDB Bson serializer in a special way, to make this work?
You no need to use BsonClassMap.RegisterClassMap if you no need custom serializtion(documentation).
All your classes will be desirialzied according to default rules.
Also i am changed your example a little bit to get it work(i've replaces myValueMap class with Dictionary):
public class myProdData
{
public Dictionary<string, myValue> Mapping { get; set; }
}
static void Main(string[] args)
{
var o = new mySystemPosition()
{
ProdData = new myProdData()
{
Mapping = new Dictionary<string, myValue>()
{
{"123", new myValue() {Id = 1, Label = "Item1"}},
{"345", new myValue() {Id = 2, Label = "Item2"}},
}
}
};
var json = o.ToJson();
Console.WriteLine(json);
Console.ReadKey();
}
Here is console output(just well formatted):
{
"Text":null,
"ProdData":{
"Mapping":{
"123":{
"_id":1,
"Label":"Item1"
},
"345":{
"_id":2,
"Label":"Item2"
}
}
}
}
You can test your serializtion using ToJson() extention method, in order to view that all correct and after that use ToBson() if need.
The problem is that myValueMap derives from Dictionary. That results in a class that the AutoMap method can't handle.
I recommend you just use the Dictionary directly, as Andrew did in his reply.
Ufortunately the myValueMap is an object that I can't easily change, however it turns out, that's pretty easy to create your own (de)serializer....
public class myValueMapSerializer : IBsonSerializer
{
public object Deserialize(Bson.IO.BsonReader bsonReader, System.Type nominalType, System.Type actualType, IBsonSerializationOptions options)
{
if (nominalType != typeof(myValueMap)) throw new ArgumentException("Cannot serialize anything but myValueMap");
var res = new myValueMap();
var ser = new DictionarySerializer<string, myValue>();
var dic = (Dictionary<string, myValue>)ser.Deserialize(bsonReader, typeof(Dictionary<string, myValue>), options);
foreach (var item in dic)
{
res.Add(item.Key, item.Value);
}
return res;
}
public object Deserialize(Bson.IO.BsonReader bsonReader, System.Type nominalType, IBsonSerializationOptions options)
{
throw new Exception("Not implemented");
}
public bool GetDocumentId(object document, out object id, out IIdGenerator idGenerator)
{
id = null;
idGenerator = null;
return false;
}
public void Serialize(Bson.IO.BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
{
if (nominalType != typeof(myValueMap)) throw new ArgumentException("Cannot serialize anything but myValueMap");
var ser = new DictionarySerializer<string, myValue>();
ser.Serialize(bsonWriter, typeof(DictionarySerializer<string, myValue>), value, options);
}
public void SetDocumentId(object document, object id)
{
return;
}
}