#target pointcut throws IllegalStateException - aop

In Spring boot AOP application I have a pointcut #target(MyAnnotation) || #annotation(MyAnnotation).
Advice should be executed if MyAnnotation is put either on executing object annotated with this annotation or on annotated method.
When I run application I get
java.lang.IllegalArgumentException: Cannot subclass final class org.springframework.cloud.sleuth.log.Slf4jScopeDecorator
A similar problem is discussed here but there it seems that pointcut is too wide and mine is not as I have only few annotated classes with MyAnnotation in the project.
I put this annotation to feign client interface, like this.
#MyAnnotation
#FeignClient(name="some-name", url="http://test.url")
public interface MyClient {
#RequestMapping(method = RequestMethod.GET, value = "/endpoint")
List<Store> getSomething();
}
Any ideas what's wrong with my pointcut?

Ok, after hours of investigation I replaced my pointcut with this one
#Around("execution(* (#MyAnnotation *).*(..)) || execution(#MyAnnotation * *(..))")
As explained here I used only execution to avoid proxy creation. Hope this helps

Related

How do you mock a singleton dependency in JMockit?

I'm working on some automated unit and integration tests for a robot. As you could imagine, a robot has a lot of sensor objects and such that would need mocking during testing.
One of the dependencies is a singleton designed not to be instantiated by anything but itself. As I understood it (I'm new to JMockit), once a class is annotated with #Mocked all of its methods and constructors are mocked. JMockit Documentation:
There are three different mocking annotations we can use when declaring mock fields and parameters: #Mocked, which will mock all methods and constructors on all existing and future instances of a mocked class
However I'm noticing (via the usage of a breakpoint) that the real class' constructor is being called and failing to access a sensor, causing the tests to fail.
Here is the relevant part of the singleton I'm trying to mock. Note that I cannot modify this class:
public class DriverStation() {
// This line in particular is an issue.
private static DriverStation currentInstance = new DriverStation();
public static DriverStation getInstance() {
return DriverStation.instance;
}
private DriverStation() {
// This constructor cannot be called during tests.
}
}
And here is my test code:
public class BlingControllerTest {
#Mocked
private DriverStation station;
#Tested
private BlingController blingController;
/**
* Tests getting the robot's operation period while not in a real match.
*/
#Test
public void testGetOperationPeriodDuringRealMatch(#Mocked DriverStation station) {
new Expectations(DriverStation.class) {{
DriverStation.getInstance();
result = station;
station.isFMSAttached();
result = true;
station.isAutonomous();
returns(true, false);
}};
}
}
Full source also available on GitHub
I should also mention that for some reason calling the singleton's constructor locally during tests isn't a problem, but when the tests are run on travis-ci it is a problem.
Stacktrace from running on travis-ci:
ca.team2706.frc.robot.commands.bling.BlingControllerTest > testGetOperationPeriodDuringRealMatch STANDARD_ERROR
java.io.IOException: wpiHaljni could not be loaded from path or an embedded resource.
attempted to load for platform /linux/x86-64/
at edu.wpi.first.wpiutil.RuntimeLoader.loadLibrary(RuntimeLoader.java:79)
at edu.wpi.first.hal.JNIWrapper.<clinit>(JNIWrapper.java:25)
at edu.wpi.first.wpilibj.DriverStation.<init>(DriverStation.java:194)
at edu.wpi.first.wpilibj.DriverStation.<clinit>(DriverStation.java:132)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:398)
at mockit.internal.state.TestRun.ensureThatClassIsInitialized(TestRun.java:138)
at mockit.internal.expectations.mocking.BaseTypeRedefinition.redefineType(BaseTypeRedefinition.java:65)
at mockit.internal.expectations.mocking.TypeRedefinition.redefineType(TypeRedefinition.java:28)
at mockit.internal.expectations.mocking.FieldTypeRedefinitions.redefineFieldType(FieldTypeRedefinitions.java:78)
at mockit.internal.expectations.mocking.FieldTypeRedefinitions.redefineFieldType(FieldTypeRedefinitions.java:65)
at mockit.internal.expectations.mocking.FieldTypeRedefinitions.redefineFieldTypes(FieldTypeRedefinitions.java:53)
at mockit.internal.expectations.mocking.FieldTypeRedefinitions.<init>(FieldTypeRedefinitions.java:33)
at mockit.integration.TestRunnerDecorator.handleMockFieldsForWholeTestClass(TestRunnerDecorator.java:142)
at mockit.integration.TestRunnerDecorator.updateTestClassState(TestRunnerDecorator.java:40)
Any and all help is appreciated.

