MOQ WCF Service - wcf

I need to MOQ wcfClientService while calling the SomeMethod().
Class ABC : IABC
{
internal WcfClientService wcfClientService = new WcfClientService();
public void SomeMethod(object pqr)
{
using(wcfClientService)
{
wcfClientService.Save(some parameters)
}
}
}

With the current implementation, you cannot isolate the "ABC" class as it is tightly coupled with wcfClientService. I would strongly suggest things mentioned below:
Extract an interface IClientService. This makes your "ABC" class depend on an abstraction instead of a concrete implementation. It will help in short term to isolate "ABC" better for unit testing. In long term, your "ABC" class would not have to be changed if a "RestfulClientService" was to be used.
Consider introducing a Dependency Injection framework. Anything like a Spring.Net, Unity or Autofac should serve the purpose. Ideally, your production code should never instantiate a dependency. Let the framework take care of it.
Now, register and resolve a mock implementation of the interface using the DI framework and start unit testing the "ABC" class.

Related

How implement the same instance of a clas throughout the app?

I am trying to implement a NotificationService in a correct way from the point of view of OOP. For this I have the next interface:
abstract class NotificationsService {
void initNotificationsHandlers();
int sendGeneralNotification({String? title, String? body});
//...
}
And his subclass:
class FirebaseNotificationService extends NotificationsService {
//All implementations...
}
The problem is when I implement it. I have to instance it on the main:
NotificationsService notificationsService = new FirebaseNotificationService();
But I have to use this service in more classes,and I don't want to instance the FirebaseNotificationService in every class because I would be violating the Dependency Inversion Principle. I want other classes just know the abstraction NotificationsService.
I have thought using something like this:
abstract class NotificationsService {
///Current notification service subclass used.
static final NotificationsService instance;
//...
}
And then implementing the class this way:
Main
NotificationsService.instance = new FirebaseNotificationService();
Other class
NotificationsService.instance.initNotificationsHandlers(); // For example, it could be any method
But it doesn't look very clean because I am using the NotificationService interface to "save" the current subclass. I think it shouldn't be his responsibility.
Maybe should I make another class which "saves" the current implementation? Or apply a singleton pattern? What is the OOP most correct way to do this?
Clarification: I am not asking for a personal opinion (otherwise this question should be close). I'm asking about the correct OOP solution.
In which language are you programming? Java probably, by reading your Code.
What you actually want is Dependency Injection and a Singleton (even though I think that Singleton is overkill for a NotificationService)
If we remain at the Java Standard, it works in this way:
The classes that need your NotificationService would have a constructor annotated with #Inject and an agument of type NotificationService (not your Implementation Class) - so your consumer classes rely on something abstract rather than something concrete, which makes it easier to change the implementation.
The Dependency Injection Container or Framework would take care that when your classes are being injected by them self somewhere, that their Dependencies are being satisfied in order to be able to construct this class.
How does it actually know which Implementation belongs to an Interface?
Well it depends on the Framework or Platform you are using but you either define your bindings of the interface to the concrete class or is is looking it up with reflection (if we are using Java)
If a class gets injected with a new Instance every time or always the same instance this depends on your annotations on the class itself. For example you could annotate it with #Singleton.
I hope it helps a bit.

Mocking EntityManager

