using Powermock annotations via interface or annotation type - powermock

We are trying to use Powermock and for starters we feel that it is a very good unit test tool for static method testing.
We could not figure out how to use Powermock annotations in interface or annotation types.
When we use them in an abstract class and make our test class extend it works
#RunWith(PowerMockRunner.class)
#PrepareForTest({ Dummy.class })
#PowerMockIgnore({ "javax.management.*", "com.mycompany.excludepackage.*" })
public abstract class BaseTestClass {
}
However defining them in an interface as follows and make the test class implement that interface does not work :
#RunWith(PowerMockRunner.class)
#PrepareForTest({ Dummy.class })
#PowerMockIgnore({ "javax.management.*", "com.mycompany.excludepackage.*" })
public interface ITestClass {
}
Implementing a custom annotation as follows and annotate the test class with that annotation does not help either :
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.TYPE)
#Inherited
#RunWith(PowerMockRunner.class)
#PrepareForTest({ Dummy.class })
#PowerMockIgnore({ "javax.management.*", "com.mycompany.excludepackage.*" })
public #interface TestClassAnnotation {
}
For both cases we are having ClassNotPreparedException
[Ljava.lang.Object;#43bc63a3
The class xxx not prepared for test.
at org.powermock.api.mockito.expectation.reporter.MockitoPowerMockReporter.classNotPrepared(MockitoPowerMockReporter.java:29)
at org.powermock.api.mockito.internal.mockcreation.MockTypeValidatorFactory$DefaultMockTypeValidator.validate(MockTypeValidatorFactory.java:37)
at org.powermock.api.mockito.internal.mockcreation.AbstractMockCreator.validateType(AbstractMockCreator.java:10)
at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMock(DefaultMockCreator.java:49)
at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.mock(DefaultMockCreator.java:40)
at org.powermock.api.mockito.PowerMockito.mockStatic(PowerMockito.java:62)
So is there any way we can make use of the annotations other than extending a class? Extending a class will be too restrictive for us because we will need to ignore different packages for same test class.
We are searching a way to achieve this by composition not by inheritance.
Any other recommendation for applying multiple annotations by composition would also help
Thanks in advance

Related

Can I match class that implements annotated Interface with knowledge only about annotation type?

just like in the topic. I have my resource class :
public class HelloWorldEndpoint implements IRest {
public String sayHello()
{
return "Hello world!";
}
}
And Interface :
#Path("/helloworld")
public interface IRest {
#GET
#Path("/hello")
String sayHello();
}
Is it possible to match sayHello() from HelloWorldEndpoint using only #Path class annotation? This is very specific example of resource class implementation, but it shows that it is possible to have REST endpoint without any annotation in class.. I've tried with inheritsAnnotation() and isAnnotatedWith() but it's not working that way unfortunatly. My goal is to find all resource classes :)
Annotations of interfaces are not inherited in accordance to the Java Langauge specification. They are neither exposed by the reflection API, for example.
In order to discover the annotation, you can manually travers the class hierarchy and look for the annotation in question. This is possible by hasSuperType(isAnnotatedWith(...)). Note that this is a rather expensive matching condition.

How to two runner property include in one test case class?

#RunWith(DataProviderRunner.class)
#RunWith(SpringJUnit4ClassRunner.class)
public class DatabaseModelTest {
// some tests
}
or
#RunWith(Parameterized.class)
#RunWith(SpringJUnit4ClassRunner.class)
public class DatabaseModelTest {
// some tests
}
We can not use two runner property in one test case class...!! so that
I want to run test case with Multiple data how i pass multiple parameter in Rest web service to execute test case ??
Any solution for extend class for DataProviderRunner or parameterized ??
Thanks
(stayconnected52)
You could use Spring's JUnit rules instead of the SpringJUnit4ClassRunner. This works at least with the Parameterized runner. I don't know whether it works with the DataProviderRunner, too.
You need at least version 4.2.0 of the Spring framework and spring-test.
#RunWith(Parameterized.class)
public class DatabaseModelTest {
#ClassRule
public static final SpringClassRule SCR = new SpringClassRule();
#Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
...
}
I tested the solution of #Stefan and works also well for #RunWith(DataProviderRunner.class)
I found a second solution in DataProvider for Spring Integration Testing, they wrote a class DataProviderRunnerWithSpring and set the test class like:
#RunWith(DataProviderRunnerWithSpring.class)
public class TestClass{
...
}

Any alternative to injecting Castle Windsor typed factories?

Most of my components are registered using the code-based (fluent) approach, but there is one particular component that I need to resolve differently at runtime. This is the interface and a couple of concrete implementations:-
public interface ICommsService ...
public class SerialCommsService : ICommsService ...
public class TcpCommsService : ICommsService ...
Some of our users will need the serial service while others will need the TCP service. My current solution (which works btw) is to use a typed factory and a custom component selector - the latter reads an app.config setting to determine which implementation the typed factory will resolve and return.
First the typed factory (nothing special about this):-
public interface ICommsServiceFactory
{
ICommsService Create();
void Release(ICommsService component);
}
Next, the custom component selector, which reads the fully-qualified type name from app.config (e.g. "MyApp.SomeNamespace.TcpCommsService"):-
public class CommsFactoryComponentSelector : DefaultTypedFactoryComponentSelector
{
protected override string GetComponentName(MethodInfo method, object[] arguments)
{
return ConfigurationManager.AppSettings["commsServiceType"];
}
}
Then the registration stuff:-
var container = new WindsorContainer();
container.AddFacility<TypedFactoryFacility>();
container.Register(Component.For<ITypedFactoryComponentSelector>()
.ImplementedBy<CommsFactoryComponentSelector>());
container.Register(Component.For<ICommsFactory>()
.AsFactory(o => o.SelectedWith<CommsFactoryComponentSelector>()));
container.Register(Component.For<ICommsService>()
.ImplementedBy<SerialCommsService>().LifeStyle.Singleton);
container.Register(Component.For<ICommsService>()
.ImplementedBy<TcpCommsService>().LifeStyle.Singleton);
Finally, an example class with a dependency on ICommsService:-
public class Test
{
public Test(ICommsFactory commsFactory)
{
var commsService = commsFactory.Create();
...
}
}
As already mentioned, the above solution does work, but I don't like having to inject the factory. It would be more intuitive if I could just inject an ICommsService, and let something somewhere figure out which implementation to resolve and inject - similar to what I'm doing now but earlier in Windsor's "resolving pipeline". Is something like that possible?
You can use UsingFactoryMethod here:
container.Register(Component.For<ICommsService>().UsingFactoryMethod(kernel => kernel.Resolve<ICommsServiceFactory>().Create()));
You can inject ICommsService to any class now. ICommsServiceFactory can be a simple interface now:
interface ICommsServiceFactory
{
ICommsService Create();
}

Junit: How to stubs the following java class in junit

Hi I have a class which the invoke the run() method of a thread from the constructor of the class by calling the start() method , So please help me to Stubs the so to write the junit test cases . The class is as follows
public class MyClass extends Thread {
Student st=null;
University uni= new University();
public MyClass(Student st) {
this.st=st;
start();
}
public void run() {
uni.calculate(st);
}
}
Thanks
Take a look at the discussion here:
Testing Constructor With Powermock
It discusses sub-classing and overriding.
In general it should be considered bad practice to have to mock the class under test in order to test it. It is also hard to do since most mocking frameworks will not allow mocking a single method once in the class under test since they create wrapping proxies.

Registering the same classes with two services - in two steps - in Castle Windsor

I have some executor-classes that implements one or two interfaces (IHandleMessages<> and/or CommandExecutor<>).
Can I register all these executor classes - with whichever interface(s) it implements of the two - as services. Without ending up having all other interfaces on the class as services too.
My initial attempt was this:
public class Test
{
[Fact]
public void SomeTest()
{
var container = new WindsorContainer();
container.Register(Classes.FromThisAssembly().BasedOn(typeof(CommandExecutor<>)).WithService.Base().LifestyleTransient(),
Classes.FromThisAssembly().BasedOn(typeof(IHandleMessages<>)).WithService.Base().LifestyleTransient());
container.ResolveAll<CommandExecutor<object>>().Count().ShouldBe(2);
container.ResolveAll<IHandleMessages<object>>().Count().ShouldBe(2);
}
public interface IHandleMessages<T> { }
public interface CommandExecutor<T> { }
public class HandlesMessagesOnly : IHandleMessages<object> { }
public class HandlesMessagesAndExecutesCommands : CommandExecutor<object>, IHandleMessages<object> { }
public class ExecutesCommandsOnly : CommandExecutor<object> { }
}
But that does not work. Is there a solution for this?
I'm using Windsor 3.1.0.
EDIT: I guess what I'm really asking is: Is it possible to find the same type twice, and just have the discoverer add more services to that type's registration?
This will make your test pass:
container.Register(
Classes
.FromThisAssembly()
.BasedOn(typeof(CommandExecutor<>))
.WithServiceBase()
.WithServiceFirstInterface() // Ensures first interface is included.
.LifestyleTransient(),
Classes
.FromThisAssembly()
.BasedOn(typeof(IHandleMessages<>))
.WithServiceBase()
.LifestyleTransient()
);
For more sophisticated interface selection techniques see this question.
I've made a pull request to Windsor which was accepted in 3.2, and you can now do this:
Container.Register(
Classes.FromThisAssembly()
.BasedOn<IFoo>()
.OrBasedOn(typeof(IBar))
.WithServiceBase()
.LifestyleTransient());
Read more here