Leave out passthrough parameters - unit-testing

Consider this example:
case class Home(description: String)
case class Person(age: Int, race: String, home: Home)
def age(p: Person): Person = {
val newAge = p.age + 1
p.copy(age = newAge, home = if (newAge == 18) Home("Under the bridge") else p.home)
}
it("Should move on 18th birthday") {
val person18yrs = age(Person(17, "Caucasian", Home("With parents")))
person18yrs shouldBe Person(18, "Caucasian", Home("Under the bridge"))
}
Now if I want to test the method age, I need to fill the field race even though the method age doesn't discriminate the person object based on it's race. It's only pass-through parameter. In this trivial example, it's not so much work, but when i work with two fields in a 20-field class hierarchy, I'm not happy. And I want to be happy. So I start to look around for some solution.
One solution might be to fill the empty fields with nulls. But the downside is if I then change the implementation, it would convert test classes compile error to tests failure. And I still need to write these nulls.
The other solution might be to just create the methods so they accept and return the parameters with which they interact. The downside is that I need to return tuples, which lack the name or I need to create some classes that encapsulate the method parameters and return types.
Or maybe the smart folks of stackoverflow do have some other solution, that half-blind eye of my intelligence cannot see. :-)

Create one completely filled person as a prototype, and then just create copies with the values that are relevant to your specific test case.
val protoype = Person(16, "Caucasian", Home("With parents"))
val person18yrs = age(protoype.copy(age = 17))

You could define factories with the same names as your case classes but fewer arguments, and have them create corresponding objects to which you pass default arguments, for example:
case class Person(age: Int, race: String, home: Home)
def Person(age: Int): Person = Person(age, "", Home(""))
Access to these factories could be limited to the test suite in order to avoid that they are used in non-rest-related code of your application.

Related

In Kotlin, how can one unit test that a data class, sealed class, or class field are not changed?

Basically we might have some data like so
open class RealmCart : RealmObject() {
#PrimaryKey
var _id: String = UUID.randomUUID().toString()
var items: RealmList<RealmCartItem> = RealmList()
var discountCode: String? = null
var userId: String = ""
}
And we do not want people editing these by mistake. We have some failsafe like code owners, labels in the repo, but we also want to have a unit test that can also prevent a merge if the data is changed in any way (add, change, or remove data). Basically, we do not want any accidents, and people are not perfect.
What is the best way to go about such a thing?
This is what I ended up doing:
I created an extension function for my data models
fun RealmObject.testDeclaredFields(): List<String> {
val fields = this::class.java.fields.map { it.name }
return this::class.java.declaredFields
.map { it.name }
.filterNot { fields.contains(it) }
.sorted()
}
Basically this just gets the data model fields, excluding things like companion objects.
Then I was able to create a test simply like
class RealmMessageTest {
#Test
fun `RealmMessage fields match spec`() {
val item = RealmMessage().testDeclaredFields()
assertContentEquals(item, fieldSpec)
}
private val fieldSpec = listOf(
"_id",
"acknowledgeStatusValue",
"body",
"completed",
"createdAt",
"deliveryStatusValue",
"from",
"meta",
"organizationId",
"platforms",
"threadId",
"title"
).sorted()
}
Why do this? Sometimes when someone is making changes carelessly, they will not realize that they have added a field, changed a field, or removed an important field in a data model that is sync'd to the backend. This does not prevent the developer from changing it, but given that they need to now change it in two places, they will be more cognizant whether they need to make this change or not.
I noticed a lot of people questioned why you would need to do this. My answer is that, I work in a very large repo where newer developers edit this without a second thought. This is just to make them more cognizant of changes to these important models, before they break develop. There are code owners for the repo, but they may not always see these changes. It is just an extra precaution.
How about using a mechanism like githooks to prevent the editing of certain files from being committed?
I'm not familiar with githooks, so I can't show you exactly how to do it, but I think it would be good to prevent commits and inform the developer of the situation with an error message.

How to back a MutableList<Uri> field with a MutableList<String>