I am getting NPE while mocking EntityManager, below is my code,
#Stateless
public class NodeChangeDeltaQueryBean implements NodeChangeDeltaQueryLocal {
#PersistenceContext
private EntityManager em;
#Override
public String findIdByNaturalKey(final String replicationDomain, final int sourceNodeIndex,
final int nodeChangeNumber) {
List<String> result =
NodeChangeDelta.findIdByNaturalKey(this.em, replicationDomain, sourceNodeIndex,
nodeChangeNumber).getResultList();
return result.isEmpty() ? null : result.get(0);
}
}
My Entity Class
#Entity
public class NodeChangeDelta implements Serializable, Cloneable, GeneratedEntity, KeyedEntity<String> {
public static TypedQuery<String> findIdByNaturalKey(final EntityManager em, final String replicationDomain, final int sourceNodeIndex, final int nodeChangeNumber) {
return em.createNamedQuery("NodeChangeDelta.findIdByNaturalKey", String.class)
.setParameter("replicationDomain", replicationDomain)
.setParameter("sourceNodeIndex", sourceNodeIndex)
.setParameter("nodeChangeNumber", nodeChangeNumber);
}
}
My Test Class
#RunWith(MockitoJUnitRunner.class)
public class NodeChangeDeltaQueryBeanTest {
#InjectMocks
NodeChangeDeltaQueryBean nodeChangeDeltaQueryBean;
#Mock
EntityManager em;
#Test
public void testFindIdByNaturalKey() {
this.addNodeChangeDelta();
this.nodeChangeDeltaQueryBean.findIdByNaturalKey(this.REPLICATION_DOMAIN,
this.SOURCE_NODE_INDEX, this.NODE_CHANGE_NUMDER);
}
}
While debugging em is not null (also other arguments REPLICATION_DOMAIN,
SOURCE_NODE_INDEX, NODE_CHANGE_NUMDER not null) in Entity class, whereas em.createNamedQuery("NodeChangeDelta.findIdByNaturalKey", String.class) is null.
On the mockito wiki : Don't mock types you don't own !
This is not a hard line, but crossing this line may have repercussions! (it most likely will.)
Imagine code that mocks a third party lib. After a particular upgrade of a third library, the logic might change a bit, but the test suite will execute just fine, because it's mocked. So later on, thinking everything is good to go, the build-wall is green after all, the software is deployed and... Boom
It may be a sign that the current design is not decoupled enough from this third party library.
Also another issue is that the third party lib might be complex and require a lot of mocks to even work properly. That leads to overly specified tests and complex fixtures, which in itself compromises the compact and readable goal. Or to tests which do not cover the code enough, because of the complexity to mock the external system.
Instead, the most common way is to create wrappers around the external lib/system, though one should be aware of the risk of abstraction leakage, where too much low level API, concepts or exceptions, goes beyond the boundary of the wrapper. In order to verify integration with the third party library, write integration tests, and make them as compact and readable as possible as well.
Mock type that you don't have the control can be considered a (mocking) anti-pattern. While EntityManager is pretty much standard, one should not consider there won't be any behavior change in upcoming JDK / JSR releases (it already happened numerous time in other part of the API, just look at the JDK release notes). Plus the real implementations may have subtleties in their behavior that can hardly be mocked, tests may be green but the production tomcats are on fire (true story).
My point is that if the code needs to mock a type I don't own, the design should change asap so I, my colleagues or future maintainers of this code won't fall in these traps.
Also the wiki links to other blogs entries describing issues they had when they tried to mock type they didn't have control.
Instead I really advice everyone to don't use mock when testing integration with another system. I believe for database stuff, Arquillian is the thing to go, the project appears to be quite active.
Adapted from my answer : https://stackoverflow.com/a/28698223/48136
In Mockito, any method invocation on a mock that is not explicitly configured, always returns null. Therefore in findIdByNaturalKey, em.createNamedQuery is returning null and so NPE on setParameter. You need to configure it to RETURN_MOCKS.
Also, I am not sure if #InjectMocks supports #PersistenceContext. If it does not then em is probably null. If it does, please let me know and the above is your issue.

Autofac: Resolving dependencies with parameters

