Stub not returning correct value with Rhino Mocks 3.6 - rhino-mocks

I'm trying to write a test using Rhino Mocks 3.6 with AAA. The problem I'm running into is that the Stub i've set up doesn't seem to be returning the correct object.
The following test fails:
[SetUp]
public void SetUp()
{
repository = new MockRepository();
webUserDal = repository.Stub<IWebUserDal>();
}
[Test]
public void Test()
{
var user1 = new WebUser{Status = Status.Active, Email = "harry#test.com"};
webUserDal.Stub(x => x.Load(Arg<string>.Is.Anything)).Return(user1);
var user2 = webUserDal.Load("harry#test.com");
Assert.AreEqual(user1.Email, user2.Email);
}
User1's email property is harry#test.com while user2's email property is null
Could anyone shed some light on what I'm doing wrong?

You mixed up the old and new syntax, and it doesn't seem to work nicely together. If you want to use the new syntax (preferred), you have to change your set up method to:
[SetUp]
public void SetUp()
{
webUserDal = MockRepository.GenerateStub<IWebUserDal>();
}
If you create the MockRepository object then you need to run repository.ReplayAll() before you use the mocks, but this is the old syntax. So its better to just use static methods.

Related

Some problems with testing Akka.net

Version Akka.NET v1.3.8
Version Akka.TestKit.NUnit3 v1.3.2
Version NUnit v3.10.1
Platform Windows 10
I have an actor of the following kind:
public class BranchUsersActor : ReceiveActor
{
public BranchUsersActor()
{
Receive<UserBeingOnline>((online) =>
{
var userActorName = $"user_{online.UserId}";
if (Context.Child(userActorName).Equals(ActorRefs.Nobody))
{
var user = Context.ActorOf(UserActor.Props(online.UserId, online.BranchId), userActorName);
user.Tell(online);
}
});
}
public static Props Props(LoggingTags tags)
{
return Akka.Actor.Props.Create(() => new BranchUsersActor(tags));
}
}
When testing this actor, I expect that I will have a child actor.
I'm writing the next test to check this situation (using the NUnit framework):
[Test]
public void Test()
{
var branchUserActor = Sys.ActorOf(BranchUsersActor.Props());
branchUserActor.Tell(UserBeingOnline.Create(userId, branchId));
var expectedChildActor = Sys.ActorSelection($"{actorPath}/user_{userId.AkkaPrepare()}")
.ResolveOne(TimeSpan.FromSeconds(1)).Result;
Assert.IsNotNull(expectedChildActor);
}
I expect that within a second I will receive the child actor on the specified path, but I get ActorNotFoundExpection.
If I'm doing something like this:
[Test]
public void Test()
{
var branchUserActor = Sys.ActorOf(BranchUsersActor.Props());
branchUserActor.Tell(UserBeingOnline.Create(userId, branchId));
Task.Delay(100).ContinueWith(_ =>
{
var expectedChildActor = Sys.ActorSelection($"{actorPath}/user_{userId.AkkaPrepare()}")`enter code here`
.ResolveOne(TimeSpan.FromSeconds(1)).Result;
}
Assert.IsNotNull(expectedChildActor);
}
This works fine, but 1 of 10 times the test falls, because I get an ActorNotFoundException.
But I wonder why the first option does not work the way I expect?
Am I doing something wrong?
Thanks in advance for the answer.
branchUserActor.Tell(UserBeingOnline.Create(userId, branchId));
var expectedChildActor = Sys.ActorSelection($"{actorPath}/user_{userId.AkkaPrepare()}")
.ResolveOne(TimeSpan.FromSeconds(1)).Result;
The problem here is that when you're telling UserBeingOnline, you're triggering an asynchronous action - a message has been send to branchUserActor, but it may not have been processed right away. In the meantime you're calling resolve one, which tells actor system to find a child of branchUserActor - a child, which is not yet there, since the parent didn't handle the message yet.
You can use AwaitAssert(() => Assert.IsNotNull(ResolveChild())) method to work with that.

Combining dataproviders TestNG

I have read a few stackoverflow posts about combining dataproviders but I cant't get anything to work.
What I'm currently doing is a selenium test that takes screenshots of every language the site is translated to.
It simply clicks through every link while taking screenshots of it, then it switches the URL to another language and repeat.
My problem is when doing this I can't redirect my screenshots to a specific folder per "language test". To do this I need a second dataprovider, but I already have a dataprovider for this test method for running a different URL per test.
So I need to combine these two dataproviders somehow.
They currently look like this
public static Object [][] language(){
return new Object[][]{
{"https://admin-t1.taxicaller.net/login/admin.php?lang=en"},
{"https://admin-t1.taxicaller.net/login/admin.php?lang=sv"},
};
}
public static Object [][] directory(){
return new Object[][]{
{"screenshotsEnglish.dir"},
{"screenshotsSwedish.dir"},
};
}
In my test class I just want to reach these two by writing
driver.get(**url**);
// This is the screenshot method. Where "Directory" is written I decide where to save the screenshots
Properties settings = PropertiesLoader.fromResource("settings.properties");
String screenshotDir = settings.getProperty(**directory**);
screenShooter = new ScreenShooter(driver, screenshotDir, "en");
Hope I have made myself clear, appreciate all help!
Regards
public static Object[][] dp() {
return new Object[][]{
{
"https://admin-t1.taxicaller.net/login/admin.php?lang=en",
"screenshotsEnglish.dir"
},
{
"https://admin-t1.taxicaller.net/login/admin.php?lang=sv",
"screenshotsSwedish.dir"
}
};
}
#Test(dataProvider = "dp")
public void t(String url, String directory) {
driver.get(url);
Properties settings = PropertiesLoader.fromResource("settings.properties");
String screenshotDir = settings.getProperty(directory);
screenShooter = new ScreenShooter(driver, screenshotDir, "en");
/*...*/
}

Elastic Search NEST Self referencing loop detected for property

Using version 2.0.2 I just cannot find where to set the serializer settings for the Nest.JsonNetSerializer to avoid Self referencing loop detected exception.
And i guess that the documentation is not updated for version 2.
There is one PR in the NEST repo explaining how you can handle this situation in version 2.x.x.
Summary:
var connectionPool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var settings = new ConnectionSettings(connectionPool, connectionSettings => new MyJsonNetSerializer(connectionSettings))
.DefaultIndex(indexName)
.DisableDirectStreaming()
.PrettyJson();
public class MyJsonNetSerializer : JsonNetSerializer
{
public MyJsonNetSerializer(IConnectionSettingsValues settings) : base(settings)
{
}
protected override void ModifyJsonSerializerSettings(Newtonsoft.Json.JsonSerializerSettings settings)
{
settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
}
}
Hope it helps.
Once again there are some significant changes to how this is handled in v.5.
I found this example in the tests and it worked for me...
/**=== Overriding Json.NET settings
*
* Overriding the default Json.NET behaviour in NEST is an expert behavior but if you need to get to the nitty gritty, this can be really useful.
*/
/**
* The easiest way is to create an instance of `SerializerFactory` that allows you to register a modification callback
* in the constructor
*/
public void EasyWay()
{
var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var connectionSettings = new ConnectionSettings(
pool,
new HttpConnection(),
new SerializerFactory((jsonSettings, nestSettings) => jsonSettings.PreserveReferencesHandling = PreserveReferencesHandling.All));
var client = new ElasticClient(connectionSettings);
}
https://github.com/elastic/elasticsearch-net/blob/5.x/src/Tests/ClientConcepts/LowLevel/Connecting.doc.cs#L289

Get exception when stubbing a property

When I run the following test:
[TestMethod]
public void MyTest()
{
var wizardCatalog = MockRepository.GenerateStub<IWizardCatalog>();
var firstQuestion = MockRepository.GenerateStub<IWizardQuestion>();
wizardCatalog.Stub(i => i.GetFirstQuestion()).Return(firstQuestion);
var choices = new List<IWizardChoice>();
firstQuestion.Stub(i => i.Choices).Return(choices);
}
I get this exception:
You are trying to set an expectation on a property that was defined to
use PropertyBehavior. Instead of writing code such as this:
mockObject.Stub(x => x.SomeProperty).Return(42); You can use the
property directly to achieve the same result: mockObject.SomeProperty
= 42;
Everything I read tells me that this stub operation is valid:
var choices = new List<IWizardChoice>();
firstQuestion.Stub(i => i.Choices).Return(choices);
What is going on?
PropertyBehaviour is on by default on stubs, but not on mocks. So you can either continue using a stub and change to the syntax suggested in the exception, or create a mock with GenerateMock<IWizardQuestion>() and use your existing .Stub(...).Return(...) syntax.

Rhino AutoMocker and Stubs

I am using Joshua Flanagan article “Auto mocking Explained” as a guide. In the article there is a section called “The same tests, with automocker would look like this”. I used this information to build code to run the automocker.
As you can see below answer is a list returned from the BLL. Answer does have one row in it; however, all fields are null. So the test for boo fails. Any tips and hints would be greatly appreciated.
[Test]
public void GetStaffListAndRolesByTeam_CallBLLWithDALStub()
{
// Build List<> data for stub
List<StaffRoleByTeamCV> stubData = new List<StaffRoleByTeamCV>();
StaffRoleByTeamCV stubRow = new StaffRoleByTeamCV();
stubRow.Role = "boo";
stubRow.StaffId = 12;
stubRow.StaffName = "Way Cool";
stubData.Add(stubRow);
// create the automocker
var autoMocker = new RhinoAutoMocker<PeteTestBLL>();
// get instance of test class (the BLL)
var peteTestBllHdl = autoMocker.ClassUnderTest;
// stub out call to DAL inside of BLL
autoMocker.Get<IPeteTestDAL>().Stub(c => c.GetStaffListAndRolesByTeam("4146")).Return(stubData);
// make call to BLL this should return stubData
List<StaffRoleByTeamCV> answer = peteTestBllHdl.GetStaffListAndRolesByTeam("4146");
// do simple asserts to test stubData present
// this passes
Assert.IsTrue(1 == answer.Count, "Did not find any rows");
// this fails
Assert.IsTrue(answer[0].Role == "boo", "boo was not found");
}
I tried using MockMode.AAA but still no joy
An new version of AutoMocker (1.0.3) is available. The new version supports relay mode as in this example..
[TestMethod]
public void ShouldSupportOrderedTest()
{
//Arrange
var autoMocker = new RhinoAutoMocker<CustomerUpdater>();
var mockRepository = autoMocker.Repository;
using (mockRepository.Ordered())
{
autoMocker.Get<ICustomerDataProvider>().Expect(x => x.GetCustomer(Arg<int>.Is.Anything)).Return(new CustomerItem());
autoMocker.Get<ICustomerDataProvider>().Expect(x => x.UpdateCustomer(Arg<CustomerItem>.Is.Anything));
autoMocker.Get<ILogWriter>().Expect(x => x.Write(Arg<string>.Is.Anything));
autoMocker.Get<ILogWriter>().Expect(x => x.Write(Arg<string>.Is.Anything));
autoMocker.Get<IMailSender>().Expect(x => x.SendMail(Arg<string>.Is.Anything, Arg<string>.Is.Anything));
}
//Act
autoMocker.ClassUnderTest.UpdateCustomerName(1, "Frank", "frank#somecompany.com");
//Assert
ExceptionAssert.Throws<ExpectationViolationException>(mockRepository.VerifyAll,"IMailSender.SendMail(anything, anything); Expected #1, Actual #0.\r\nILogWriter.Write(anything); Expected #1, Actual #0.\r\n");
}
I haven't tried, but this article suggests that by default all the mocks created by automocker are not replayed:
http://www.lostechies.com/blogs/joshuaflanagan/archive/2008/09/25/arrange-act-assert-with-structuremap-rhinoautomocker.aspx
Yes that was true for the previous version. But was changed to support ordered tests in version 1.0.3.