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?
67 Views Asked by tech_questions At
1
There are 1 best solutions below
Related Questions in SPRING
- Redirect inside java interceptor
- Spring RestTemplate passing the type of the response
- spring-integration-dsl-groovy-http return null when i use httpGet method
- Custom Spring annotation for request parameters
- Spring - configure Jboss Intros for xml with java config?
- HTTP Status 404 - Not Found in Spring 3.2.7
- AndroidAnnotations how to use setBearerAuth
- android I/O error: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found
- Show login dialog when not authenticated yet
- Spring Data Rest supporting json and xml
- @Value annotation not resolved in a class that belongs to dependency jar
- Remove nested _embedded fields while using projections
- How to send Rest GET request that contains "#" value in url parameters?
- How to inject spring bean into Validator(hibernate)
- How to keep a variable in the URL when using Spring LocaleChangeInterceptor
Related Questions in JUNIT
- Reopening the application freshly through appium java script for Next Testcase
- Some of my tests show prepended with junit.framework
- Test Selector Plugin Jenkins returns No tests were executed
- Inject EntityManager in SwitchYard Junit implementation
- Java JUnit4: Make simple assertEquals Test pass
- Don't let test stop on failure
- How to test Reply<?> in sitebricks
- Arquillian Embedded Derby database columnDefinition="text"
- How do I write unit test (JUnit) to check Database connection using DAO class?
- Get full path of a package situated in source folder from junit
- How to write a JUnit unit test for database call?
- Unit tests fail to run after upgrade from grails 2.3 to 2.5
- Issues with a UDF
- Unit testing with Liferay 6.2
- What does the "Test Artifact" selector do in Android STudio
Related Questions in SPRING-TEST
- executeSqlScript fails with Spring for PL/SQL block
- JUnit Tests: Why is Maven (Surefire) so much slower than running on Eclipse?
- Autowired HttpServletRequest in Spring-test integration tests
- Spring tests are closing embedded database multiple times
- @Autowired in @Before of spring-test is null
- Specifying classes loading order in @ContextConfiguration in JUnit test cases
- I would like to test the resolved view name for a spring controller
- What embedded database to use for seamless MySQL > (embedded database) dumping
- Test XML content without using mock mvc
- Junit Tests with Spring Boot Actuator gives Exception
- When should I use TypeExcludeFilters in Spring?
- RunWith SpringJUnit4ClassRunner gives error fail to load ApplicationContext with InitializingBean
- Spring Cloud Stream - Mock Source always failed (without an existing MQ instance)
- Spring boot can not autowire repository bean for service test class
- Why bean is unable to be created in junit test environment?
Related Questions in SPRINGJUNIT4CLASSRUNNER
- Using multiple runner annotation in test class for spring-boot and testrail
- SpringJunit4Runner no tests found
- maven does not detect tests from the command line
- How to write junit for RabbitListenerEndpointRegistry in spring framework
- initializationError running junit test with SpringJUnit4ClassRunner after moving or deleting a class
- unable to mock RestTemplate response
- why can't I access ApplicationContext from ApplicationContextAware implemented bean
- springboottest how to prevent running application
- Unit testing with SpringJUnit4ClassRunner using only @Component and @Autowired
- Start JUnit test with fresh Spring Context
- spring contextconfiguration using bean several times
- when to create objects using new operator or use auto-wire when testing a class?
- The import org.springframework.test.context.junit4.SpringJUnit4ClassRunner cannot be resolved
- Could not open JDBC Connection for transaction in Spring Junits
- JmsListenerContainerFacotory Not available: NoSuchBeanDefinitionException, even though have configured a DefaultJmsListenerContainerFactory
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)
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?
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.