I'm currently learning the API for Autofac, and I'm trying to get my head around what seems to me like a very common use case.
I have a class (for this simple example 'MasterOfPuppets') that has a dependency it receives via constructor injection ('NamedPuppet'), this dependency needs a value to be built with (string name):
public class MasterOfPuppets : IMasterOfPuppets
{
IPuppet _puppet;
public MasterOfPuppets(IPuppet puppet)
{
_puppet = puppet;
}
}
public class NamedPuppet : IPuppet
{
string _name;
public NamedPuppet(string name)
{
_name = name;
}
}
I register both classes with their interfaces, and than I want to resolve IMasterOfPuppets, with a string that will be injected into the instance of 'NamedPuppet'.
I attempted to do it in the following way:
IMasterOfPuppets master = bs.container.Resolve<IMasterOfPuppets>(new NamedParameter("name", "boby"));
This ends with a runtime error, so I guess Autofac only attempts to inject it to the 'MasterOfPuppets'.
So my question is, how can I resolve 'IMasterOfPuppets' only and pass parameter arguments to it's dependency, in the most elegant fashion?
Do other ioc containers have better solutions for it?
Autofac doesn't support passing parameters to a parent/consumer object and having those parameters trickle down into child objects.
Generally I'd say requiring the consumer to know about what's behind the interfaces of its dependencies is bad design. Let me explain:
From your design, you have two interfaces: IMasterOfPuppets and IPuppet. In the example, you only have one type of IPuppet - NamedPuppet. Keeping in mind that the point of even having the interface is to separate the interface from the implementation, you might also have this in your system:
public class ConfigurablePuppet : IPuppet
{
private string _name;
public ConfigurablePuppet(string name)
{
this._name = ConfigurationManager.AppSettings[name];
}
}
Two things to note there.
First, you have a different implementation of IPuppet that should work in place of any other IPuppet when used with the IMasterOfPuppets consumer. The IMasterOfPuppets implementation should never know that the implementation of IPuppet changed... and the thing consuming IMasterOfPuppets should be even further removed.
Second, both the example NamedPuppet and the new ConfigurablePuppet take a string parameter with the same name, but it means something different to the backing implementation. So if your consuming code is doing what you show in the example - passing in a parameter that's intended to be the name of the thing - then you probably have an interface design problem. See: Liskov substitution principle.
Point being, given that the IMasterOfPuppets implementation needs an IPuppet passed in, it shouldn't care how the IPuppet was constructed to begin with or what is actually backing the IPuppet. Once it knows, you're breaking the separation of interface and implementation, which means you may as well do away with the interface and just pass in NamedPuppet objects all the time.
As far as passing parameters, Autofac does have parameter support.
The recommended and most common type of parameter passing is during registration because at that time you can set things up at the container level and you're not using service location (which is generally considered an anti-pattern).
If you need to pass parameters during resolution Autofac also supports that. However, when passing during resolution, it's more service-locator-ish and not so great becausee, again, it implies the consumer knows about what it's consuming.
You can do some fancy things with lambda expression registrations if you want to wire up the parameter to come from a known source, like configuration.
builder.Register(c => {
var name = ConfigurationManager.AppSettings["name"];
return new NamedPuppet(name);
}).As<IPuppet>();
You can also do some fancy things using the Func<T> implicit relationship in the consumer:
public class MasterOfPuppets : IMasterOfPuppets
{
IPuppet _puppet;
public MasterOfPuppets(Func<string, IPuppet> puppetFactory)
{
_puppet = puppetFactory("name");
}
}
Doing that is the equivalent of using a TypedParameter of type string during the resolution. But, as you can see, that comes from the direct consumer of IPuppet and not something that trickles down through the stack of all resolutions.
Finally, you can also use Autofac modules to do some interesting cross-cutting things the way you see in the log4net integration module example. Using a technique like this allows you to insert a specific parameter globally through all resolutions, but it doesn't necessarily provide for the ability to pass the parameter at runtime - you'd have to put the source of the parameter inside the module.
Point being Autofac supports parameters but not what you're trying to do. I would strongly recommend redesigning the way you're doing things so you don't actually have the need to do what you're doing, or so that you can address it in one of the above noted ways.
Hopefully that should get you going in the right direction.

adapter pattern and dependency

