Is there a way to have the #MethodSource arguments parameters derived from another method - junit5

I have a Junit 5 non static parameterized test where I am using #MethodSource to get the test data.
The Method Source arguments are getting the data from other methods as below code. I made the #MethodSource non static by having a
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
The fullDomain parameter in the #MethodSource is derived from the method getFullDomain() in the registrationPage which is also non static . I #Autowired the RegistrationPage in the BaseTest and using it by extending in my Junit5SampleTest Class
When I run the test the fullDomain is returning null. Is there a way to fix this or can I use any others like #ArgumentSource to fix this.
I will need to get the Arguments.of("Successful Regisration", fullDomain) data from different classes and its methods.
Base Test:
public class BaseTest {
#Autowired
protected RegistrationPage registrationPage;
}
Test Class:
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class Junit5SampleTest extends BaseTest {
String fullDomain = registrationPage.getFullDomain();
Stream<Arguments> registrationInputParameters() {
return Stream.of(
Arguments.of("Successful Regisration", fullDomain)
}
#ParameterizedTest()
#MethodSource("registrationInputParameters")
public void junit5(String testName, String fullDomain){
System.out.println(testName);
open(fullDomain);
}
}

Related

How to access the public variable in plugin1 from plugin2 using OSGI framework

I'm new to OSGI framework and I'm trying to access the 'Derived' Class variable 'publicVariable' from another class 'Derived2' like "Derived.publicVariable" but publicVariable is always shows null. I really appreciate if someone can help me out with this.
Thanks
Manifest file - Derived2
Require-Bundle:com.xxxxxx.Derived1
Java code
abstract class Base {
protected Vector <String> supportedCommands = new Vector <String> ();
protected abstract void initialiseCommands();
}
class Derived extends Base {
private static Derived derivedPlugin = null;
public Derived()
{
derivedPlugin = this;
}
public static Derived getPlugin()
{
return derivedPlugin;
}
public String publicVariable = null;
protected void initialiseCommands()
{
publicVariable = "someData";
System.out.println("Derived" + publicVariable);
}
}
class Derived2 extends Base {
protected void initialiseCommands()
{
supportedCommands.add(Derived.getPlugin().publicVariable);
System.out.println("IMRSAUtilitiesPlugin" +supportedCommands);
}
Also referred below link, which is a similar issue but i'm not using any static variable, it is just a public variable.
how use Singleton object in different class loader....?
The code in the question will not compile. You are trying to access an instance field (publicVariable in class Derived) in a static way, i.e. Derived.publicVariable.
OSGi does not change the semantics of the Java language, and if you cannot even compile your code then OSGi will certainly not be able to run it.

Using InjectMock on Object with private static final fields failing

I am writing test cases for a legacy code which for some reason we dont want to change.
The code is something like this
public class ToBeTested{
private static final String field1=SomeUtil.getProperty("somekey");
#AutoWired
Someservice service;
}
In my Junit I am using powermock with mockito and did something like this
public class myTestClass{
#Mock
SomeService service;
#InjectMock
ToBeTested tested;
}
However, InjectMocks fails to create the object for ToBeTested since the final fields are not provided
So I implemented a #BeforeClass and mocked the static method of SomeUtil. This works if i have only one test case. But for more than one test case, only one passes and others are failing with same error that
cannot instantiate #injectmocks field named you haven't provided the instance at field declaration
I have been able to resolve this by using something as below:
public class myTestClass{
#Mock
SomeService service;
ToBeTested tested;
#Before
public void setup(){
MockitoAnnotations.initMocks(this);
mockStatic(SomeUtil.class);
when(SomeUtil.getProperty(anyString())).thenReturn("test");
toBeTested=new ToBeTested(); Whitebox.setInternalState(toBeTested,"someService",someService);
}
}
However am not a fan of using reflection in Junit which WhiteBox does internally.
Is there a better way to do this?
Edit: Adding the snippet of code as suggested by Rann in comment
#RunWith(PowerMockRunner.class)
#PrepareForTest(SomeUtil.class)
public class myTestClass{
#Mock
SomeService service;
#InjectMock
ToBeTested tested;
#BeforeClass
public static void doBeforeClass(){
mockStatic(SomeUtil.class);
when(SomeUtil.getProperty(anyString())).thenReturn("test");
}
#Test
public void test1(){
tested.doSomethingFor1();
}
#Test
public void test2(){
tested.doSomethingFor2();
}
}
test1 passes fine. for test2 i get an exception as
Caused by: org.mockito.exceptions.base.MockitoException:
Cannot instantiate #InjectMocks field named 'tested' of type 'class com.xyz.ToBeTested'.
You haven't provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : null
at org.powermock.api.extension.listener.AnnotationEnabler.injectSpiesAndInjectToSetters(AnnotationEnabler.java:72)
at org.powermock.api.extension.listener.AnnotationEnabler.beforeTestMethod(AnnotationEnabler.java:64)
at org.powermock.tests.utils.impl.PowerMockTestNotifierImpl.notifyBeforeTestMethod(PowerMockTestNotifierImpl.java:82)
... 23 more
Caused by: java.lang.NullPointerException
at com.xyz.SomeUtil.getProperty(SomeUtil.java:42)

variable not taking in consideration with velocity

I want to generate java class.
I create a template with velocity
#Repository
public class $className extends BaseRepository<$bean, $searchDto> {
#PersistenceContext
private EntityManager em;
#Autowired
public $className(EntityManager em) {
super($bean.class, em);
}
}
If I pass this value
className=UsersRepositoryImpl
bean=Users
searchDto=UsersSearch
I get
#Repository
public class UsersRepositoryImpl extends BaseRepository<Users, UsersSearch> {
#PersistenceContext
private EntityManager em;
#Autowired
public UsersRepositoryImpl(EntityManager em) {
super(class java.lang.String, em);
}
}
seem like a issue with $bean.class
tried "$bean.class" but get same issue
Edit
put {} around work
${bean}
You need to call
${bean}.class
which tells the velocity processor that ${bean} is the velocity variable and .class is just static text of the template. Othherwise he will interpret $bean.class as one expression, your $bean is a String and $bean.class is therefore printed using the toString method of the String's Class object.

Replace #Value property within #Configuration during Spring Boot test

Scenario
I've got a Spring Boot application with a #Configuration annotated Spring configuration class which contains some #Value annotated fields. For testing I want to replace these field values with custom test values.
Unfortunately these test values cannot be overridden using a simple properties file, (String) constants or similar, instead I must use some custom written property resolving Java class (e.g. TargetProperties.getProperty("some.username")).
The problem I have is that when I add a custom PropertySource to the ConfigurableEnvironment within my test configuration, it's already too late because this PropertySource will be added after the e.g. RestTemplate has been created.
Question
How can I override #Value annotated fields within a #Configuration class with properties obtained programmatically via custom Java code before anything else gets initialized?
Code
Production Configuration Class
#Configuration
public class SomeConfiguration {
#Value("${some.username}")
private String someUsername;
#Value("${some.password}")
private String somePassword;
#Bean
public RestTemplate someRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getInterceptors().add(
new BasicAuthorizationInterceptor(someUsername, somePassword));
return restTemplate;
}
}
Test Configuration Class
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class SomeTest {
#SpringBootConfiguration
#Import({MySpringBootApp.class, SomeConfiguration.class})
static class TestConfiguration {
#Autowired
private ConfigurableEnvironment configurableEnvironment;
// This doesn't work:
#Bean
#Lazy(false)
// I also tried a #PostConstruct method
public TargetPropertiesPropertySource targetPropertiesPropertySource() {
TargetPropertiesPropertySource customPropertySource =
new TargetPropertiesPropertySource();
configurableEnvironment.getPropertySources().addFirst(customPropertySource);
return customPropertySource;
}
}
}
You can override properties directly in the #SpringBootTest annotation using the properties parameter:
#SpringBootTest(properties = {"some.username=user", "some.password=pwd"},
webEnvironment = SpringBootTest.WebEnvironment.NONE)
You can use #TestPropertySource
#TestPropertySource(
properties = {
"some.username=validate",
"some.password=false"
}
)
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ApplicationTest {
//...
}
You can use constructor injection in production cases, which allows it to set the configuration manually:
#Configuration
public class SomeConfiguration {
private final String someUsername;
private final String somePassword;
#Autowired
public SomeConfiguration(#Value("${some.username}") String someUsername,
#Value("${some.password}") String somePassword) {
this.someUsername = someUsername;
this.somePassword = somePassword;
}
...
)
}
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class SomeTest {
private SomeConfiguration config;
#Before
public init() {
config = new SomeConfiguration("foo", "bar");
}
}

