The class that I want to test is called UserService with sendEmail method, which sends an email to user. To accomplish this task it depends on EmailService. Now when writing a testcase to test this - should I create UserService userService = new UserService() and mock Email service or create context file define UserService bean there and @Autowired UserService in my test class and mock EmailService? What is the differebce between both approaches and when should i use one over the other?
when to create objects using new operator or use auto-wire when testing a class?
68 views Asked by tech_questions At
1
There are 1 answers
Related Questions in SPRING
- HTTPS configuration in Spring Boot, server returning timeout
- Multi Tenancy in Spring - Partitioned Data Approach
- How to create beans of the same class for multiple template parameters in Spring
- org.telegram.telegrambots.meta.exceptions.TelegramApiException: Bot token and username can't be empty
- Springboot: How to get an entity optional property and check null?
- How do I propagate the current SecurityContext to my @RabbitListener in Spring Boot?
- Spring's XML based bean configuration for Object Mapper's Case Insensitive property
- Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured. I'm using Postgresql
- springboot class org.hibernate.mapping.Bag cannot be cast to class org.hibernate.mapping.SimpleValue
- Issue while deploying JDK 17 and Spring 6 application in Tomcat 10.1.20
- Spring JPA Data Auditing - How to design it?
- Springframework test: Async not started
- Error: Cannot invoke "jakarta.servlet.http.HttpSession.getAttribute(String)" because "session" is null
- How does spring-retry determine which methods to retry when @Retryable is placed at the class level?
- problem with edge server registration in Eureka
Related Questions in JUNIT
- Embedded Kafka Failed to Start After Spring Starter Parent Version 3.1.10
- Springframework test: Async not started
- Problems running both JUnit tests and Selenium/Cucumber tests at the same time
- Writing test methods with shared expensive set-up
- Mocking Stream or Reader in Java Junit
- Junit test: NoSuchElementException, Mock getConnection
- Get program traces with JaCoCo
- Junit test with Mockito: Error ExceptionInInitializerError
- How to Mock HttpResponse
- How to mock dependency in service class from Junit
- classNotPreparedForTest exception, using JUNIT5, MOCKITO and POWERMOCKITO
- Ant Junit ForkMode with Suites
- I import JUnit to Eclipse and still does not work
- Mock DriverManager.getconnection method for junit/mockito unit tests
- throwing a StaleElementReferenceException during dictionary iteration in a for loop
Related Questions in SPRING-TEST
- When i try to test with Testcontainers more than one TestClass, others always failed
- Spring integration tests : how to use context-caching?
- DataJpaTest loads all classes from my context and starts the application like a normal run
- How to run global junit5 test setup depending on spring bean?
- Upgrading Springframework-security from 6.1.1 to 6.2.2 break tests
- How write Junit test for custom Authentication Provider
- @TestConfiguration bean override not working on Spring Boot 2.4.0
- Implementing a custom annotation with readable attributes in Spring Configuration (test)
- Clean way to kick-start a Spring Integration poller in JUnit integration test
- How to deserialize JSON response to a complex Java object with nested fields and a map using Jackson?
- How I fix 404 error when test the spring boot using junit with m:m relationship
- How to mock jakarta.validation.ConstraintValidator or its dependencies?
- How to associate the mockmvc user to the security context holder
- Stubbing void method of spybean failing
- Configured datasource is not injected during a test
Related Questions in SPRINGJUNIT4CLASSRUNNER
- unable to mock RestTemplate response
- JmsListenerContainerFacotory Not available: NoSuchBeanDefinitionException, even though have configured a DefaultJmsListenerContainerFactory
- maven does not detect tests from the command line
- SpringJunit4Runner no tests found
- How to write junit for RabbitListenerEndpointRegistry in spring framework
- I have an apache camel test case which is failing because of different object instances getting created. The object instances are having different IDs
- Migrating Spring 4 to Spring 5 lead to failed Junits using SpringJUnit4ClassRunner
- Intellij Test Case not Exiting
- Pre loading data from .sql before unit testing throws syntax error
- SpringBoot integration tests failing with java.awt.HeadlessException
- Configuration of SpringJUnit4ClassRunner Test clashes with SpringBootTest
- Spring 4, JUnit 4 without spring boot NoSuchBeanDefinitionException: No qualifying bean of type
- Spring configuration via code vs. configuration via annotations
- spring contextconfiguration using bean several times
- when to create objects using new operator or use auto-wire when testing a class?
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
Popular Tags
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
I would say that for
unit testing purposes you could just create
UserServiceusingnewand inject mock. Usingspring ioc containerin this case will not make any difference except tests will be slower, since they will not only create single class, but start spring container.However if your application uses
springyou need to test it somehow as well, and for integration testing approach with spinning spring context works perfectly. In this kind of testing you will test that spring context can start and that beans were injected correctly. However, usually in such kind of testing people try to replace real services with fake endpoints, changing property files accordingly. E.g. :Sending message to some queue - run your own queue in docker and use it for testing.
Saving something to DB - run your own db in docker OR run inmemory one.
Hitting some HTTP endpoint - run wiremock in docker and mock any kind of responses, simulating connection failures, etc.