In Prism 8 with DryIoC, how do I mock the IContainerRegistry when I need to unit test code in RegisterTypes? - unit-testing

I have a requirement to access the container directly because Prism's IContainerRegistry doesn't provide me the ability to pass parameters through the constructor of an instance I am registering.
However I can't mock IContainerRegistry because I have to call .GetContainer() on it, which is a static extension method.
In short, if I have to access the container directly to do something more complex than IContainerRegistry and IContainerProvider provide in their interfaces and have to get the container directly via .GetContainer(), what is the best way to unit test RegisterTypes(IContainerRegistry) and OnInitialized(IContainerProvider)?
I considered passing in a concrete implementation of the IContainerRegistry but this is much less than ideal.
I also don't think I can create a wrapper for the extension method since I can't change the signature of RegisterTypes as this is an implementation detail of the Prism library and not my own code.

Related

Why database types aren't interface in GO

There is an emphasis on using interfaces instead of concrete types in order to make the code easier to test. I wonder though why this wasn't done for the types in the sql package like DB or Rows. In order to mock those dependencies I had to create my own interfaces so that I could write unit tests (not integration tests). Aren't DB facing code supposed to be tested that way?
Exposing interfaces in your public API instead of concrete types increases the risk of breaking other peoples code when you add methods to the interface.
See for example os.File. If os.File was an interface it would be an interface with 17 public methods. Adding an 18th method would break everyone who defined their own types that implemented the os.File interface. In contrast, adding an 18th method to the current os.File struct won't break any methods taking an io.Reader, io.Writer or any other interface that defines a subset of the methods of an os.File. It also won't break test code which mocks these io.Reader and io.Writer interfaces.
So expose an interface in your public API if you want other people to define their own implementations of them. Otherwise expose a concrete type and let people define their own interfaces implemented by your concrete type using only the subset of methods they need.

Fake objects vs Mock objects

In the TDD there is two concept: fake objects and mock objects. These two concepts are used in case a class you want to test is interacting with other classes or objects or databases...
My question is : what is the difference between the two? and when can I use each one of them?
Edit:
I found this answer:
What's the difference between faking, mocking, and stubbing?
But I'm still confused about the difference between the two:
both of them create implementation of the components, with light implementation for a Fake. But, what do they mean by "light implementation" of "shortcut" in case of a fake?
And what is the difference between how a Mock object works, and the real object work?
A fake implementation for a DataSet for instance, would simply return a static set of data. A mock would pretty much be a full implementation that would be able to generate various sets of data depending upon input. If you were mocking away your data layer, you would be able to execute your command objects against the mock and it would be robust enough to return data with a "valid" statement, or throw exceptions with an invalid statement. All without actually connecting to a database or file.
As for the differences between mock and real, usually when mocking a class away, you would create a factory object that, by default, returns the real object, but when you write your tests, you can tell it to return a specific mock class. The mock class either implements the same interfaces as the real object, or you use a wrapper class that mimics the underlying real class, but allows for dependency injection for the critical parts to generate data without making the external calls.

How to verify method class in test class

I have a repository with a method called ConvertToBusinessEntity which converts the data from the data source to a business object. This method is supposed to be used by other methods in the repository namely the Get, GetAll, etc.
This method is unit tested. I check if the data is being retrieved correctly from the data source and the values are being put in the entity correct properties.
But now I need to test and create the GetEntity method which is supposed to call ConvertToBusinessEntity. The logic behind ConvertToBusiness is tested. I just need to know how to verify that a method in the class being tested is called (not a dependency).
Does anyone know how to do this or any alternative method?
I thought of an alternative method but I am not sure if it's the best. I could extend the class under test and have a counter increasing each time the method is called.
Another one would be to mock the class itself.
What do you think? Any other suggestions?
Having ConvertToBusinessEntity in repository is not very good idea. Responsibility of repository is working with data store (CRUD). Mapping of data types is responsibility of some mapper class. Otherwise your repository has too many responsibilities. Take a look on what you are trying to test:
I check if the data is being retrieved correctly from the data source
and the values are being put in the entity correct properties
You see this and? Your test can fail on two completely different reasons. Also you should change repository on two completely different reasons. Best approach here is persisting business entities directly. Modern ORMs allows doing that without polluting business entity with attributes or forcing it inheriting some data-access specific class.
If you really want to have data mapping logic in repository, then make it private (actually only repository should require conversion of business entity to some data-access object) and don't care how this logic is implemented. Let it be part of internal class implementation. You should care only about repository being able to accept or return filled business entities - that's the responsibility of repository. It doesn't matter how mapping is implemented in repository. You should test what repository does, instead of how. So just check that expected business objects are returned by repository.
I just need to know how to verify that a method in the class being tested is called (not a dependency).
But do you really need to do that? If your GetEntity method operates correctly, do you really care how it operates? Do you really care if it performs its function by delegating to ConvertToBusiness, or by some other means?
I recommend instead that you
Think of each method as having a specification.
That specification describes what the outputs and publicly visible manipulations it must make. That do not describe how a method performs its function; that is an implementation detail that could change.
Your unit tests check only that your methods conform to their specification.
You might nevertheless use your knowledge about the implementation to choose good test cases.
But, you might declare, if I do that I am not unit testing my method code; my test of GetEntity depends on both the GetEntity method and the ConvertToBusiness method: two units, so an integration test rather than a unit test. But do you mock the methods of the runtime environment? Of course not. The line between unit and integration testing is not so clear.
More philosophically, you can not create good mock objects in many cases. The reason is that, for most methods, the manner in which an object delegates to associated objects is undefined. Whether it does delegate, and how, is left by the specification as an implementation detail. The only requirement is that, on delegating, the method satisfies the preconditions of its delegate. In such a situation, only a fully functional (non-mock) delegate will do. If the real object checks its preconditions, failure to satisfy a precondition on delegating will cause a test failure. And debugging that test failure will be easy.

