How to populate method's return values with AutoFixture - 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.

Related

How to create a read-only array in java?

I want to get rid of clone() method.
For the below class sonar (static code check tool) was complaining that
I should not directly expose an internal array of the object as one can change the array after the method call which in turn changes the object's state. It suggested to do a clone() of that array before returning so that object's state is not changed.
Below is my class...
class DevicePlatformAggregator implements IPlatformListings{
private DevicePlatform[] platforms = null;
public DevicePlatform[] getAllPlatforms() throws DevicePlatformNotFoundException {
if (null != platforms) {
return platforms.clone();
}
List<DevicePlatform> platformlist = new ArrayList<DevicePlatform>();
..... // code that populates platformlist
platforms = platformlist.toArray(new DevicePlatform[platformlist.size()]);
return platforms;
}
}
However I don't think its good to clone as its unnecessary to duplicate the data.
There is nothing similar to Collections.unmodifiableList() for array
I can not change the return type of the method getAllPlatforms() to some
collection as it is an interface method
I am not a Java guru but I am pretty confident that you are out of luck here. There is no way to make a primitive array immutable apart from creating an array of 0 elements.
Making it final won't help cause only the reference pointing to it would be immutable.
As you already said the way to go in obtaining an unmodifiable list would be to use Collections as in the following example:
List<Integer> contentcannotbemodified= Collections.unmodifiableList(Arrays.asList(13,1,8,6));
Hope it helps.

Is it bad to wrap singleton instance methods in static methods?

Is there a con to implementing a singleton that wraps instance methods with static ones?
For example:
public void DoStuff() { instance._DoStuff(); }
private void _DoStuff() {
...
}
And of course instance would be static. But it would be nicer to call:
Singleton.DoStuff();
Instead of:
Singleton.GetInstance().DoStuff();
I think it depends.
First the GetInstance() really should be used for getting an object back and then using that else where in your code. The Singleton should just help guarantee a single instance of that object exists.
Next if you want to make DoStuff static go ahead, though you have to know to call it that way everywhere else in your code.
So you really have this difference:
var instance = Singleton.GetInstance();
...
instance.DoStuff ()
Vs
Singleton.DoStuff ()
This means that you can pass a singleton object around and not have to know static calls.
Also, I have to mention that Singletons if not used properly can lead to a nightmare in unit testing: http://misko.hevery.com/2008/08/25/root-cause-of-singletons/

How to JUnit test an add method for a custom made ArrayList?

I implemented my custom ArrayList using a resizeable Array, and I would like to unit test my add method to check if the right value getting inserted to the right position. My add method looks like this:
public class MyArrayList<T> implements ArrayListInterface {
private int max=20;
private int index = 0;
private int[] a = new int[max];
#Override
public void add(int value) {
if(index>max-1) {
resize();
}
a[index] = value;
index++;
}
I am aware, I could just make my method boolean and check what the method returns, but I would like to check that the right value added to the right position. My problem is that my Array is private, and that way it is only possible to reach its value through a getter. Is it a good solution to make a getter for my Array, and compare that to the actual result of the test, or what would be the best solution to test this method?
I have checked couple of other stackoverflow questions in the same topic, but I couldn't find any solution for my problem.
Add a get() (get(position), getLast(), etc.) method to your class and test using this method. Unit tests should exercise the class through its interfaces, without caring about the internal implementation. Any other class that will interact with your MyArrayList will do so through add() and get().

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

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. :)

Is there a #visibility package concept in PHPDoc / PHPStorm?

I have a domain model written in PHP, and some of my classes (entities inside an aggregate) have public methods, which should never be called from outside the aggregate.
PHP does not have the package visibility concept, so I'm wondering if there is some kind of standardized way to define #package and #visibility package in the docblocks, and to have a static analysis tool that would report violations of the visibility scope.
I'm currently trying out PHPStorm, which I've found very good so far, so I'm wondering if this software has support for this feature; if not, do you know any static code analysis tool that would?
The closest parallel to this line of thinking that I see in PHP's capability is using "protected" scope rather than public for these kinds of methods. Granted, that requires using inheritance to grant access to the protected items. In my years of managing phpDocumentor, I've never encountered anything else that attempts to mimic that kind of "package scope" that I remember from my Java days.
If the entities within your aggregate root should not be modifiable without going through the aggregate root, then the only means you have to control that is making the entity a private or protected member so that all modifications to the entity have to go through the aggregate.
class RootEntity {
private $_otherEntity;
public function DoSomething() {
$this->_otherEntity->DoSomething();
}
public function setOtherEntity( OtherEntity $entity ) {
$this->_otherEntity = $entity;
}
}
Someone can still always do:
$otherEntity = new OtherEntity();
$otherEntity->DoSomethingElse();
$rootEntity->setOtherEntity($otherEntity);
Though, I guess you could use the magic __call() method to prohibit setting of the _otherEntity anywhere except during construction. This falls under total hack category :)
class RootEntity {
private $_otherEntity;
private $_isLoaded = false;
public function __call( $method, $args ) {
$factoryMethod = 'FactoryOnly_'.$method;
if( !$this->_isLoaded && method_exists($this,$factoryMethod) {
call_user_func_array(array($this,$factoryMethod),$args
}
}
public function IsLoaded() {
$this->_isLoaded = true;
}
protected function FactoryOnly_setOtherEntity( OtherEntity $otherEntity ) {
$this->_otherEntity = $otherEntity;
}
}
So, from there, when you build the object, you can call $agg->setOtherEntity($otherEntity) from your factory or repository. Then when you are done building the object, call IsLoaded(). From there, nobody else will be able to introduce a new OtherEntity into the class and will have to use the publicly available methods on your aggregate.
I'm not sure if you can call that a "good" answer, but it's the only thing I could think of to truly limit access to an entity within an aggregate.
[EDIT]: Also, forgot to mention...the closest for documentation is that there is an #internal for phpdoc:
http://www.phpdoc.org/docs/latest/for-users/tags/internal.html
I doubt that it will modify the IDE's code completion, however. Though, you could probably make a public function/property but label it as "#access private" with phpdoc to keep it from being in code completion.
So far, PHPStorm does not seem to provide this feature.

Resources