I have two classes
public class MyTest {
#Autowired
private MyService myService;
private void test() {
myService.writeToDb();
}
}
#Service
public class MyService {
#Transactional
public void writeToDb() {
// do db related stuff
}
}
I want to know if calling a method test() (which is a private method) from MyTest class would create a transaction.
P.S
I'm using Spring Boot. And Java 17.
It will work, whether you call the method of another object from a public or private method inside yours is an implementation detail. From callee's point of view, it's the same, it is not even aware of the caller's context.
Spring AOP uses the Proxy pattern to handle those scenarios. It means you are not directly receiving a MyService bean, but a MyServiceSpringCreatedProxy (not the actual name, check in debug mode and you'll see), which is actually handling transactions around methods.
So as long as the call passes through the Spring's proxy, the #Transactional will be accounted for as expected. Bear in mind that it doesn't mean a new transaction is open, it depends if another already exists and your configuration.
However, any self call (to a public or a private method) would not pass through the proxy and then #Transactional would not be working.
#Service
public class MyService {
// can be private, public or whatever
public void callRelatedStuff() {
//self call, no transactional work done
writeToDb();
}
#Transactional
public void writeToDb() {
// do db related stuff
}
}
Related
In out project we don't use setter or filed injection, we use only constructor injection, and I know that both options 1. and 2. may work.
Is it unsafe to work with beans in constructor in that case?
Or spring boot 2+ makes something, and I should better use option 1. instead of 2. I can't imagine case when option 1 will go wrong
#Component
#ConfigurationProperties("config")
public class ServiceConfigProperties {
// .... some code
}
Can be unsafe? - but it looks better
#Component
public class Service {
private boolean skipCheck;
public Service(ServiceConfigProperties configProps) {
this.skipCheck = configProps.isSkipCheck();
}
}
Can't be unsafe?
#Component
public class Service {
private boolean skipCheck;
private ServiceConfigProperties configProps;
public Service(ServiceConfigProperties configProps) {
this.configProps= configProps;
}
#PostConstruct
public void initConfig() {
this.skipCheck= configProps.isSkipCheck();
}
}
With a couple of caveats, interacting with constructor-injected beans inside the constructor is completely safe.
I'm learning about dependecy injection and testing with Mockito. And I just found a tutorial where someone explain an application with dependency injection and without dependency injection. This is the link: https://www.journaldev.com/2394/java-dependency-injection-design-pattern-example-tutorial
I have 2 questions:
The first question is about the code that he writes for testing. What kind of mock is that? Don't you need to use #Mock to mock an object?
This is his code for testing:
public class MyDIApplicationJUnitTest {
private MessageServiceInjector injector;
#Before
public void setUp(){
//mock the injector with anonymous class
injector = new MessageServiceInjector() {
#Override
public Consumer getConsumer() {
//mock the message service
return new MyDIApplication(new MessageService() {
#Override
public void sendMessage(String msg, String rec) {
System.out.println("Mock Message Service implementation");
}
});
}
};
}
#Test
public void test() {
Consumer consumer = injector.getConsumer();
consumer.processMessages("Hi Pankaj", "pankaj#abc.com");
}
#After
public void tear(){
injector = null;
}
}
And the second question is about testing the app without dependency injection. I don't understand why he say that: "Testing the application will be very difficult since our application is directly creating the email service instance. There is no way we can mock these objects in our test classes." Why we cannot mock these objects in our test cases.
The first question is about the code that he writes for testing. What kind of mock is that? Don't you need to use #Mock to mock an object?
To mock an object you have to provide an object that has same type i.e behaves the same or is a subtype of the class that object you want to mock. So to mock an object you can use an instance of anonymous class (in your case it would be an object of anaonymous class that extends MyDIApplication) or you can use Mockito with its #Mock annotation which does basically similiar thing. Bascially using #Mock annotation is similiar to doing :
MyDIApplication myDiApplication = Mockito.mock(MyDIApplication.class)
which creates a mock object extending class passed in constructor. Here you may pass interface or class depending on what you want to mock.
When using anonymous class you provide implementation of methods that you want to mock in overriden implementations of methods, but in case of Mockito you provide intender behaviour by using methods like Mockito::when.
And the second question is about testing the app without dependency injection. I don't understand why he say that: "Testing the application will be very difficult since our application is directly creating the email service instance. There is no way we can mock these objects in our test classes." Why we cannot mock these objects in our test cases.
I guess you are refering to this piece of code :
public class MyApplication {
private EmailService email = new EmailService();
public void processMessages(String msg, String rec){
//do some msg validation, manipulation logic etc
this.email.sendEmail(msg, rec);
}
}
Here you create an instance of EmailService as class field. So there is no possibilty you can mock this (although you could use reflection or PowerMock). So you are tightly coupled to EmailService and it is hard to test MyApplication class logic. To be able to test it you can use constructor injection :
public class MyApplication {
private EmailService email;
public MyApplication(EmailService emaliService) {
this.email = emailService;
}
public void processMessages(String msg, String rec){
//do some msg validation, manipulation logic etc
this.email.sendEmail(msg, rec);
}
}
Or setter injection :
public class MyApplication {
private EmailService email;
public void setEmailService(EmailService emailService) {
this.email = emailService;
}
public void processMessages(String msg, String rec){
//do some msg validation, manipulation logic etc
this.email.sendEmail(msg, rec);
}
}
My mocks are not being picked up when I add a #Secured to any method in the service class and test the service class. This even happens when I am testing a method that isn't secured. I don't understand whether it is due to the mock not being used or being overriden.
public class Service {
#Autowired
private DAO dao;
public void method1() {
...
//System.out.println("DEBUG:" + dao.hashCode());
dao.XXX();
...
}
#Secured("...") // added second time (Case 2)
public void method2() {
...
dao.XXX();
...
}
}
public class ServiceTest {
#Mock
private DAO dao;
#InjectMocks
#Autowired
private Service service;
#Before
public void beforeTest() {
MockitoAnnotations.initMocks(this);
}
public void testMethod1() {
Mockito.when(dao.XXX()).thenReturn(...);
//System.out.println("DEBUG:" + dao.hashCode());
...
}
public void testMethod2() {
Mockito.when(dao.XXX()).thenReturn(...);
...
}
}
Case 1:
I test method1 (testMethod1) without the #Secured on method2 and everything works fine. My expected results match what the Mock dao returns.
Case 2
I add the #Secured to method2 and re-run testMethod1. The test completes but the results are not matching the Mock dao. The actual dao has been used and the actual results match the database data.
I use the DEBUG statements to print the hashcode of the dao in the ServiceTest class and the Service class. In Case 1 they are the same. In Case 2 they are different.
Apparently there is something happening when I add the #Secured. I want to know what that is.
Assuming you are using the SpringJUnit4ClassRunner, the difference may be that Spring is creating a Proxy around your Service to handle the #Secured annotation, and Mockito cannot handle the injection of the dao in the proxy.
Btw, the same would happen with #Asynchronous, #Transactional and co.
I would suggest to use the MockitoRunner (forget Spring), or, if you really need to combine Spring and Mockito, use springockito
How to verify internal proxy calls in unit testing by using Mockito framework?
I am trying to write a test for doAllTasks() method and verify that doSingleTask() was called a certain amount of times. Obviously I can not split my service into two because these methods have the same meaning. The simplest solution is to add setProxy() method but disadvantage of this is that I will need to add test related code to my service definition. Any ideas?
#Service
public class XXXServiceImpl implements XXXService, BeanNameAware {
private String name;
private XXXService proxy;
#Autowired
private ApplicationContext applicationContext;
#Override
public void setBeanName(String name) {
this.name = name;
}
#PostConstruct
public void postConstruct() {
proxy = (XXXService)applicationContext.getBean(name);
}
#Transactional
public void doAllTasks(){
for(...)
proxy.doSingleTask(...);
}
#Transactional(propagation = Propagation.REQUIRES_NEW)
public void doSingleTask(...){
}
}
A simple way to fix this is to add a setter for the proxy and overwrite the field in the unit test with a simple mock. If you also add a getter, you can restore it after the test.
The main drawback is that this prevents you from running the tests in parallel unless you create a new ApplicationContext for this test.
An alternative might be to give the field a #Qualifier so you can define two different beans in your test's configuration. In production, you simply return the singleton.
Inject mock of ApplicationContext.
Mock getBean meatod to return mock of XXXService
Verify doSingleTask invoked
I have a singleton EJB whose business methods are all #Lock(READ). However, on special ocassions, some of them call a private method that persists stuff on a database. What's the best way to handle this situation? Should I:
Use #Lock(WRITE) for that private method even though it's not a business method? If so, is this a reliable behaviour?
Do the synchronization on the private method myself? If so, is it safe to synchronize over the EntityManager?
Do something completely different?
This only partially answers your question, but here goes.
You could put the private methods in a "private" businness interface and call them via the container like this:
TestEJB.java:
#Stateless
public class TestEJB implements PrivateIface, PublicIface {
SessionContext ctx;
public void doBusiness() {
PrivateIface businessObject = ctx.getBusinessObject(PrivateIface.class);
businessObject.doPrivateBusinness();
}
#SomeContainerAnnotation
public void doPrivateBusinness() {
}
}
#Local
interface PrivateIface {
void doPrivateBusinness();
}
PublicIface.java:
#Local
public interface PublicIface {
void doBusiness();
}