Unit Testing mGo

I have a function that accepts a database *mgo.Database parameter.
func myFunc(db *mgo.Database) {
// does some operations with db
}
I would like to write a unit test and pass in a mocked db object, but I'm having a very difficult time figuring out how to do that with golang. In other languages I could use there testing frameworks to do a myMock = createMock("Class to Mock"), but with Go I'm not sure how to do this.
I glanced at gomock, but wasn't sure if that is the only way, and wasn't sure how to use the mockgen tool with mgo.
I also thought maybe to write an interface that has all of the same methods as mgo.Database and pass a "mocked" object that uses the interface, and then create an object that uses the interface and passes calls through to mgo's library (similar to an ORM), but that seems like a lot of coding.
*mgo.Database is a pointer to a type, not an interface, you can't mock it.
As in other languages - you need to provide a level of indirection, so that you can provide a real object in production but a mock for testing. So your first step is to extract the interface that your "myFunc" uses (which methods it calls), then you can provide *mgo.Database in production and your mock (manual mock or using some mocking framework) for testing.
This free sample chapter from great book "The Art of Unit Testing" explains the steps you need to do on page 52 (chapter 3, "Using stubs to break dependencies" - "3.3 Determining how to easily test LogAnalyzer"):
http://www.manning.com/osherove/SampleChapter3.pdf
given that in Go a type implements the interface just by implementing the interface's methods - it's even easier than in other languages (like C# for example)
so the answer is as you said
to write an interface that has all of the same methods as mgo.Database
and pass a "mocked" object that uses the interface, and then create an
object that uses the interface and passes calls through to mgo's
library (similar to an ORM), but that seems like a lot of coding.
except that you don't need to create an object that uses the interface and passes calls through to mgo's library (similar to an ORM) because *mgo.Database will implicitly satisfy your interface. So it's not a lot of coding.
You can use Docker on your unit testing too.
I've created a library to help this kind of testing: https://github.com/skarllot/raiqub
Example: https://github.com/raiqub/data/blob/v0.4/mongostore/store_test.go

Should dynamic dependencies of service objects be avoided?

This question is about testable software design based on mostly value objects and services.
Services that have static dependencies are straightforward to instantiate or configure when using a DI container. However, in some cases, services require dependencies that are known at runtime only.
Say, imagine a simple FileSystemDataStore with some CRUD methods in it for managing files in a directory. This service will need a directory name as one of its constructor parameters. That name could be known at runtime only and will have to be provided by its collaborators.
This seems to be somewhat of a problem because you can't configure such service in a DI container because of its dynamic nature. You'll probably have to use a factory to create such services. However, this will result in a quirk in the unit tests of the service's clients. You will have to mock the factory to return a mock of the service. This adds additional complexity to unit tests. Mocks returning mocks is often considered a test smell.
What is your opinion about this problem? Is it even a problem in your experience? Should such services be instead refactored to be more "pure"?
As a general observation, when services depend on run-time values, an Abstract Factory is indeed the appropriate response.
However, as pointed out in the question, this does have an impact on the maintainability of the tests, so if you can redesign the API to avoid such situations, you should do that. It's not always possible, though.
You would like to inject the directory name, but it is not known during the construction phase. I see three options here.
1. Inject a Provider
Instead of saying "Here is the directory name you need" you are saying "Here is an object that can give you the directory name at run-time". The way to implement this is to declaring a constructor argument Provider<String> directoryNameProvider. The constructor stores a reference to this provider as a member variable. When called apon to do some real-work in the run phase, the class would contain code like this when the directory name is needed:
directoryName = directoryNameProvider.get();
In java, the interface you implement is [javax.inject.Provider<T>][1]. This has a single method: get() which returns type T. The use of the generic provider interface means you do not have a proliferation of intefaces.
When it comes to your unit test, you can inject an anonymous inner class that implements the single method of Provider<T> to return a constant value easily enough. Our code base has a SimpleProvider<T> class that wraps a given object in the Provider interface.
Pro: Allows you to construct the object in the main construction phase. Unit testing is pretty easy.
Con: Details about dependency creation issues are leaking into the class when they should entirely be the concern of the factory. Too bad if the class is already written and accepts directoryName rather than directoryNameProvider already.
Despite the seemingly long list of cons, this is an option I use alot. It is my opinion that there is a missing language construct here.
2. Construct the troublesome object later
You can enter an inner scope when you know more. Within a run-phase method, you can enter a new scope. This means that you go through a whole new mini-construction phase, and then a mini-run phase. Ths is similiar to what happens in your application main() but at a smaller level.
Pro: Class receiving the dependency remains pure.
Con: Entering and exiting too many scopes can make the application and object life-cycles difficult to understand.
3. Use a method argument
You can decide that directoryName is to be a method argument and pass it to your class during the run phase rather than trying to inject it as a constructor argument. This is effectively deciding not to use dependency inject style for this occasion.
Pro: Simplicity
Con: Class that passes directoryName as a method parameter is tightly coupled to the class that needs it. It will be very difficult to implement an alternate implementation that depends on say, a database connection.
These are matters that I have been considering alot lately, so I'm interested in any comments or edits. Are there any other options?