How to start Spring Boot server in #BeforeClass of junit - junit

We need to use Spring Boot in our project for testing only at present. The Spring app configuration and test app configuration are as below:
#TransactionConfiguration(transactionManager = "transactionManager")
#Transactional
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#IntegrationTest
#DirtiesContext
public abstract class TestApplicationContext {
}
#SpringBootApplication
public class TestApplication extends SpringBootServletInitializer {
#Bean
public EmbeddedServletContainerFactory embeddedServletContainerFactory() {
...
}
}
Now we need to ensure the Spring Boot server starts in #BeforeClass so that a client can connect to it before any tests run. How do I enable the Spring Boot server to run this way? Removing #SpringapplicationConfiguration and manually starting the server in #BeforeClass like this does not work (it says ContextLoader is NULL). Can someone point out how to achieve this?
public class TestClass extends TestApplicationContext {
...
ConfigurableApplicationContext appContext;
#Beforeclass
public void setup() {
appContext = SpringApplication.run(TestApplication.class, "");
...
}
...
}

Related

Save into Database by Repository SpringBoot MVC

I have to store "extractedNumbers" into SQL Database but I can't manage it. I have created ExtractedNumbersRepository interface but I can't access it from this method and I don't know how to do it. Could somebody help me please?
public class Lotto6From49 extends Thread {
// Save lucky numbers in Database
public ExtractedNumbers addExNr() {
ExtractedNumbers extractedNumbers = new ExtractedNumbers();
extractedNumbers.setExtractedNumbers(luckyNumbers.toString());
extractedNumbers.setExtractionDate(timeNow);
return extractedNumbers;
}
}
#Repository
public interface ExtractedNumbersRepository extends JpaRepository<ExtractedNumbers,Integer> {
}
You should implement a service and inject the ExtractedNumbersRepository dependency:
#Service
public class ExtractedNumbersServiceImpl {
#Autowired
ExtractedNumbersRepository theExtractedNumbersRepository;
public void saveextractedNumbers(ExtractedNumbers extractedNumbers){
//here you can call the repository and save the extracted numbers
this.theExtractedNumbersRepository.save(extractedNumbers);
}
}
The next step is to inject the Service dependency inside your Lotto6From49 or controller:
private final ExtractedNumbersServiceImpl theExtractedNumbersServiceImpl;
public Lotto6From49(ExtractedNumbersServiceImpl extractedNumbersServiceImpl) {
this.theExtractedNumbersServiceImpl= extractedNumbersServiceImpl;
}
Now you can call:
theExtractedNumbersServiceImpl.saveextractedNumbers(extractedNumbers);

Unable to autowire bean in Spring integration test

I am trying to autowire a bean for unit testing purpose.
I'm working with annotation based configuration classes and not using xml based application-context.
Porblem: It says Failed to load ApplicationContext
Here is my code.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = AppContextLoader.class, loader = AnnotationConfigContextLoader.class)
public class StockTest
{
static Logger logger = Logger.getLogger(StockTest.class);
#Autowired
private StockGenerator generator;
#Test
public void someTest()
{//some code here}
}
}
And my configuration class looks like this
#Configuration
public class AppContextLoader
{
#Bean
public StockGenerator stockProvider()
{
StockGenerator stock = new StockGenerator();
return stock;
}
}
Note: StockGenerator is spring managed so I am not sure how to handle it here. I am following this example.
Or is there any other way to autowire beans when one is not using xml based approach.

Unit testing spring mvc with spring-test and junit

I am new to unit testing with spring-test. I have a spring-mvc-rest application. I am able to mock the environment using MockMvc.
My question is do I need to build the MockMvc object in every class of testing?
Would that not be repetitive configuration.
Is there a way to define this in one class and use it across every testing class?
If we go by single configuration or multiple configuration then which is the best way (by design and by maintenance)?
It's called inhertance
for example
Base Class
#ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class)
public class BaseTest
{
protected MockMvc mockMvc;
#Before
public void setup()
{
mockMvc = MockMvcBuilders.standaloneSetup().build();
}
}
Extend
public class ExtendedTest extends BaseTest
{
#Test
public void test()
{
//execute test here we have access to the mockMVC
}
}

