0

I am new to Spring Boot and testing. I am currently studying from baeldung's tutorial (https://spring.io/guides/gs/testing-web/) and I bumped into this error.

enter image description here

In fact, it passes when I use isNull() method. But I don't understand this because my controller class has mappings and all that. Why would it be null?

This is my controller class

enter image description here

Or maybe this is not how this test is supposed to be done? But they show it as follows in baeldung

enter image description here

Any help is appreciated.

Best,

Burakhan Aksoy
  • 319
  • 3
  • 14
  • This variable is null as your test doesn't load Spring context. You should setup test as Hiren proposed below. – Andrey Mar 01 '21 at 12:03

2 Answers2

2

If you want to run the testcases with spring context you need to provide @SpringBootTest annotation at your test class (i.e instead of @SpringBootConfiguration at your test class Smoke). The other option apart from @SpringBootTest are as below.

for junit4:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SpringTestConfiguration.class })
public class YourTestClass {}

for junit 5:

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = { SpringTestConfiguration.class })
public class YourTestClass

Where SpringTestConfiguration class hold's all the beans you need to autowire. For more details of SpringRunner vs SpringBootTest read the article

hiren
  • 1,742
  • 13
  • 20
  • Hello. Thank you for the answer Hiren. When I use @SpringBootTest, I get error – Burakhan Aksoy Mar 01 '21 at 13:42
  • java.lang.IllegalStateException: Unable to find a "@SpringBootConfiguration" , you need to use "@ContextConfiguration" or "@SpringBootTest(classes=...)" with your test – Burakhan Aksoy Mar 01 '21 at 13:43
  • yes you need to remove @SpringBootConfiguration annotation – hiren Mar 01 '21 at 13:44
  • One more suggestion is, if you want to do intergration testing of your controller API you should consider MockMvc as demonstrated in the link I shared in my ansser – hiren Mar 01 '21 at 13:45
  • I removed @SpringBootConfiguration annotation. Right now I only have "@SpringBootTest" but I get the error – Burakhan Aksoy Mar 01 '21 at 13:45
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/229344/discussion-between-burakhan-aksoy-and-hiren). – Burakhan Aksoy Mar 01 '21 at 13:49
  • Ok. so the thing is your test class should be under the hierarchy of your SpringBootApplication class. If it is not then you need to provide it as classes argument in @SpringBootTest annotation – hiren Mar 01 '21 at 13:49
0

Have you tried assertNotNull(studentController)?

pens
  • 15
  • 8