New to AutoFixture trying to get my head around it and I can't see it helping me - autofixture

Currently, I'm using custom made fake objects that behind the scenes use NSubstitute which creates the actual objects but it's becoming very hard to maintain as the project grows, so I'm trying to find alternatives and I'm hoping that AutoFixture is the right tool for the job.
I read the documentation and I'm struggling because there's very little to no documentation and I read most of the blog posts by Mark Seemann including the CheatSheet.
One of the things that I'm having hard time to grasp is how to create an object with a constructor that have parameters, in my case I need to pass argument to CsEmbeddedRazorViewEngine as well as HttpRequestBase to ControllerContext.
The way I see it is that I need to create a fake objects and finally create a customization object that injects them to
I also looked into NBuilder it seems slightly more trivial to pass arguments there but I've heard good things about AutoFixture and I would like to give it a try. :)
I'm trying to reduce the amount of fake objects I have so here is a real test, how can I do the same thing with AutoFixture?
[Theory,
InlineData("en-US"),
InlineData("en-us"),
InlineData("en")]
public void Should_return_the_default_path_of_the_view_for_enUS(string language)
{
// Arrange
const string EXPECTED_VIEW_PATH = "~/MyAssemblyName/Views/Home/Index.cshtml";
CsEmbeddedRazorViewEngine engine = CsEmbeddedRazorViewEngineFactory.Create(ASSEMBLY_NAME, VIEW_PATH, string.Empty);
string[] userLanguage = { language };
HttpRequestBase request = FakeHttpRequestFactory.Create(userLanguage);
ControllerContext controllerContext = FakeControllerContextFactory.Create(request);
// Act
ViewEngineResult result = engine.FindPartialView(controllerContext, VIEW_NAME, false);
// Assert
RazorView razorView = (RazorView)result.View;
string actualViewPath = razorView.ViewPath;
actualViewPath.Should().Be(EXPECTED_VIEW_PATH);
}
P.S. I'm using xUnit as my testing framework and NSubstitute as my mocking framework should I install both AutoFixture.Xunit and AutoFixture.AutoNSubstitute?
UPDATE: After learning more and more about it I guess it is not the right tool for the job because I tried to replace my test doubles factories with AutoFixture rather than setting up my SUT with it.
Due to odd reason I thought it's doing the same thing NBuilder is doing and from what I can see they are very different tools.
So after some thinking I think I'll go and change the methods I have on my test doubles factories to objects then use AutoFixture to create my SUT and inject my test doubles to it.

Note: I don't have the source code for the CsEmbeddedRazorViewEngine type and all the other custom types.
Here is how it could be written with AutoFixture:
[Theory]
[InlineAutoWebData("en-US", "about", "~/MyAssemblyName/Views/Home/Index.cshtml")]
[InlineAutoWebData("en-US", "other", "~/MyAssemblyName/Views/Home/Index.cshtml")]
public void Should_return_the_default_path_of_the_view_for_enUS(
string language,
string viewName,
string expected,
ControllerContext controllerContext,
CsEmbeddedRazorViewEngine sut)
{
var result = sut.FindPartialView(controllerContext, viewName, false);
var actual = ((RazorView)result.View).ViewPath;
actual.Should().Be(expected);
}
How it works:
It uses AutoFixture itself together with it's glue libraries for xUnit.net and NSubstitute:
PM> Install-Package AutoFixture.Xunit
PM> Install-Package AutoFixture.AutoNSubstitute
With InlineAutoWebData you actually combine inline values and auto-generated data values by AutoFixture – also including Auto-Mocking with NSubstitute.
internal class InlineAutoWebDataAttribute : CompositeDataAttribute
{
internal InlineAutoWebDataAttribute(params object[] values)
: base(
new InlineDataAttribute(values),
new CompositeDataAttribute(
new AutoDataAttribute(
new Fixture().Customize(
new WebModelCustomization()))))
{
}
}
Remarks:
You could actually replace the WebModelCustomization customization above with AutoNSubstituteCustomization and it could work.
However, assuming that you are using ASP.NET MVC 4, you need to customize the Fixture instance with:
internal class WebModelCustomization : CompositeCustomization
{
internal WebModelCustomization()
: base(
new MvcCustomization(),
new AutoNSubstituteCustomization())
{
}
private class MvcCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customize<ControllerContext>(c => c
.Without(x => x.DisplayMode));
// Customize the CsEmbeddedRazorViewEngine type here.
}
}
}
Further reading:
Encapsulating AutoFixture Customizations
AutoData Theories with AutoFixture