Creating Aspect bean in Spring Java Config file causes another bean to not be autowired

Having a weird issue with attempting to test a Spring AOP class.
Here is a similar setup since I cannot put the actual code on here.
Test Class:
#RunWith(SpringJUnit4ClassRunner.class)
#DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
#ContextConfiguration(classes = {MyTestConfiguration.class})
public class MyTest {
#Autowired
private MyService1 myService1;
#Autowired
private MyService2 myService2;
#Test
public void testAop() {
myService1.methodToBeIntercepted();
verify(myService2).create();
}
}
Spring Java Configuration File:
#EnableAspectJAutoProxy
#Configuration
public class MyTestConfiguration {
#Bean
public MyService1 myService1() {
return new MyService1Impl();
}
#Bean
public MyService2 myService2() {
return Mockito.mock(MyService2.class);
}
}
AOP Class:
#Aspect
#Component
public class MyAop {
#Autowired
private MyService2 myService2;
#Around("execution(* package.MyService1.methodToBeIntercepted(..))")
public void interception(ProceedingJoinPoint joinPoint) {
// do stuff
MyReturn myReturn = (MyReturn) joinPoint.proceed();
myService2.create();
}
}
With this setup I get an error saying that the test wanted 1 execution of myService2.create() but there was none. This means the AOP class is not intercepting the call properly and that the Spring configuration is correct in that all beans are found.
Next I added the following to MyTestConfiguration to create the bean for the AOP class:
#Bean
public MyAop myAop() {
return new MyAop();
}
Now I get a Spring error saying it can't find the MyService1 bean so the test never runs. Simply adding the myAop bean to MyTestConfiguration now causes the MyService1 bean to no longer be recognized by Spring.
Am I doing something wrong and if so, what?

Unit testing a Play controller using mocks

The title pretty much says it all. I would like to set up a traditional JUnit test to mock a controller's dependencies and run tests against actions.
I've found that I can achieve my goal like this:
public class AccountsControllerTest {
private controllers.Accounts accountsController;
#Test
public void test() {
running(fakeApplication(), new Runnable() {
public void run() {
accountsController = new controllers.Accounts();
accountsController.setAccountsWorkflow(mock(workflow.Accounts.class));
}
});
}
}
The obvious problem here is that I'm instantiating my class under test and injecting mock dependencies from the test method itself, when I should be doing that in the setup() method. It seems that the setup() method is useless if I'm going to test my controller in a traditional way.
Of course I can test controllers the way Play recommends, but my application is dependent on an external SOAP web service, so I need unit tests to show that our code is working when their servers are down.
So, what's the best way to unit test a Play controller using mocks while still taking advantage of setup() and teardown() methods?
Edit
I realize I'm assuming some knowledge here, so for those who are unaware, controller instantiation in a unit test must be wrapped in a running() function or Play! will throw a runtime exception saying that no application has been started.
You could accomplish this using Mockito and Play's FakeApplication and setting the static Http.Context variable.
This way you can write the test like all other JUnit test.
Example:
...
import static play.test.Helpers.status;
import play.test.FakeApplication;
import play.test.Helpers;
import play.mvc.Http;
import play.mvc.Result;
...
#RunWith(MockitoJUnitRunner.class)
public class ApplicationTest {
public static FakeApplication app;
#Mock
private Http.Request request;
#BeforeClass
public static void startApp() {
app = Helpers.fakeApplication();
Helpers.start(app);
}
#Before
public void setUp() throws Exception {
Map<String, String> flashData = Collections.emptyMap();
Http.Context context = new Http.Context(request, flashData, flashData);
Http.Context.current.set(context);
}
#Test
public void testIndex() {
final Result result = Application.index();
assertEquals(play.mvc.Http.Status.OK, status(result));
}
#AfterClass
public static void stopApp() {
Helpers.stop(app);
}