I am writing junit test to test BaseClass method. The method uses super class members.
The BaseClass constructor invokes super(arg1, arg2).
In the super(arg1, arg2) constructor there is a dependency injector setting a private member
of the super class.
When I am running the test, since the dependency is not set, the super() is throwing an
exception. I want to mock only that statement in the super() which is setting the private member with dependency injection. How to do with mockito ?
Field injection is always a problem for testing. So whenever you have the choice, choose constructor injection instead.
You could start the dependency injector and make it inject a mock instead of a real class. Solutions would depend on the DI framework that you use actually (guice, cdi, ...) For guice you could use jukito, for cdi Arquillian for example. But it slows down the test execution and adds complexity to your test class.
As a alternative you could reflect the private field on an instance of you test class an simply set a mock. Something like:
instance = new TestObject();
Field injected = TestObject.class.getDeclaredField("injected");
injected.setAccessible(true);
injected.set(instance, mock(InjectedType.class));
while TestObject is the class that you want to test, injected the private field where something is injected an InjectedType the type of that private field.
Related
I am new to nodejs and typescript, coming from C#.
I want to use dependency injection in my project and found that the most popular package is inversify.
I started using it but I don't like the fact that I have to add decorators all over.
for example it bothers me that I need to add #inject before parameters in the constructor:
public constructor(
#inject(TYPES.Weapon) katana: Weapon,
#inject(TYPES.ThrowableWeapon) shuriken: ThrowableWeapon
)
This mean every class has to know the TYPES object...
I don't understand why #inject needs the string literal and can't inject just on the basis of the type...
Is there a neater way to do this?
In contrast to strictly typed languages, TypeScript types don't exist at runtime. It's possible to use type information at runtime for dependency injection but in limited ways. With the use of emitDecoratorMetadata TypeScript option it's possible to get constructor parameter types and use them for DI.
The example is injection-js, which is Angular injector that was extracted from the library for standalone use. Only #Injectable decorator is needed to be used on DI-enabled class, #Inject parameter decorators are optional.
The limitations are that only class instances can be injected this way:
constructor(foo: FooClass) {}
Generics are ignored and discarded:
constructor(foo: FooClass<Bar>) {}
Other types are ignored and result in DI error:
constructor(foo: fooSymbol) {}
constructor(foo: 'foo string provider') {}
The same applies to InversifyJS:
In case of concrete injections, you can simply define your constructor
parameters as usual without using the #inject decorator.
InversifyJS also supports TypeScript's constructor assignments so you
can have private or protected access modifiers in your parameters and
the container will have no trouble injecting the dependencies
It would be possible to omit #inject for Weapon and ThrowableWeapon if they were classes but in listed example TYPES.Weapon is a symbol and Weapon is an interface that doesn't exist at runtime, so #inject is necessary.
Is there any reason why everybody uses #Before instead of #BeforeClass with initMocks? In my case I have only one method call in setup method and that is MockitoAnnotations.initMocks. #BeforeClass is even faster.
#BeforeClass, as the name suggest is run after class is loaded and no object exist. So all variable which you initialize need to be static. So, if you want to reuse this static variable in all testcases, as base setup input data, then you can do ahead with using #BeforeClass.
#Before is useful, then you want to reset the data before each test case gets called, so you are sure, anyone changing the input base data, does not impact the with what the next test is called.
coming to initmock, you can do via #Mock, #InjectMocks and using #RunWith(MockitoJUnitRunner.class)
#RunWith(MockitoJUnitRunner.class)
public class SampleTest {
#InjectMocks
private ClassA classA;
#Mock
private ClassB classB
// #BeforeClass and other test methods
}
In above code,
1. Instance of ClassA will be created
2. Mock object of ClassB will be created
3. classB will be injected in ClassA object created in step 1
I'm new to groovy...
I've made a class. Within this class, I'd like to call an external method : LOG.error, but somehow, groovy is complaining about the method not being part of the class... how should I call that external method ?
class GAPI{
private myvar
public getResult(){
this.myvar="blabla"
LOG.error("test")
}
}
Groovy provides #Slf4j annotation that can add log field to your class, e.g.
#Slf4j
class GAPI{
private myvar
public getResult(){
this.myvar="blabla"
log.error("test")
}
}
Alternatively you can use #Log annotation that adds log field that uses java.util.logging.Logger instead of one provided with Slf4j. However in this case you have to be aware that java.util.logging.Logger uses different API, so there is no log.error() method.
In your example Groovy throws MissingPropertyException, because LOG is not defined in your class. If there is a class LOG with static method error you will have to import this class. But most probably you should just create LOG field (with annotation or manually) and call it to be most explicit (otherwise your code gets unreadable).
#RunWith(CucumberWithSerenity.class)
#CucumberOptions(<configuration>)
public Class TestRunner{}
public Class StepDefinitions{}
public Class SomeClass{}
Is there a way to pass object of type SomeClass from TestRunner to StepDefintions? The reason behind this requirement is to have a single object of someClass object for all scenarios.
The way to share information between steps in different step classes in Cucumber-JVM is to use dependency injection.
Cucumber has bindings to many different dependency injection frameworks. One of them is PicoContainer. I wrote a blog post a while back describing how it can be used.
I am using groovy to create some mock classes for a test case. I am basically creating dummy objects where all the methods return null so that i can run my testcase.
I am using the following syntax:
MessageFactory.instance = ["getMessage": {a,b,c,d -> "dummy"}] as MessageFactory
So here i am trying to overwrite the singleton instance with my on fake factory object. The problem is that MessageFactory's constructor happens to be a private method. This gives me an illigal access exception when i run the code above. Is there a away i can create a proxy in groovy and overcome the private constructor issue?
If you have access to the MessageFactory, and are willing to modify it, then you use the standard dependency-injection solution, as detailed here: mock singleton
..Though it's not particularly Groovy.
Otherwise, the best workaround I've found is to override the method(s) on the singleton instance itself, like so:
#Singleton
class Test{
def method(){"Unmocked method called"}
}
def test = Test.instance
test.metaClass.method = {-> null}
test.method() // Now returns null
Naturally, as a singleton, this instance doesn't change (at least in theory)... So, overriding methods in this manner is effectively global.
Edit: Or you can use GMock, which supports constructor mocking (among other things).