I ended up doing this.
[Theory,
InlineData("en-US", "Index", "~/MyAssemblyName/Views/Home/Index.cshtml"),
InlineData("en-us", "Index", "~/MyAssemblyName/Views/Home/Index.cshtml"),
InlineData("en", "Index", "~/MyAssemblyName/Views/Home/Index.cshtml")]
public void Should_return_the_default_path_of_the_view(string language, string viewName, string expected)
{
// Arrange
CsEmbeddedRazorViewEngine engine = new CsEmbeddedRazorViewEngineFixture();
ControllerContext controllerContext = FakeControllerContextBuilder.WithLanguage(language).Build();
// Act
ViewEngineResult result = engine.FindPartialView(controllerContext, viewName, false);
// Assert
string actualViewPath = ((RazorView)result.View).ViewPath;
actualViewPath.Should().Be(expected);
}
I encapsulated the details to setup my SUT into a fixture and used the builder pattern to handle my fakes, I think that it's readable and pretty straightforward now.
While AutoFixture looks pretty cool, the learning curve seems long and I will need to invest enough time to understand it, for now, I want to clean-up my unit tests and make them more readable. :)

Related

Writing a generic InsertData method using Dapper.Contrib and InsertAsync

I am fairly new to C# and Dapper. I am trying to write a generic Insert Data method for my project. I come from a Delphi environment so I am still finding my way around C#.
Dapper seems fairly straight forward to use but I am experiencing some challenges. I have tried every which way to get the syntax right with the following code but have been unsuccessful.
Issues seem to be around the T (I still quite don't understand what T is) and all the combinations I have tried don't work.
public async Task<int> InsertData<T>(T list)
{
string connectionString = _config.GetConnectionString(ConnectionStringName);
using (IDbConnection connection = new SqlConnection(connectionString))
{
return await connection.InsertAsync<int>(list);
}
}
The following code does work, so where am I going wrong?
public async Task SaveData<T>(string sql, T parameters)
{
string connectionString = _config.GetConnectionString(ConnectionStringName);
using (IDbConnection connection = new SqlConnection(connectionString))
{
await connection.ExecuteAsync(sql, parameters);
}
}
Your second code (await connection.ExecuteAsync(sql, parameters);) works because you are simply executing your hand written SQL statement. The method ExecuteAsync belongs to Dapper; NOT Dapper.Contrib. The generic T is used for parameters, not for the object you are trying to insert.
With your first code (return await connection.InsertAsync<int>(list);), you are actually using Dapper.Contrib; you are not writing the SQL statement by hand. Dapper.Contrib generates it for you.
Your following code seems the problem:
return await connection.InsertAsync<int>(list);
You are passing generic parameter <int> to the method which does not make sense.
I have not tested this but I hope changing that line to below one should work:
return await connection.InsertAsync<T>(list);
Also, you have to make sure the generic type T is class by adding where T : class to it.
Following generic method should serve your purpose; you need to convert it to async to match with your current code:
public void InsertData<T>(T entity) where T : class
{
string connectionString = ....;
using(IDbConnection connection = new SqlConnection(connectionString))
{
long result = connection.Insert<T>(entity);
}
}
I did not understood few other parts in your code. Say InsertData<T>(T list). What is list? Is it as single object or list of objects? If it is list of objects, List<T> list makes more sense. If it is single object, better you rename list to actual object name, say T customer/entity/poco etc.

Watson Retrieve & Rank : Difference in answer when asked using Web UI versus an application

Please see this JSON returned when asked the question : What are the basic methods of Optional ? This is not the perfect match answer that is being returned in the Retrieve and Rank Tooling ( pasted below this JSON snippet). Can you please help me understand why this is happening?
{
"context": {
"conversation_id": "f87c08f1-2122-4d44-b0bc-d05cd458162d",
"system": {
"dialog_stack": "[root]",
"dialog_turn_counter": "1.0",
"dialog_request_counter": "1.0"
}
},
"inquiryText": "what are the basic methods of Optional",
"responseText": "Going to get answers from Devoxx corpus, ",
"resources": [
{
"id": "\"50a305ba-f8fd-4470-afde-884df5170e29\"",
"score": "1.5568095",
"title": "\"no-title\"",
"body": "\"Voxxed JUnit 5 – The Basics Nicolai Parlog 5 months ago Categories: Methodology Tags: java , JUnit , JUnit 5 19 SHARES Facebook Twitter Reddit Google Mail Linkedin Digg Stumbleupon Buffer Last time, we  set up JUnit 5 to be able to write tests. So let’s do it! Overview This post is part of a series about JUnit 5: Setup Basics Architecture Conditions Injection … Most of what you will read here and more can be found in the emerging JUnit 5 user guide . Note that it is based on an alpha version and hence subject to change.Indeed, we are encouraged to open issues or pull requests so that JUnit 5 can improve further. Please make use of this opportunity! It is our chance to help JUnit help us, so if something you see here could be improved, make sure to take it upeam .This post will get updated when it becomes necessary. The code samples I show here can be found on GitHub . Philosophy The new architecture, which we will discuss another time, is aimed at extensibility. It is possible that someday very alien (at least to us run-of-the-mill Java devs) testing techniques will be possible with JUnit 5. But for now the basics are very similar to the current version 4. JUnit 5’s surface undergoes a deliberately incremental improvement and developers should feel right at home. At least I do and I think you will, too: Basic Lifecycle And Features class Lifecycle { #BeforeAll static void initializeExternalResources() { System.out.println(\\\"Initializing external resources...\\\"); } #BeforeEach void initializeMockObjects() { System.out.println(\\\"Initializing mock objects...\\\"); } #Test void someTest() { System.out.println(\\\"Running some test...\\\"); assertTrue(true); } #Test void otherTest() { assumeTrue(true); System.out.println(\\\"Running another test...\\\"); assertNotEquals(1, 42, \\\"Why wouldn't these be the same?\\\"); } #Test #Disabled void disabledTest() { System.exit(1); } #AfterEach void tearDown() { System.out.println(\\\"Tearing down...\\\"); } #AfterAll static void freeExternalResources() { System.out.println(\\\"Freeing external resources...\\\"); } } See? No big surprises. The Basics Of JUnit 5 Visibility The most obvious change is that test classes and methods do not have to be public anymore. Package visibility suffices but private does not. I think this is a sensible choice and in line with how we intuit the different visibility modifiers. Great! I’d say, less letters to type but you haven’t been doing that manually anyways, right? Still less boilerplate to ignore while scrolling through a test class. Test Lifecycle #Test The most basic JUnit annotation is #Test, which marks methods that are to be run as tests. It is virtually unchanged, although it no longer takes optional arguments. Expected exceptions can now be verified via assertions but as far as I know there is not yet a replacement for timeouts . JUnit 5 creates a new test instance for each test method (same as JUnit 4). Before And After You might want to run code to set up and tear down your tests. There are four method annotations to help you do that: #BeforeAll Executed once; runs before the tests and methods marked with #BeforeEach. #BeforeEach Executed before each test. #AfterEach Executed after each test. #AfterAll Executed once; runs after all tests and methods marked with #AfterEach. Because a new instance is created for each test, there is no obvious instance on which to call the #BeforeAll/ #AfterAll methods, so they have to be static. The order in which different methods annotated with the same annotation are executed is undefined. As far as I can tell the same is true for inherited methods. Whether it should be possible to define an order is currently being discussed . Except in name, these annotations work exactly like in JUnit 4. While not  uncommon , I am not convinced of the names, though. See this issue for details. Disabling Tests It’s Friday afternoon and you just want to go home? No problem, just slap#Disabled on the test (optionally giving a reason) and run. A Disabled Test #Test #Disabled(\\\"Y U No Pass?!\\\") void failingTest() { assertTrue(false); } Test Class Lifecycle Compared to the prototype it is interesting to note that the test class lifecycle didn’t make it into the alpha version. It would run all tests on the same instance of the test class, thus allowing the tests to interact with each other by mutating state. As I already wrote while discussing the prototype: I think this is a typical case of a feature that is harmful in 99% of the cases but indispensable in the other 1%. Considering the very real risk of horrible inter-test-dependencies I’d say it was a good thing that it was taken out in its original form. But the JUnit team is discussing  ways to bring it back in with a different name and added semantics. This would make its use very deliberate. What do you think? Assertions If #Test, #Before..., and #After... are a test suite’s skeleton, assertions are its heart. After the instance under test was prepared and the functionality to test was executed on it, assertions make sure that the desired properties hold. If they don’t, they fail the running test. Classic Classic assertions either check a property of a single instance (e.g. that it is not null) or do some kind of comparison (e.g. that two instances are equal). In both cases they optionally take a message as a last parameter, which is shown when the assertion fails. If constructing the message is expensive, it can be specified as a lambda expression, so construction is delayed until the message is actually required. Classic Assertions #Test void assertWithBoolean() { assertTrue(true); assertTrue(this::truism); assertFalse(false, () -> \\\"Really \\\" + \\\"expensive \\\" + \\\"message\\\" + \\\".\\\"); } boolean truism() { return true; } #Test void assertWithComparison() { List expected = asList(\\\"element\\\"); List actual = new LinkedList<>(expected); assertEquals(expected, actual); assertEquals(expected, actual, \\\"Should be equal.\\\"); assertEquals(expected, actual, () -> \\\"Should \\\" + \\\"be \\\" + \\\"equal.\\\"); assertNotSame(expected, actual, \\\"Obviously not the same instance.\\\"); } As you can see JUnit 5 doesn’t change much here. The names are the same as before and comparative assertions still take a pair of an expected and an actual value (in that order). That the expected-actual order is so critical in understanding the test’s failure message and intention, but can be mixed up so easily is a big blind spot. There’s nothing much to do, though, except to create a new assertion framework. Considering big players like Hamcrest (ugh!) or AssertJ (yeah!), this would not have been a sensible way to invest the limited time. Hence the goal was to keep the assertions focused and effort-free. New is that failure message come last. I like it because it keeps the eye on the ball, i.e. the property being asserted. As a nod to Java 8, Boolean assertions now accept  suppliers , which is a nice detail. Extended Aside from the classical assertions that check specific properties, there are a couple of others. The first is not even a real assertion, it just fails the test with a failure message. 'fail' #Test void failTheTest() { fail(\\\"epicly\\\"); } Then we have assertAll, which takes a variable number of assertions and tests them all before reporting which failed (if any). #Test void assertAllProperties() { Address address = new Address(\\\"New City\\\", \\\"Some Street\\\", \\\"No\\\"); assertAll(\\\"address\\\", () -> assertEquals(\\\"Neustadt\\\", address.city), () -> assertEquals(\\\"Irgendeinestraße\\\", address.street), () -> assertEquals(\\\"Nr\\\", address.number) ); } Failure Message for ‘AssertALL’ org.opentest4j.MultipleFailuresError: address (3 failures) expected: but was: expected: but was: expected: but was: This is great to check a number of related properties and get values for all of them as opposed to the common behavior where the test reports the first one that failed and you never know the other values. Finally we have assertThrows and expectThrows. Both fail the test if the given method does not throw the specified exception. The latter also returns the exceptions so it can be used for further verifications, e.g. asserting that the message contains certain information. #Test void assertExceptions() { assertThrows(Exception.class, this::throwing); Exception exception = expectThrows(Exception.class, this::throwing); assertEquals(\\\"Because I can!\\\", exception.getMessage()); } Assumptions Assumptions allow to only run tests if certain conditions are as expected. This can be used to reduce the run time and verbosity of test suites, especially in the failure case. #Test void exitIfFalseIsTrue() { assumeTrue(false); System.exit(1); } #Test void exitIfTrueIsFalse() { assumeFalse(this::truism); System.exit(1); } private boolean truism() { return true; } #Test void exitIfNullEqualsString() { assumingThat( \\\"null\\\".equals(null), () -> System.exit(1) ); } Assumptions can either be used to abort tests whose preconditions are not met or to execute (parts of) a test only if a condition holds. The main difference is that aborted tests are reported as disabled, whereas a test that was empty because a condition did not hold is plain green. Nesting Tests JUnit 5 makes it near effortless to nest test classes. Simply annotate inner classes with #Nested and all test methods in there will be executed as well: package org.codefx.demo.junit5;// NOT_PUBLISHED import org.junit.gen5.api.BeforeEach; import org.junit.gen5.api.Nested; import org.junit.gen5.api.Test; import static org.junit.gen5.api.Assertions.assertEquals; import static org.junit.gen5.api.Assertions.assertTrue; class Nest { int count = Integer.MIN_VALUE; #BeforeEach void setCountToZero() { count = 0; } #Test void countIsZero() { assertEquals(0, count); } #Nested class CountGreaterZero { #BeforeEach void increaseCount() { count++; } #Test void countIsGreaterZero() { assertTrue(count > 0); } #Nested class CountMuchGreaterZero { #BeforeEach void increaseCount() { count += Integer.MAX_VALUE / 2; } #Test void countIsLarge() { assertTrue(count > Integer.MAX_VALUE / 2); } } } } As you can see, #BeforeEach (and #AfterEach) work here as well. Although currently not documented the initializations are executed outside-in. This allows to incrementally build a context for the inner tests. For nested tests to have access to the outer test class’ fields, the nested class must not be static. Unfortunately this forbids the use of static methods so #BeforeAll and#AfterAll can not be used in that scenario. ( Or can they? ) Maybe you’re asking yourself what this is good for. I use nested test classes to inherit interface tests , others to keep their test classes small and focused . The latter is also demonstrated by the more elaborate example commonly given by the JUnit team , which tests a stack: class TestingAStack { Stack stack; boolean isRun = false; #Test void isInstantiatedWithNew() { new Stack(); } #Nested class WhenNew { #BeforeEach void init() { stack = new Stack(); } // some tests on 'stack', which is empty #Nested class AfterPushing { String anElement = \\\"an element\\\"; #BeforeEach void init() { stack.push(anElement); } // some tests on 'stack', which has one element... } } } In this example the state is successively changed and a number of tests are executed for each scenario. Naming Tests JUnit 5 comes with an annotation #DisplayName, which gives developers the possibility to give more easily readable names to their test classes and methods. With it, the stack example which looks as follows: #DisplayName(\\\"A stack\\\") class TestingAStack { #Test #DisplayName(\\\"is instantiated with new Stack()\\\") void isInstantiatedWithNew() { /*…*/ } #Nested #DisplayName(\\\"when new\\\") class WhenNew { #Test #DisplayName(\\\"is empty\\\") void isEmpty() { /*…*/ } #Test #DisplayName(\\\"throws EmptyStackException when popped\\\") void throwsExceptionWhenPopped() { /*…*/ } #Test #DisplayName(\\\"throws EmptyStackException when peeked\\\") void throwsExceptionWhenPeeked() { /*…*/ } #Nested #DisplayName(\\\"after pushing an element\\\") class AfterPushing { #Test #DisplayName(\\\"it is no longer empty\\\") void isEmpty() { /*…*/ } #Test #DisplayName(\\\"returns the element when popped and is empty\\\") void returnElementWhenPopped() { /*…*/ } #Test #DisplayName( \\\"returns the element when peeked but remains not empty\\\") void returnElementWhenPeeked(){ /*…*/ } } } } This creates nicely readable output and should bring joy to the heart of BDD ‘ers! Reflection That’s it, you made it! We rushed through the basics of how to use JUnit 5 and now you know all you need to write plain tests: How to annotate the lifecycle methods (with #[Before|After][All|Each]) and the test methods themselves ( #Test), how to nest ( #Nested) and name ( #DisplayName) tests and how assertions and assumptions work (much like before). But wait, there’s more! We didn’t yet talk about conditional execution of tests methods, the very cool parameter injection, the extension mechanism, or the project’s architecture. And we won’t right now because we will take a short break from JUnit 5 and come back to it in about a month. Stay tuned! Window size: x Viewport size: x\"",
"docName": "\"JUnit 5 – The Basics - Voxxed.htm\""
},
{
"id": "\"0054b4e9-6b55-420e-84bc-8f31c79a949f\"",
"score": "1.2038735",
"title": "\"By Stefan Bulzan\"",
"body": "\"With the advent of lambdas in Java we now have a new tool to better design our code. Of course, the first step is using streams, method references and other neat features introduced in Java 8. Going forward I think the next step is to revisit the well established Design Patterns and see them through the functional programming lenses. For this purpose I’ll take the Decorator Pattern and implement it using lambdas. We’ll take an easy and delicious example of the Decorator Pattern: adding toppings to pizza. Here is the standard implementation as suggested by GoF: First we have the interface that defines our component: public interface Pizza { String bakePizza(); } We have a concrete component: public class BasicPizza implements Pizza { #Override public String bakePizza() { return \\\"Basic Pizza\\\"; } } We decide that we have to decorate our component in different ways. We go with Decorator Pattern. This is the abstract decorator: public abstract class PizzaDecorator implements Pizza { private final Pizza pizza; protected PizzaDecorator(Pizza pizza) { this.pizza = pizza; } #Override public String bakePizza() { return pizza.bakePizza(); } } We provide some concrete decorators for the component: public class ChickenTikkaPizza extends PizzaDecorator { protected ChickenTikkaPizza(Pizza pizza) { super(pizza); } #Override public String bakePizza() { return super.bakePizza() + \\\" with chicken topping\\\"; } } public class ProsciuttoPizza extends PizzaDecorator { protected ProsciuttoPizza(Pizza pizza) { super(pizza); } #Override public String bakePizza() { return super.bakePizza() + \\\" with prosciutto\\\"; } } And this is the way to use the new structure: Pizza pizza = new ChickenTikkaPizza(new BasicPizza()); String finishedPizza = pizza.bakePizza(); //Basic Pizza with chicken topping pizza = new ChickenTikkaPizza(new ProsciuttoPizza(new BasicPizza())); finishedPizza = pizza.bakePizza(); //Basic Pizza with prosciutto with chicken topping We can see that this can get very messy, and it did get very messy if we think about how we handle buffered readers in Java: new DataInputStream(new BufferedInputStream(new FileInputStream(new File(\\\"myfile.txt\\\")))) Of course, you can split that in multiple lines, but that won’t solve the messiness, it will just spread it. Now lets see how we can do the same thing using lambdas. We start with the same basic component objects: public interface Pizza { String bakePizza(); } public class BasicPizza implements Pizza { #Override public String bakePizza() { return \\\"Basic Pizza\\\"; } } But now instead of declaring an abstract class that will provide the template for decorations, we will create the decorator that asks the user for functions that will decorate the component. public class PizzaDecorator { private final Function toppings; private PizzaDecorator(Function... desiredToppings) { this.toppings = Stream.of(desiredToppings) .reduce(Function.identity(), Function::andThen); } public static String bakePizza(Pizza pizza, Function... desiredToppings) { return new PizzaDecorator(desiredToppings).bakePizza(pizza); } private String bakePizza(Pizza pizza) { return this.toppings.apply(pizza).bakePizza(); } } There is this line that constructs the chain of decorations to be applied: Stream.of(desiredToppings).reduce(identity(), Function::andThen); This line of code will take your decorations (which are of Function type) and chain them using andThen. This is the same as… (currentToppings, nextTopping) -> currentToppings.andThen(nextTopping) And it makes sure that the functions are called subsequently in the order you provided. Also, Function.identity() is translated to elem -> elem lambda expression. OK, now where will we define our decorations? Well, you can add them as static methods in PizzaDecorator or even in the interface: public interface Pizza { String bakePizza(); static Pizza withChickenTikka(Pizza pizza) { return new Pizza() { #Override public String bakePizza() { return pizza.bakePizza() + \\\" with chicken\\\"; } }; } static Pizza withProsciutto(Pizza pizza) { return new Pizza() { #Override public String bakePizza() { return pizza.bakePizza() + \\\" with prosciutto\\\"; } }; } } And now, this is how this pattern gets to be used: String finishedPizza = PizzaDecorator.bakePizza(new BasicPizza(),Pizza::withChickenTikka, Pizza::withProsciutto); //And if you static import PizzaDecorator.bakePizza: String finishedPizza = bakePizza(new BasicPizza(),Pizza::withChickenTikka, Pizza::withProsciutto); As you can see, the code got more clear and more concise, and we didn’t use inheritance to build our decorators. This is just one of the many design patterns that can be improved using lambdas. There are more features that can be used to improve the rest of them like using partial application (currying) to implement Adapter Pattern. I hope I got you thinking about adopting a more functional programming approach to your development style.\"",
"docName": "\"Decorator Design Pattern Using Lambdas - Voxxed.htm\""
}
]
}
When you submit a query to R&R with a trained ranker id, it will take the responses from the retrieve side of the service, and use the ranker to sort them into order based on what the ranker has "learned" about relevance.
The number of rows you fetch from the retrieve service in the first place is crucial for this.
To take the extreme case as an example, if you fetch only one row, it doesn't matter what training you've given the ranker. It has one thing to sort into order. So it will return that one thing.
If you fetch a small number of rows, for example 3, you will retrieve those three rows, and then the ranker will sort them. You will always get the same three rows - the difference the ranker makes will be what order they come in.
If you fetch a very large number of rows, for example 100, the ranker has 100 results to sort into order, so the top answer from such a query may well be different to what the top answer would be if you'd only fetched the top few.
When comparing the top result from two different apps querying the R&R service, it's therefore essential to take the rows parameter into account.
The web tooling you included a screenshot of uses a rows parameter of 30. It's retrieving 30 rows, and then using the ranker you've selected to sort them into order and display the top results.
My guess is that your application is either setting rows to something different, or not setting it at all and using the default value of 10. If you set the rows parameter in your application to 30, matching what the web tool is doing, I would expect the results to then be consistent.
There is more background about the rows parameter here : https://www.ibm.com/watson/developercloud/doc/retrieve-rank/training_data.shtml

How to populate method's return values with AutoFixture

I would like to auto-generate a method's return values in a non-deterministic manner, i.e. with every call/test run to I expect a method to return random value. For the moment it returns always default values of the method calls:
public interface IReturn
{
bool BoolMethod();
int IntMethod();
}
[Fact]
public void AllReturnsFromAutofixtureMethodsAreFalse()
{
IFixture fixture = new Fixture().Customize(new AutoNSubstituteCustomization());
IEnumerable<IReturn> theBools = fixture.CreateMany<IReturn>();
Assert.True(theBools.All(tb => tb.BoolMethod() == false));
Assert.True(theBools.All(tb => tb.IntMethod() == 0));
}
In questions like this one can find a way how to achieve similar thing for properties, however not methods. Any idea?
I haven't used AutoFixture with NSubstitute customization, however by analogy to Moq library, It seems that AutoConfiguredNSubstituteCustomization class should be used to achieve advanced AutoFixture faking behavior such that you want to. Using it you can auto-generate results from stubbed methods, as well as it is possible to create mock objects chains, injecting freezed objects into chain, an so on.

RegisterMultiple does not keep implementation type as singleton if registered as multiple registration types?

I am trying to add a type called TypeA as two different registration types: InterfaceA and InterfaceB.
container.RegisterMultiple(typeof(InterfaceA), new[] {typeof(TypeA), typeof(TypeB)});
container.RegisterMultiple(typeof(InterfaceB), new[] {typeof(TypeA), typeof(TypeC)});
But when I Resolve them, I get one instance of TypeA when resolving InterfaceA, and another instance when resolving InterfaceB. I expect to get the same instance for both resolves, but I am not.
I have also tried to add .AsSingleton() to the call, but it made no difference.
Am I doing something wrong, or does anyone have any ideas of doing this without adding a TypeAFactory or such that keeps track of the instances instead?
Thanks in advance for any help.
I think what you are seeing is by design.
To get the same instance for both interfaces you can create the instance yourself and register it for both interfaces:
var instanceOfA = new TypeA(...);
container.Register<InterfaceA>(instanceOfA);
container.Register<InterfaceB>(instanceOfA);
I solved this on my own with a quite ugly (but yet quite elegant) solution.
I create another, internal, instance of a TinyIoCContainer, and I register all my types with the actual TinyIoCContainer.Current by giving it a factory in the form of:
var container = TinyIoCContainer.Current;
var internalIoC = new TinyIoCContainer();
Dictionary<Type, Object> instances = new Dictionary<Type, Object>();
...
Func<TinyIoCContainer, NamedParameterOverloads, Object> factory = (TinyIoCContainer c, NamedParameterOverloads o) =>
{
if (instances.ContainsKey(implementationType) == false)
{
// Create the instance only once, and save it to our dictionary.
// This way we can get singleton implementations of multi-registered types.
instances.Add(implementationType, internalIoC.Resolve(implementationType));
}
return instances[implementationType];
};
container.Register(registerType, factory, implementationType.FullName);
I'm sure there will be a few caveats with this solution, but I'm also sure I'll be able to figure out a workable fix for them, as things look right now.

typesafe NotifyPropertyChanged using linq expressions

Form Build your own MVVM I have the following code that lets us have typesafe NotifyOfPropertyChange calls:
public void NotifyOfPropertyChange<TProperty>(Expression<Func<TProperty>> property)
{
var lambda = (LambdaExpression)property;
MemberExpression memberExpression;
if (lambda.Body is UnaryExpression)
{
var unaryExpression = (UnaryExpression)lambda.Body;
memberExpression = (MemberExpression)unaryExpression.Operand;
}
else memberExpression = (MemberExpression)lambda.Body;
NotifyOfPropertyChange(memberExpression.Member.Name);
}
How does this approach compare to standard simple strings approach performancewise? Sometimes I have properties that change at a very high frequency. Am I safe to use this typesafe aproach? After some first tests it does seem to make a small difference. How much CPU an memory load does this approach potentially induce?
What does the code that raises this look like? I'm guessing it is something like:
NotifyOfPropertyChange(() => SomeVal);
which is implicitly:
NotifyOfPropertyChange(() => this.SomeVal);
which does a capture of this, and pretty-much means that the expression tree must be constructed (with Expression.Constant) from scratch each time. And then you parse it each time. So the overhead is definitely non-trivial.
Is is too much though? That is a question only you can answer, with profiling and knowledge of your app. It is seen as OK for a lot of MVC usage, but that isn't (generally) calling it in a long-running tight loop. You need to profile against a desired performance target, basically.
Emiel Jongerius has a good performance comparrison of the various INotifyPropertyChanged implementations.
http://www.pochet.net/blog/2010/06/25/inotifypropertychanged-implementations-an-overview/
The bottom line is if you are using INotifyPropertyChanged for databinding on a UI then the performance differences of the different versions is insignificant.
How about using the defacto standard
if (propName == value) return;
propName = value;
OnPropertyChanged("PropName");
and then create a custom tool that checks and refactors the code file according to this standard. This tool could be a pre-build task, also on the build server.
Simple, reliable, performs.
Stack walk is slow and lambda expression is even slower. We have solution similar to well known lambda expression but almost as fast as string literal. See
http://zamboch.blogspot.com/2011/03/raising-property-changed-fast-and-safe.html
I use the following method in a base class implementing INotifyPropertyChanged and it is so easy and convenient:
public void NotifyPropertyChanged()
{
StackTrace stackTrace = new StackTrace();
MethodBase method = stackTrace.GetFrame(1).GetMethod();
if (!(method.Name.StartsWith("get_") || method.Name.StartsWith("set_")))
{
throw new InvalidOperationException("The NotifyPropertyChanged() method can only be used from inside a property");
}
string propertyName = method.Name.Substring(4);
RaisePropertyChanged(propertyName);
}
I hope you find it useful also. :-)
Typesafe and no performance loss: NotifyPropertyWeaver extension. It adds in all the notification automatically before compiling...

Resources