How do I use spring @SpringBootTest instead of DataJPATest

Kado

I have this code.

@RunWith(SpringRunner.class)
@SpringBootTest(
        webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT,
        classes = ApiDbApplication.class)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@TestPropertySource(
        locations = "classpath:application.yml")
@ExtendWith(SpringExtension.class)
@Transactional
public class LocationIT {

    @MockBean
    CompanyRepository companyRepository;
    @MockBean
    ShipmentRepository shipmentRepository;
    @MockBean
    ContactRepository contactRepository;

    private LocationController locationController;
    private LocationService locationService;

    @Autowired
    LocationRepository locationRepository;

    @LocalServerPort
    private int port;
    TestRestTemplate restTemplate = new TestRestTemplate();
    HttpHeaders headers = new HttpHeaders();

    @Before
    public void setup() {
        locationService = new LocationService(locationRepository);
        this.locationController = new LocationController(locationService);
    }



    @Test
    public void testAddLocation() {
        ObjectMapper mapper = new ObjectMapper()
                .registerModule(new JavaTimeModule());
        ;
        Location location = Location.builder()
                .id(Long.valueOf(7))
                .city("Fayetteville")
                .lat(32.33)
                .lon(37.49)
                .name("Big place")
                .State("Arkansas").build();

        ResponseEntity<String> responseEntity = this.restTemplate
                .postForEntity("http://localhost:" + port + "/api/location/save", location, String.class);

        ResponseEntity<List<Location>> results = restTemplate.exchange("http://localhost:" + port + "/api/location/list",
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<List<Location>>(){});


        assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
        assertEquals(HttpStatus.OK, results.getStatusCode());
        assertEquals(Collections.singletonList(location), results.getBody());

    }
}

Whenever I run the test. My location repository is null and I have the @Repository annotation. This is the error I get: No qualifying bean of type 'com.example.apidb.location.LocationRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

I want to hit the endpoint using restTemplate, so I would rather not use @DataJPATest.

This question is similar: How can I use @SpringBootTest(webEnvironment) with @DataJpaTest?

M. Deinum

If the test case you are running is the actual one in your post you are doing things wrong

  1. You are mixing JUnit4 and JUnit5, that won't work in a single class.
  2. The @TestPropertySource is for property files not yaml files
  3. You should autowire the TestRestTemplate not create it (this also allows you to remove the @LocalServerPort as that is setup already as a base URL.
  4. Your @Before doesn't really make sense, constructing the service and controller don't add anything in your test, it only takes up memory and execution time.
  5. The ObjectMapper inside your test method isn't used, so why construct it.
  6. The @SpringBootTest can figure out the application class itself.
  7. The @AutoConfigureTestDatabase isn't needed, that is only for sliced tests like @DataJpaTest, @DataJdbcTest etc.

That all being said I would expect something like the following to work

Assuming you configured a proper datasource in your application.yml in your src/test/resources.


import org.junit.jupiter.api.Test

@SpringBootTest(
        webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT,
        )
class LocationIT {

    @MockBean
    private CompanyRepository companyRepository;
    @MockBean
    private ShipmentRepository shipmentRepository;
    @MockBean
    private ContactRepository contactRepository;
    
    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    void testAddLocation() {       
        Location location = Location.builder()
                .id(Long.valueOf(7))
                .city("Fayetteville")
                .lat(32.33)
                .lon(37.49)
                .name("Big place")
                .State("Arkansas").build();

        ResponseEntity<String> responseEntity = this.restTemplate
                .postForEntity("/api/location/save", location, String.class);

        ResponseEntity<List<Location>> results = restTemplate.exchange("/api/location/list",
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<List<Location>>(){});

        assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
        assertEquals(HttpStatus.OK, results.getStatusCode());
        assertEquals(Collections.singletonList(location), results.getBody());
    }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How can I use @SpringBootTest(webEnvironment) with @DataJpaTest?

How do do slice testing in Spring Boot 1.4 using @DataJpaTest with SpringFox @EnableSwagger2

How do I use Comet with Spring MVC?

How do I configure Notepad++ to use spaces instead of tabs?

How do I change Eclipse to use spaces instead of tabs?

How do I import configuration classes in a @DataJpaTest in a SpringBootTest?

How to run a integration test in Spring with @SpringBootTest

How do I uninstall PIL for python 2.7 and use Pillow instead?

How to use user defined database proxy in @DataJpaTest

How can I combine @DataJpaTest @SpringBootTest in one MVC application for testing every layer?

How do I use Any() instead of RemoveAll() to exclude list items?

How do I use IsError on a function value, instead of cell value?

How do I force the DotNet Framework to use JIT instead of NGEN?

how do I use JobLauncherSynchronizer in spring admin

How do I use reduce function instead of recurring function?

How do I convert this to use a text file instead?

How do I force compiler to use aggregate init instead of constructor

How do I use an array instead of the variables in this repetitive function?

How do I use json instead of plist to populate TableView

how do I use current node instead of this?

How do I use a validator in Spring? I encountered a 500 error

How do I use jQuery Post/Ajax instead of form submit?

In spring framework if i use annotations instead of XML configuration do i need to initialize the spring container in a separate class?

How to specify Spring `ApplicationContext` object to a SpringBootTest?

How do I make Alien use an existing tarball instead of downloading?

HOw do I use the index as a reference instead of the date

How do I use async pipe instead of using subscribe?

SwiftUI how do I use .textFieldStyle(.myTextFieldStyle) instead of textFieldStyle(MyTextFieldStyle())

How do I use patterns instead of colors in a county map?