I have little doubt about adapter class. I know what's the goal of adapter class. And when should be used. My doubt is about class construction. I've checked some tutorials and all of them say that I should pass "Adaptee" class as a dependency to my "Adapter".
e.g.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter(AdapteeClass instance)
{
mInstance=instance;
}
}
This example is copied from wikipedia. As you can see AdapteeClass is passed to my object as dependency. The question is why? If I'm changing interface of an object It's obvious I'm going to use "new" interface and I won't need "old" one. Why I need to create instance of "old" class outside my adapter. Someone may say that I should use dependency injection so I can pass whatever I want, but this is adapter - I need to change interface of concrete class. Personally I think code bellow is better.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter()
{
mInstance= new AdapteeClass();
}
}
What is your opinion?
I would say that you should always avoid the new operator in a class when it comes to complex objects (except when the class is a Builder or Factory) to reduce coupling and make your code better testable. Off course objects like a List or Dictionary or value objects can be constructed inside a class method (which is probably the purpose of the class method!)
Lets say for example that your AdapteeClass is a Remote Proxy. If you want to use Unit Testing, your unit tests will have to use the real proxy class because there is no way to replace it in your unit tests.
If you use the first approach, you can easily inject a mock or fake into the constructor when running your unit test so you can test all code paths.
Google has a guide on writing testable code which describes this in more detail but some important points are:
Warning Signs for not testable code
new keyword in a constructor or at field declaration
Static method calls in a constructor or at field declaration
Anything more than field assignment in constructors
Object not fully initialized after the constructor finishes (watch out for initialize methods)
Control flow (conditional or looping logic) in a constructor
Code does complex object graph construction inside a constructor rather than using a factory or builder
Adding or using an initialization block
AdapteeClass can have one or more non-trivial constructors. In this case you'll need to duplicate all of them in your SampleAdapter constructor to have the same flexibility. Passing already constructed object is simpler.
I think creating the Adaptee inside the Adapter is limiting. What if some day you want to adapt a pre-existing instance?
To be honest though, I'd do both if at all possible.
Class SampleAdapter implements MyInterface
{
private AdapteeClass mInstance;
public SampleAdapter()
: base (new AdapteeClass())
{
}
public SampleAdapter(AdapteeClass instance)
{
mInstance=instance;
}
}
Let's assume you have an external hard drive with a regular USB port and you are trying to hook it up with a Mac which only has type-c ports. Yes, you can buy a new drive which has a type-c port but what about the data in it?
It's the same for the adapter pattern. There're times you initialize AdapteeClass with tons of flavors. When you do the conversion, you want to keep all the context.

How to manage IoC containers in tests?

I'm very new to testing and IoC containers and have two projects:
MySite.Website (MVC)
MySite.WebsiteTest
Currently I have an IoC container in my website. Should I recreate another IoC container for my test? Or is there a way to use the IoC in both?
When you have an IoC container, hopefully you will also have some sort of dependency injection going on - whether through constructor or setter injection.
The point of a unit test is to test components in isolation and doing DI goes a long way in aiding that. What you want to do is unit test each class by manually constructing it and passing it the required dependencies, not rely on container to construct it.
The point of doing that is simple. You want to isolate the SUT(System Under Test) as much as possible. If your SUT relies on another class and IoC to inject it, you are really testing three systems, not one.
Take the following example:
public class ApiController : ControllerBase {
IRequestParser m_Parser;
public ApiController(IRequestParser parser) {
m_Parser = parser;
}
public ActionResult Posts(string request) {
var postId = m_Parser.GetPostId(request);
}
}
The ApiController constructor is a dependency constructor and will get invoked by IoC container at runtime. During test, however, you want to mock IRequestParser interface and construct the controller manually.
[Test]
public void PostsShouldCallGetPostId() {
//use nmock for mocking
var requestParser = m_Mocks.NewMock<IRequestParser>();
//Set up an expectation that Posts action calls GetPostId on IRequestParser
Expect.Once.On(requestParser).Method("GetPostId").With("posts/12").Will(Return.Value(0));
var controller = new ApiController(requestParser);
controller.Posts("posts/12");
}
Testing is about real implementation. So you normally should not use IOC in your unit tests. In case you really feel needing it (one component depending on another one), using an interface to isolate the interaction and using a mocking lib (Moq is good) to mock it and do the testing.
The only chance I see IOC container is necessary for testing is in integration testing.