When should we use #InjectMocks?

I have read through a lot of discussion about #Mock & #InjectMocks and still could not find what are the suitable or necessary cases to use #InjectMocks. In fact, I am not sure about what would happen when we use #InjectMocks.
Consider the following example,
public class User {
private String user_name;
private int user_id;
public User(int user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
}
public interface UserDao {
public List<User> getUserList();
}
public class UserService {
private UserDao userDao;
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public List<User> getUserList() {
return userDao.getUserList();
}
}
This is my test class
#RunWith(MockitoJUnitRunner.class)
public class UserServiceTest {
private UserService service = new UserService();
#Mock
private UserDao dao;
#Test
public void testGetUserList() {
service.setUserDao(dao);
// mock the return value of the mock object
List<User> mockResult = Arrays.asList(new User(101),new User(102),new User(103));
when(dao.getUserList()).thenReturn(mockResult);
// check return value is same as mocked value
assertEquals(service.getUserList(),mockResult);
// verify the getUserList() function is called
verify(dao).getUserList();
}
}
The test run successfully with no errors.
Consider another approach using #InjectMock annotation.
#RunWith(MockitoJUnitRunner.class)
public class UserServiceTest {
#InjectMocks
private UserService service;
#Mock
private UserDao dao;
#Test
public void testGetUserList() {
service.setUserDao(dao);
// mock the return value of the mock object
List<User> mockResult = Arrays.asList(new User(101),new User(102),new User(103));
when(dao.getUserList()).thenReturn(mockResult);
// check return value is same as mocked value
assertEquals(service.getUserList(),mockResult);
// verify the getUserList() function is called
verify(dao).getUserList();
}
}
This works equally well. So, which way is better? Any best practice?
Btw, I am using Junit 4.8.1 and Mockito 1.9.5
Your actual question can't be answered without you providing further code (the code you are showing does not explain the results you claim to observe).
Regarding the underlying question: you probably should not use #InjectMocks; one of its core problems is: if injecting fails, Mockito does not report an error to you.
In other words: you have passing unit tests, and some internal detail about a field changes ... and your unit tests break; but you have no idea why ... because the mocking framework doesn't tell you that the "initial" step of pushing a mock into the class under test is all of a sudden failing. See here for further reading.
But to be clear here: in the end, this almost a pure style question. People used to #InjectMocks will love it; other people do object it. Meaning: there is no clear evidence whether you should use this concept. Instead: you study the concept, you understand the concept, and then you (and the team working with you) make a conscious decision whether you want to use this annotation, or not.
Edit: I think I get your problem now. The idea of #InjectMocks is to inject a mocked object into some object under test.
But: you are doing that manually in both cases:
service.setUserDao(dao);
Meaning: if injecting works correctly (and there isn't a problem that isn't reported by Mockito) then your example that uses that annotation should also work when you remove that one line. Whereas the testcase that doesn't have #InjectMocks should fail without that line!
In other words: your testcases are both passing because your code does a "manual inject"!
When should we use #InjectMocks?
IHMO : we should not use it.
That favors so many design issues that I would like to add my POV on the question.
Here is relevant information from the javadoc (emphasis is not mine) :
Mark a field on which injection should be performed.
Allows shorthand mock and spy injection.
Minimizes repetitive mock and spy injection.
Mockito will try to inject mocks only either by constructor injection,
setter injection, or property injection in order and as described
below. If any of the following strategy fail, then Mockito won't
report failure; i.e. you will have to provide dependencies yourself.
...
Mockito is not an dependency injection framework,
In two words :
Advantage : you write less code to setup your mock dependencies.
Drawback : no failure if some mocks were not be set in the object under test.
IHMO the advantage hides also another drawback still more serious.
About the advantage :
Mockito uses constructor/setter/reflection to set the mocks in the object under test. The problem is that it is up to you to decide the way to set your fields : mockito will try one after the other way.
The setter way is often very verbose and provides mutability of the dependencies. So developers don't use it frequently. It makes sense.
The constructor way to set the bean dependencies requires to keep a good design with a decent number of dependencies : not more than 4 or 5 in general.
It demands strong design exigencies.
At last, the reflection way is the most easy : few code to write and no mutability of the dependencies.
The reflection way being the simplest from the lambda developer PVO, I saw many teams not aware of the consequences of reflection to specify dependencies and abuse of the reflection way in their Mockito tests but also in their design since finally InjectMocks allows to cope with it in a someway.
You may consider it fine to not finish with a class that declares 30 setters as dependencies or a constructor with 30 arguments but that has also a strong drawback : it favors bad smells such as dependency field hiding and declaration of many dependencies in as field instances of the class. As a result your class is complex, bloat, hard to read, hard to test and error prone to maintain.
The real thing is that in the very most of cases, the right solution is the constructor injection that promotes decent class responsibility and so good maintainability and testability of that.
About the drawback :
Mock injection doesn't work as the dependency injection of IOCs.
The javadoc states itself :
Mockito is not an dependency injection framework,
IOC and DI framework are able and by default consider dependencies as required. So any missing dependency will provoke a fast-fail error at the startup.
It prevents so many headaches and makes you win a precious time.
While Mockito injection will silently ignore the mocks that were not managed to be injected. It is so up to you to guess the error cause.
Finding the issue cause is sometimes complex because you don't have any clue from Mockito and that all is done by reflection by Mockito.
Using #InjectMocks injects the mocked objects as dependencies to the created object(The object marked by #InjectMocks). Creating an object using constructor will defy the purpose since the mocked objects are not injected and hence all the external calls from SUT takes place on concrete objects.Try to avoid creating SUT object by constructor call.

Benefits of an abstract class with a factory constructor?

I've recently run into some examples that make use of abstract classes as interfaces but also add factory constructors to the abstract interface so it can in a sense be "newed" up. For example:
abstract class WidgetService {
factory WidgetService() = ConcreteWidgetService;
Widget getWidget();
void saveWidget(Widget widget);
}
class ConcreteWidgetService extends BaseWidgetService implements WidgetService {
WidgetService();
Widget getWidget() {
// code to get widget here
}
void saveWidget(Widget widget) {
// code to save widget here
}
}
Usages of this service would be in some other service or component like so:
WidgetService _service = new WidgetService();
Based on my understanding of this sample, the line above would essentially "new" up a WidgetService, which usually produces an warning from the Dart analyzer, and said service variable would actually be an instance of ConcreateWidgetService based on the assignment of the ConcreateWidgetService to the factory constructor of the WidgetService.
Is there a benefit to this approach? From my OOP experience, I've used abstract classes/interfaces to program against when I didn't know the concrete type I would be given. Here it seems we are assigning the concrete type immediately to the abstract factory constructor. I guess my second question would be in this instance why not just use the ConcreteWidgetService directly here instead of repeating all the method signatures?
In your example the benefits are limited but in more complex situations the benefits become more clear.
A factory constructor allows you more control about what the constructor returns. It can return an instance of a subclass or an already existing (cached) instance.
It can return different concrete implementations based on a constructor parameter:
abstract class WidgetService {
WidgetService _cached;
factory WidgetService(String type) {
switch (type) {
case 'a':
return ConcreteWidgetServiceA();
case 'b':
return ConcreteWidgetServiceB();
default:
return _cached ??= DummyWidgetServiceA();
}
}
Widget getWidget();
void saveWidget(Widget widget);
}
Your example seems to be a preparation to be extended eventually to such a more flexible approach.
In Dart, all classes are also automatically interfaces. There's nothing strange about creating a instance of - 'newing up' - an 'interface', because it's actually just creating an instance of a class.
The purpose of some abstract classes is specifically to define an interface, but they have factory constructors that return a 'default implementation' of themselves.
For instance:
void main() {
var v = new Map();
print(v.runtimeType);
}
prints: _InternalLinkedHashMap - the (current) default implementation of Map.
Core library users can create and using instances of Map without knowing or caring about the implementation they actually get. The library authors may change the implementation without breaking anyone's code.
Of course, other classes may implement Map also.
With respect to your code sample, WidgetService _service = new WidgetService(); does not produce an analyzer warning. See this example on DartPad (Note I fixed a couple of errors in your sample).
I was initially confused by:
factory WidgetService() = ConcreteWidgetService;
instead of:
factory WidgetService() => new ConcreteWidgetService();
but it seems to work.

Controlling lifetime of objects created by factory generated by ToFactory()

I am using the following Ninject related nuget packages in an MVC 5 WebAPI application:
Ninject.MVC5
Ninject.Extensions.Factory
ninject.extensions.conventions
I have a simple repository and a corresponding factory class like so:
public interface ITaskRunner
{
void Run();
}
public interface IRepository<T> where T: class
{
T[] GetAll();
}
public interface IRepositoryFactory<T> where T: class
{
IRepository<T> CreateRepository();
}
I have setup the Ninject bindings using ToFactory() from Ninject.Extensions.Factory like so:
kernel.Bind<ITaskRunner>().To<TaskRunner>().InSingletonScope();
kernel.Bind(typeof(IRepository<>)).To(typeof(Repository<>)).InRequestScope();
kernel.Bind<IRepositoryFactory<Contact>>().ToFactory();
I am using the factory in the following class:
public class TaskRunner : ITaskRunner
{
//MyTask is a simple POCO class(not shown for brevity)
IRepositoryFactory<MyTask> repoFactory = null;
IRepository<MyTask> repo = null;
public TaskRunner(IRepositoryFactory<MyTask> repoFactory)
{
this.repoFactory = repoFactory;
repo = repoFactory.CreateRepository();
}
//implementation elided
}
I am noticing that the call to repoFactory.CreateRepository() always returns the same instance of the factory (dynamic proxy) that Ninject generates.
Question : Is there a way to change/control this behavior and set a "lifetime" such as Transient, PerThread etc. for the instance that "CreateRepository" returns?
In this particular case, tasks might be processed asynchronously on multiple threads and the repository is not thread safe and hence singleton behavior for the instance returned from "CreateRepository" is not desirable.
I'm not sure what you are trying to achieve, but results you are seeing are quite expected because your TaskRunner is bound as Singleton (so constructed once), and you retrieve your repository in the TaskRunner constructor, which again happens once, and so repo is always the same instance. Note this happens regardless of how you bind IRepository and IRepositoryFactory, see Captive Dependency post by Mark Seemann for details http://blog.ploeh.dk/2014/06/02/captive-dependency/.
In fact, if you need to create repo in the constructor, you could just inject IRepository itself. The power of the Factory extension lies in the fact that it allows to resolve instances at runtime, not construction time. For example, if your TaskRunner has Run() method, you can create repository in it, so each task to run can have its own instance.

Interceptor on super method in CDI 1.0/JEE6

In the following case,
public class Base {
#Transactional
public void doSave() {
// ...
}
}
public class Inherited extends Base {
public void someMethod() {
super.doSave();
}
#Override
public void doSave() {
super.doSave();
}
}
If I add the #Transactional annotation to Inherited.someMethod, the interceptor gets called without issue.
However, without the annotation on the inherited class, the interceptor does not get involved in the call to the super class from Inherited.someMethod().
Furthermore, calling Inherited.doSave() does not seem to get the interceptor invoked either. I would have expected the annotation on the superclass to be also valid on the subclass. Is this not the expected behaviour?
I am using Apache DeltaSpike for the #Transactional annotation and this is being deployed as a war in an ear (technically as a jar in a war in an ear). However, this may not be relevant as trying with a custom interceptor shows the same behaviour.
This is JBoss EAP 6.3.0 Alpha in case its relevant.
This is expected. Interceptors are only applied if the object is managed. When you you write it this way with inheritence, it's not applied as it's not part of a call stack that CDI is aware of. You would need to inject Base into your class and call Base.doSave