Reputation: 23
I'm testing a REST controller using JUnit 4 and MockMvc. When I've written the test a few weeks ago, everything worked as expected. I've done some modifications in my code but I didn't change the JUnit test. Now, when I'm trying to run my tests, I have the error:
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/application.properties]
Here is my code:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MyServerApplication.class)
@SpringBootTest
@Transactional
public class MovieControllerTest {
private MockMvc mockMvc;
@Autowired
private MovieRepository movieRepository;
@Autowired
private WebApplicationContext wac;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
// Some tests
}
And my main class:
@SpringBootApplication
public class MyServerApplication{
public static void main(String[] args) {
SpringApplication.run(MyServerApplication.class, args);
}
}
My application.properties
file is located in src/main/resources
. I didn't move this file, I didn't do anything but add some code in my services and add some properties in my file.
I read SO questions & doc, and tried these solutions:
src/main/resources
is still in my test classpath@PropertySource("classpath:application.properties")
under the annotations in my test ; it didn't work so I tried to create a src/test/resources
with a copy of application.properties
inside, as suggested in one post@PropertySource("classpath:application.properties")
in the main class instead of the test class@WebAppConfiguration
annotation@WebMvcTest
annotationI didn't try all of these solutions at the same time of course, I removed the added code after each failure.
I can still run my code without any issue though, only the test class results in FileNotFoundException
.
How to solve this? And why do I have an issue with the test class but everything working fine when I run my server?
Upvotes: 2
Views: 1181
Reputation: 124461
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MyServerApplication.class)
@SpringBootTest
@Transactional
public class MovieControllerTest { ... }
This is what you have on your test class. When using @SpringBootTest
you shouldn't be using @ContextConfiguration
(see testing chapter of the Spring Boot Reference Guide).
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@Transactional
public class MovieControllerTest { ... }
I would also suggest you use Spring Boot for testing instead of trying to do things manually. For mock mvc testing Spring Boot applications there are special slices and setup already done for you.
To enable this add @AutoConfigureMockMvc
to your test and put @Autowired
on the MockMvc
field (and remove the setup in your @Before
method).
Upvotes: 1