design pattern query

i have a question regarding design patterns.
suppose i want to design pig killing factory
so the ways will be
1) catch pig
2)clean pig
3) kill pig
now since these pigs are supplied to me by a truck driver
now if want to design an application how should i proceed
what i have done is
public class killer{
private Pig pig ;
public void catchPig(){ //do something };
public void cleanPig(){ };
public void killPig(){};
}
now iam thing since i know that the steps will be called in catchPig--->cleanPig---->KillPig manner so i should have an abstract class containing these methods and an execute method calling all these 3 methods.
but i can not have instance of abstract class so i am confused how to implement this.
remenber i have to execute this process for all the pigs that comes in truck.
so my question is what design should i select and which design pattern is best to solve such problems .
I would suggest a different approach than what was suggested here before.
I would do something like this:
public abstract class Killer {
protected Pig pig;
protected abstract void catchPig();
protected abstract void cleanPig();
protected abstract void killPig();
public void executeKillPig {
catchPig();
cleanPig();
killPig();
}
}
Each kill will extend Killer class and will have to implement the abstract methods. The executeKillPig() is the same for every sub-class and will always be performed in the order you wanted catch->clean->kill. The abstract methods are protected because they're the inner implementation of the public executeKillPig.
This extends Avi's answer and addresses the comments.
The points of the code:
abstract base class to emphasize IS A relationships
Template pattern to ensure the steps are in the right order
Strategy Pattern - an abstract class is as much a interface (little "i") as much as a Interface (capital "I") is.
Extend the base and not use an interface.
No coupling of concrete classes. Coupling is not an issue of abstract vs interface but rather good design.
public abstract Animal {
public abstract bool Escape(){}
public abstract string SaySomething(){}
}
public Wabbit : Animal {
public override bool Escape() {//wabbit hopping frantically }
public override string SaySomething() { return #"What's Up Doc?"; }
}
public abstract class Killer {
protected Animal food;
protected abstract void Catch(){}
protected abstract void Kill(){}
protected abstract void Clean(){}
protected abstract string Lure(){}
// this method defines the process: the methods and the order of
// those calls. Exactly how to do each individual step is left up to sub classes.
// Even if you define a "PigKiller" interface we need this method
// ** in the base class ** to make sure all Killer's do it right.
// This method is the template (pattern) for subclasses.
protected void FeedTheFamily(Animal somethingTasty) {
food = somethingTasty;
Catch();
Kill();
Clean();
}
}
public class WabbitHunter : Killer {
protected override Catch() { //wabbit catching technique }
protected override Kill() { //wabbit killing technique }
protected override Clean() { //wabbit cleaning technique }
protected override Lure() { return "Come here you wascuhwy wabbit!"; }
}
// client code ********************
public class AHuntingWeWillGo {
Killer hunter;
Animal prey;
public AHuntingWeWillGo (Killer aHunter, Animal aAnimal) {
hunter = aHunter;
prey = aAnimal;
}
public void Hunt() {
if ( !prey.Escape() ) hunter.FeedTheFamily(prey)
}
}
public static void main () {
// look, ma! no coupling. Because we pass in our objects vice
// new them up inside the using classes
Killer ElmerFudd = new WabbitHunter();
Animal BugsBunny = new Wabbit();
AHuntingWeWillGo safari = new AHuntingWeWillGo( ElmerFudd, BugsBunny );
safari.Hunt();
}
The problem you are facing refer to part of OOP called polymorphism
Instead of abstract class i will be using a interface, the difference between interface an abstract class is that interface have only method descriptors, a abstract class can have also method with implementation.
public interface InterfaceOfPigKiller {
void catchPig();
void cleanPig();
void killPig();
}
In the abstract class we implement two of three available methods, because we assume that those operation are common for every future type that will inherit form our class.
public abstract class AbstractPigKiller implements InterfaceOfPigKiller{
private Ping pig;
public void catchPig() {
//the logic of catching pigs.
}
public void cleanPig() {
// the logic of pig cleaning.
}
}
Now we will create two new classes:
AnimalKiller - The person responsible for pig death.
AnimalSaver - The person responsible for pig release.
public class AnimalKiller extends AbstractPigKiller {
public void killPig() {
// The killing operation
}
}
public class AnimalSaver extends AbstractPigKiller {
public void killPing() {
// The operation that will make pig free
}
}
As we have our structure lets see how it will work.
First the method that will execute the sequence:
public void doTheRequiredOperation(InterfaceOfPigKiller killer) {
killer.catchPig();
killer.cleanPig();
killer.killPig();
}
As we see in the parameter we do not use class AnimalKiller or AnimalSever. Instead of that we have the interface. Thank to this operation we can operate on any class that implement used interface.
Example 1:
public void test() {
AnimalKiller aKiller = new AnimalKiller();// We create new instance of class AnimalKiller and assign to variable aKiller with is type of `AnimalKilleraKiller `
AnimalSaver aSaver = new AnimalSaver(); //
doTheRequiredOperation(aKiller);
doTheRequiredOperation(aSaver);
}
Example 2:
public void test() {
InterfaceOfPigKiller aKiller = new AnimalKiller();// We create new instance of class AnimalKiller and assign to variable aKiller with is type of `InterfaceOfPigKiller `
InterfaceOfPigKiller aSaver = new AnimalSaver(); //
doTheRequiredOperation(aKiller);
doTheRequiredOperation(aSaver);
}
The code example 1 and 2 are equally in scope of method doTheRequiredOperation. The difference is that in we assign once type to type and in the second we assign type to interface.
Conclusion
We can not create new object of abstract class or interface but we can assign object to interface or class type.