I'm trying to figure out how to test my code in a proper way and stuck somewhere in the middle.
What I use:
Spring-boot based Java web-application. Java based configuration. Test.
What I want:
I want to manage my testing in a proper way. I have a @RestController
annotated class what has two objects what I'd like to change in tests. It's an entities provider class BooksService
and database configuration class DBConfig
. I want to change implementations for these classes in my tests in a simple and proper way. I don't know how to do it correctly.
What kind of help I need:
Sorry if my thoughts are little bit messy, I'm pretty new in Java EE development and still didn't figure out with all basic topics well.
EDIT:
Here is some code
DemoApplication
class
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
BooksController
controller class
@RestController
public class BooksController {
@Autowired
BooksProvider booksProvider;
@CrossOrigin
@RequestMapping("/books")
String allBooks() throws Exception {
return this.booksProvider.fetchAllBooksAsTring();
}
}
BooksProvider
service class
public class BooksProvider {
public String fetchAllBooksAsTring() {
return "[\"Marting Iden\", \"Capital\", \"Strong Wind\"]";
}
}
SimpleConfiguration
configuration class
@Configuration
public class SimpleConfiguration {
@Bean
public BooksProvider booksProvider() {
return new BooksProvider();
}
}
In Spring Boot 1.3.x I have successfully used the following approach:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration({Application.class, IntegrationTestsConfiguration.class})
@ActiveProfiles({"it"})
@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)
public class MyIT {
// tests
}
as you can see apart from Application.class
(the one annotated with @SpringBootApplication
) there is IntergrationTestsConfiguration.class
present in @SpringApplicationConfguration
. This class is responsible for overwriting beans which behaviour I wanted to change for test purposes.
This is how such class can look like:
@Configuration
public class IntegrationTestsConfiguration {
@Bean
@Primary
public BooksProvider booksProvider() {
// your custom instantiation code goes here
}
}
In other words I have used "Primary beans approach".
Since Spring Boot 1.4.x there is @MockBean
annotation available, until now I hadn't opportunity to use it but for sure it is worth checking out.
Further reading:
Take a look in the Spring Boot test. There is a very nice tutorial how to test your controllers:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.