I have an interface that looks like that:
interface MyObject {
val id: String
val media: MutableList<Uri>
}
I would like to make an implementation of it where the media list is backed by a MutableList<String> instead of MutableList<Uri> (the reason I need that is explained in my long question here). The easy way is:
data class MyObjectPojo(
override val id: String,
val mediaStringList: MutableList<String>
) : Tale {
override val media: MutableList<Uri>
get() = mediaStringList.map { Uri.parse(it) } as MutableList<Uri>
}
But it's obviously inefficient (e.g. in order to get only the first element, a map operation would run for the whole list). I thought about get() = object : MutableList<Uri> {...}, But I realized I have to implement more then 20 members... Is there any nicer way to achieve that?
One option is to extend AbstractList, which could be as simple as:
val media = object : AbstractList<URL>() {
override val size get() = mediaStringList.size
override fun get(index: Int) = Uri.parse(mediaStringList[index])
}
That gives you a read-only view of the underlying mediaStringList: any changes to that are immediately reflected in the view.
Like most performance issues, it's a trade-off: it doesn't store any data itself, but needs to create a new Uri each time an item is retrieved.  So it's a good idea only when you need to save memory at the expense of extra processing; or when the list is likely to be big compared with the number of items retrieved.
If you want the view to be writable, you could instead extend AbstractMutableList, and override three more methods.  (That's left as an exercise :-)
PS. I'd suggest initialising media to this object, rather than creating it in a getter, as the latter will create a new view every time the getter is called, which is wasteful.  (If you were concerned about creating even a single view for each MyObjectPojo, you could wrap it in by lazy {…} so that it would only be created the first time it was needed — at the cost of some synchronisation.)

Inspect Ember.js: Get the type of an object (Class)?

I use console.log() a lot, especially in combination with Ember.inspect(). But there's one thing I miss:
How can I find out the type of an object (Class)?
For example: Getting something like <Sandbox.ApplicationController:ember288> when inspecting Ember.get("controller")?
If you just want the model name (for example app/models/comment.js has the model name comment), you can use thing.constructor.modelName.
For example:
var aComment = this.get('store').createRecord('comment');
aComment.get('constructor.modelName') // => 'comment'
I understand you are looking for a string for debugging purposes, but I originally came to this question wanting to know specifically how to get the type of the object, not a string describing the object.
Using the built in Javascript property constructor will yield the class used to construct the instance. For example you could do:
person = App.Person.create();
person.constructor // returns App.Person
person.constructor.toString() // return "App.Person"
If you get Class, you can usually call toString() (or as a shortcut concat an empty string + '') to get something like <Sandbox.ApplicationController:ember288>
Another useful feature (in chrome) is the dir command.
dir(App.User)
This will give you the full object information, rather than just the name.
Be aware that some of these answers suggested here only work in development. Once your code is in production most of those methods / class names will get minified.
import Model from '#ember-data/model';
export default class Animal extends Model {
// ...
}
So in development:
const model = this.store.createRecord('animal');
model.constructor.name // returns Animal
in production:
const model = this.store.createRecord('animal');
model.constructor.name // returns 'i' (or any other single letter).
To avoid this, use constructor.toString()
const model = this.store.createRecord('animal');
model.constructor.toString() // returns 'model:animal'

How to write a Mockist test of a recursive method

If I have a method that calls itself under a certain condition, is it possible to write a test to verify the behavior? I'd love to see an example, I don't care about the mock framework or language. I'm using RhinoMocks in C# so I'm curious if it is a missing feature of the framework, or if I'm misunderstanding something fundamental, or if it is just an impossibility.
a method that calls itself under a certain condition, is it possible to write a test to verify the behavior?
Yes. However, if you need to test recursion you better separate the entry point into the recursion and the recursion step for testing purposes.
Anyway, here is the example how to test it if you cannot do that. You don't really need any mocking:
// Class under test
public class Factorial
{
public virtual int Calculate(int number)
{
if (number < 2)
return 1
return Calculate(number-1) * number;
}
}
// The helper class to test the recursion
public class FactorialTester : Factorial
{
public int NumberOfCalls { get; set; }
public override int Calculate(int number)
{
NumberOfCalls++;
return base.Calculate(number)
}
}
// Testing
[Test]
public void IsCalledAtLeastOnce()
{
var tester = new FactorialTester();
tester.Calculate(1);
Assert.GreaterOrEqual(1, tester.NumberOfCalls );
}
[Test]
public void IsCalled3TimesForNumber3()
{
var tester = new FactorialTester();
tester.Calculate(3);
Assert.AreEqual(3, tester.NumberOfCalls );
}
Assuming you want to do something like get the filename from a complete path, for example:
c:/windows/awesome/lol.cs -> lol.cs
c:/windows/awesome/yeah/lol.cs -> lol.cs
lol.cs -> lol.cs
and you have:
public getFilename(String original) {
var stripped = original;
while(hasSlashes(stripped)) {
stripped = stripped.substringAfterFirstSlash();
}
return stripped;
}
and you want to write:
public getFilename(String original) {
if(hasSlashes(original)) {
return getFilename(original.substringAfterFirstSlash());
}
return original;
}
Recursion here is an implementation detail and should not be tested for. You really want to be able to switch between the two implementations and verify that they produce the same result: both produce lol.cs for the three examples above.
That being said, because you are recursing by name, rather than saying thisMethod.again() etc., in Ruby you can alias the original method to a new name, redefine the method with the old name, invoke the new name and check whether you end up in the newly defined method.
def blah
puts "in blah"
blah
end
alias blah2 blah
def blah
puts "new blah"
end
blah2
You're misunderstanding the purpose of mock objects. Mocks (in the Mockist sense) are used to test behavioral interactions with dependencies of the system under test.
So, for instance, you might have something like this:
interface IMailOrder
{
void OrderExplosives();
}
class Coyote
{
public Coyote(IMailOrder mailOrder) {}
public void CatchDinner() {}
}
Coyote depends on IMailOrder. In production code, an instance of Coyote would be passed an instance of Acme, which implements IMailOrder. (This might be done through manual Dependency Injection or via a DI framework.)
You want to test method CatchDinner and verify that it calls OrderExplosives. To do so, you:
Create a mock object that implements IMailOrder and create an instance of Coyote (the system under test) by passing the mock object to its constructor. (Arrange)
Call CatchDinner. (Act)
Ask the mock object to verify that a given expectation (OrderExplosives called) was met. (Assert)
When you setup the expectations on the mock object may depend on your mocking (isolation) framework.
If the class or method you're testing has no external dependencies, you don't need (or want) to use mock objects for that set of tests. It doesn't matter if the method is recursive or not.
You generally want to test boundary conditions, so you might test a call that should not be recursive, a call with a single recursive call, and a deeply-recursive call. (miaubiz has a good point about recursion being an implementation detail, though.)
EDIT: By "call" in the last paragraph I meant a call with parameters or object state that would trigger a given recursion depth. I'd also recommend reading The Art of Unit Testing.
EDIT 2: Example test code using Moq:
var mockMailOrder = new Mock<IMailOrder>();
var wily = new Coyote(mockMailOrder.Object);
wily.CatchDinner();
mockMailOrder.Verify(x => x.OrderExplosives());
There isn't anything to monitor stack depth/number of (recursive) function calls in any mocking framework I'm aware of. However, unit testing that the proper mocked pre-conditions provide the correct outputs should be the same as mocking a non-recursive function.
Infinite recursion that leads to a stack overflow you'll have to debug separately, but unit tests and mocks have never gotten rid of that need in the first place.
Here's my 'peasant' approach (in Python, tested, see the comments for the rationale)
Note that implementation detail "exposure" is out of question here, since what you are testing is the underlying architecture which happens to be utilized by the "top-level" code. So, testing it is legitimate and well-behaved (I also hope, it's what you have in mind).
The code (the main idea is to go from a single but "untestable" recursive function to an equivalent pair of recursively dependent (and thus testable) functions):
def factorial(n):
"""Everyone knows this functions contract:)
Internally designed to use 'factorial_impl' (hence recursion)."""
return factorial_impl(n, factorial_impl)
def factorial_impl(n, fct=factorial):
"""This function's contract is
to return 'n*fct(n-1)' for n > 1, or '1' otherwise.
'fct' must be a function both taking and returning 'int'"""
return n*fct(n - 1) if n > 1 else 1
The test:
import unittest
class TestFactorial(unittest.TestCase):
def test_impl(self):
"""Test the 'factorial_impl' function,
'wiring' it to a specially constructed 'fct'"""
def fct(n):
"""To be 'injected'
as a 'factorial_impl''s 'fct' parameter"""
# Use a simple number, which will 'show' itself
# in the 'factorial_impl' return value.
return 100
# Here we must get '1'.
self.assertEqual(factorial_impl(1, fct), 1)
# Here we must get 'n*100', note the ease of testing:)
self.assertEqual(factorial_impl(2, fct), 2*100)
self.assertEqual(factorial_impl(3, fct), 3*100)
def test(self):
"""Test the 'factorial' function"""
self.assertEqual(factorial(1), 1)
self.assertEqual(factorial(2), 2)
self.assertEqual(factorial(3), 6)
The output:
Finding files...
['...py'] ... done
Importing test modules ... done.
Test the 'factorial' function ... ok
Test the 'factorial_impl' function, ... ok
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK

How to write tests with mocks using f#

I'd like to write F# unit test with mock objects. I'm using NUnit.
But unfortunately I couldn't find any examples.
Here's an example of the code under test:
type ICustomer = interface
abstract Id: int with get
abstract Name: string with get
abstract CalculateBalanceWithDiscount: decimal -> decimal
end
type Customer = class
val id: int
val name: string
val balance: decimal
new(id, name, balance) =
{id = id; name = name; balance = balance}
interface ICustomer with
member this.Id
with get () = this.id
member this.Name
with get () = this.name
member this.CalculateBalanceWithDiscount discount =
this.balance - (discount * this.balance)
end
end
As a side-note, you can use implicit constructor syntax to make your class declaration a bit nicer. You can also simplify readonly properties, because you can omit with get():
// F# infers that the type is an interface
type ICustomer =
abstract Id : int
abstract Name : string
abstract CalculateBalanceWithDiscount : decimal -> decimal
// Parameters of the implicit constructor are autoamtically
// accessible in the body (they are stored as fields)
type Customer(id:int, name:string, balance:decimal) =
interface ICustomer with
member this.Id = id
member this.Name = name
member this.CalculateBalanceWithDiscount(discount) =
balance - (discount * balance)
Regarding testing - do you have any example of what you're trying to achieve? I'm sure we can help for example with translating code from C#. Or what kind of tests would you like to write using mocking?
In general, a nice thing about F# and functional languages is that you can usually test code more easily without using any mocks. Functional programs are written in a different style:
In functional programming, a function takes all it's inputs as arguments and the only thing that it does is that it calculates and returns some result. This is also true for methods of immutable object types - they do not modify any state of any objects
Mocks are typically used for two purposes:
To verify that the tested operation performed some call to a method of a referenced object e.g. prod.Update(newPrice) to update the state of the object. However, in functional programming the method should instead return the new state as the result - so you don't need mock object. Just check whether the new returned state is what you expected.
To load create a fake component of the application, for example instead of loading data from the database. Again, a purely functional function should take all it's inputs as arguments. This means that you don't need to create a mock object - you just call the function with some test data as argument (instead of data loaded from database).
In summary, this means that in a well-designed functional program, you should be able to write all unit tests simply as checks that verify that some function returns the expected result for the expected arguments. Of course, this isn't strictly true in F#, because you may need to interoperate with other impure .NET components (but that can be answered only if you give a more specific example).
You don't need to create a class in order to create mocks:
/// customer : int -> string -> decimal -> ICustomer
let customer id name balance =
{new ICustomer with
member this.Id = id
member this.Name = name
member this.CalculateBalanceWithDiscount discount =
balance - (discount * balance) }