DEV Community

Discussion on: Dependency injection in functional programming

Collapse
 
psfeng profile image
Pin-Sho Feng • Edited

Thanks a lot, I'm very glad to hear that!

I generally agree that mocking is a smell. Note that mocking refers to a testing technique, it's not a synonym for DI. Strictly speaking, mocking is about verifying that certain methods are called on some object and as such you're testing implementation details. See here.

Testing implementation details has the problem that it makes tests more difficult to maintain. For example, if you change the name of the method you're expecting to be called, you have to change all the tests that depend on this method, but the behavior may be exactly the same.

I prefer feature testing and avoid mocking as much as possible. Check these resources:
blog.twitter.com/engineering/en_us...
blog.kentcdodds.com/write-tests-no...

Collapse
 
koresar profile image
Vasyl Boroviak

I mock only I/O related things in my tests. Thus I call it mocking. Probably wrong term usage. Apologies.

Do I understand it right that a way of replacing side effect function is called DI in the article above?
And isn't it just a way to mock that function?

I'm confused.

Thread Thread
 
psfeng profile image
Pin-Sho Feng

DI refers to dependency injection, which is basically passing a dependency as a parameter to a function instead of having the function call it directly. For example:

fun doSomething() {
    fetchItemsFrom("http://someurl.com/items") // this is hardcoding the URL that you want to use
}

fun doSomething(url: String) {
    fetchItemsFrom(url) // now url is "injected" to the function.
} 

fun doSomething(fetchItems: () -> Unit) {
    fetchItems() // you can also choose to pass the whole function
}

DI and mocking for testing are related in that you can pass mocks (or stubs) to the function under test. If what you're injecting is a side-effectful function, you can indeed replace it with some mock function that doesn't have side-effects, just for the purposes of testing.

Let me know if it's clearer now!

Thread Thread
 
koresar profile image
Vasyl Boroviak

The only difference I see is that with DI the replaced value can be data.

Sorry. I still believe DI and ability to mock is the same concept - ability to replace a thing down the call chain.

Thread Thread
 
psfeng profile image
Pin-Sho Feng

Dependency injection is a concept and the ability to mock is a consequence of this concept, but it's by no means the only benefit.

You could, for example, use some class across different sections of an app but have it behave differently depending on the section. Using the dependency injector you can configure the different instances of the class that will be used in each section.