spring boot unit test can not resolve get - spring-boot

why inteli J can not resolve get in my unit test ?
package com.stev.pillecons.pilleCons;
import com.stev.pillecons.pilleCons.controllers.LePilleController;
import com.stev.pillecons.pilleCons.services.PilleService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
#RunWith(SpringRunner.class)
#WebMvcTest(LePilleController.class)
public class UnitTestPille {
#Autowired
private MockMvc mockMvc;
#MockBean
PilleService pilleService;
#Test
public void getAllPille() throws Exception {
mockMvc.perform(get("/api/pille"))
.andExpect(status().isOk())
.andExpect(content())
}
}
all get(),status(), and content() are Red

You are missing the static imports:
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

Related

Spring Boot - unit test not detecting the controller test

I have written unit test for the controller class but when I run unit test using "mvn test" or directly from "SpringBootDemo1ApplicationTests" only test under "SpringBootDemo1ApplicationTests" class runs, and it doesn't pick up test from "BookControllerTest" class.
SpringBootDemo1ApplicationTests.java:
package com.sprboot.SpringBootDemo1;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
#SpringBootTest
class SpringBootDemo1ApplicationTests {
#Test
void contextLoads() {
}
}
BookControllerTest.java
package com.sprboot.SpringBootDemo1;
import com.sprboot.SpringBootDemo1.controllers.BookController;
import com.sprboot.SpringBootDemo1.models.Book;
import com.sprboot.SpringBootDemo1.services.BookService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.json.AutoConfigureJsonTesters;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.json.JacksonTester;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
import java.util.Optional;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
#AutoConfigureJsonTesters
#WebMvcTest(BookController.class)
#SpringBootTest
public class BookControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private BookService bookService;
#Autowired
private JacksonTester<Book> jsonBook;
#Test
private void canRetriveBookById() throws Exception {
given(bookService.getBookByID(123)).willReturn(Optional.of(new Book(123, "test book")));
MockHttpServletResponse response = mockMvc.perform(
get("/getBookById/123")
.accept(MediaType.APPLICATION_JSON))
.andReturn().getResponse();
// then
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(response.getContentAsString()).isEqualTo(
jsonBook.write(new Book(1, "test book")).getJson()
);
}
private void canRetriveBookByIdV2() throws Exception {
given(bookService.getBookByID(123)).willReturn(Optional.of(new Book(123, "test book")));
MockHttpServletResponse response = mockMvc.perform(
get("/getBookById/123")
.accept(MediaType.APPLICATION_JSON))
.andReturn().getResponse();
// then
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(response.getContentAsString()).isEqualTo(
jsonBook.write(new Book(1, "test book")).getJson()
);
}
}
I was expecting test "canRetriveBookById" to run as well but only test "contextLoads" runs, not sure whats wrong here.
It's because your #Test method is private.
From the #Test annotations documentation:
#Test methods must not be private or static and must not return a value.

#Autowired not working inside testcontainers

I am using test containers to make integration tests with the MSSQLServer image and when I am trying to inject my repository I am recieving the following error:
lateinit property modelRepository has not been initialized
And this confuse me because I'm using the same path I used to create the test but using a postgress database in another project.
My test archive:
package *.models.integration
import *.portadapter.repository.ModelRepository
import *.builders.ModelBuilder
import org.junit.ClassRule
import org.junit.Test
import org.junit.jupiter.api.Assertions.assertEquals
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest
import org.springframework.test.context.DynamicPropertyRegistry
import org.springframework.test.context.DynamicPropertySource
import org.testcontainers.containers.MSSQLServerContainer
import org.testcontainers.containers.startupcheck.MinimumDurationRunningStartupCheckStrategy
import org.testcontainers.junit.jupiter.Testcontainers
import java.time.Duration
import java.util.function.Supplier
#DataJpaTest
#Testcontainers
#AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class ModelRepositoryTest {
#Autowired
private lateinit var modelRepository: ModelRepository
companion object {
private val hibernateDriver: Supplier<Any> = Supplier { "org.hibernate.dialect.SQLServerDialect" }
private val hibernateDll: Supplier<Any> = Supplier { "none" }
#ClassRule
#JvmField
val mssqlserver: MSSQLServerContainer<*> = MSSQLServerContainer("mcr.microsoft.com/mssql/server:2017-latest")
.withStartupCheckStrategy(MinimumDurationRunningStartupCheckStrategy(Duration.ofSeconds(5)))
.acceptLicense()
#JvmStatic
#DynamicPropertySource
fun properties(registry: DynamicPropertyRegistry) {
registry.add("spring.datasource.url", mssqlserver::getJdbcUrl)
registry.add("spring.datasource.username", mssqlserver::getUsername)
registry.add("spring.datasource.password", mssqlserver::getPassword)
registry.add("spring.jpa.properties.hibernate.dialect", hibernateDriver)
registry.add("spring.jpa.hibernate.ddl-auto", hibernateDll)
mssqlserver.acceptLicense().start()
}
}
#Test
fun `it should save a model`() {
val model = ModelBuilder().createModel().get()
modelRepository.save(model)
val modelFound = modelRepository.findByCode(model.code)
assertEquals(model.code, modelFound.get().code)
}
}
My Repository:
package *.portadapter.repository
import *.model.domain.Model
import org.springframework.data.jpa.repository.JpaRepository
import java.util.*
interface ModelRepository: JpaRepository<Model, String> {
fun findByCode(code: String): Optional<Model>
}
Could anyone please help me
Make sure you are using the right classes from junit4 or junit5. If you are using junit4 then add #RunWith(SpringRunner.class)
As I mentioned in the comment above, imports from junit4 and junit5 are mixed in the test provided. Below you can find the examples
junit4
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.jdbc.DataJdbcTest;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.testcontainers.containers.MSSQLServerContainer;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
#RunWith(SpringRunner.class)
#DataJdbcTest
#AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class SqlserverDemoApplication3Tests {
#ClassRule
public static MSSQLServerContainer sqlserver = new MSSQLServerContainer("mcr.microsoft.com/mssql/server:2017-CU12")
.acceptLicense();
#DynamicPropertySource
static void sqlserverProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", sqlserver::getJdbcUrl);
registry.add("spring.datasource.username", sqlserver::getUsername);
registry.add("spring.datasource.password", sqlserver::getPassword);
}
#Autowired
private JdbcTemplate jdbcTemplate;
#Test
public void contextLoads() {
this.jdbcTemplate.update("insert into profile (name) values ('profile-1')");
List<Map<String, Object>> records = this.jdbcTemplate.queryForList("select * from profile");
assertThat(records).hasSize(1);
}
}
junit5
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.jdbc.DataJdbcTest;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.MSSQLServerContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
#Testcontainers
#DataJdbcTest
#AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class SqlserverDemoApplication2Tests {
#Container
private static MSSQLServerContainer sqlserver = new MSSQLServerContainer("mcr.microsoft.com/mssql/server:2017-CU12")
.acceptLicense();
#DynamicPropertySource
static void sqlserverProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", sqlserver::getJdbcUrl);
registry.add("spring.datasource.username", sqlserver::getUsername);
registry.add("spring.datasource.password", sqlserver::getPassword);
}
#Autowired
private JdbcTemplate jdbcTemplate;
#Test
void contextLoads() {
this.jdbcTemplate.update("insert into profile (name) values ('profile-1')");
List<Map<String, Object>> records = this.jdbcTemplate.queryForList("select * from profile");
assertThat(records).hasSize(1);
}
}

How to write Spring boot test cases in multiple files for multiple controller respectively

I am using JUnit and Mockito to write test cases for Spring Boot Application. I have multiple controllers(For eg: ContractController and CountryCOntroller). When I write test cases for both of them in a single file , test will pass but if I write ContractController test cases in one file and the other controller test cases in second file , test cases fail.
Can you please let me know how to write in different files?
Contract Controller TEst
package com.example.demo;
import static org.junit.Assert.*;
import java.util.Collections;
import java.util.Optional;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import com.example.demo.controllers.ContractController;
import com.example.demo.controllers.CountryController;
import com.example.demo.entities.Contract;
import com.example.demo.entities.Country;
import com.example.demo.repositories.ContractRepository;
import com.example.demo.repositories.CountryRepository;
#RunWith(SpringRunner.class)
public class ContractControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private ContractRepository contractRepository;
#SuppressWarnings("unchecked")
#Test
public void testGetContract() throws Exception {
System.out.println("contract testing");
Contract contract = new Contract();
contract.setContractTypeId(1);
contract.setContractType("Calibration");
Mockito.when(this.contractRepository.findAll()).thenReturn((Collections.singletonList(contract)));
RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/api/contractType").accept(MediaType.APPLICATION_JSON_UTF8);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
System.out.println("result is"+result.getResponse().getContentAsString());
String expected = "[{id:1,contractType:Calibration}]";
JSONAssert.assertEquals(expected, result.getResponse().getContentAsString(), false);
}
}
COuntry COntroller Test
package com.example.demo;
import static org.junit.Assert.*;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import com.example.demo.controllers.CountryController;
import com.example.demo.entities.Contract;
import com.example.demo.entities.Country;
import com.example.demo.repositories.ContractRepository;
import com.example.demo.repositories.CountryRepository;
#RunWith(SpringRunner.class)
#WebMvcTest(value = CountryController.class)
public class CountryControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private CountryRepository countryRepository;
#MockBean
private ContractRepository contractRepository;
#SuppressWarnings("unchecked")
#Test
public void testGetCountries() throws Exception {
System.out.println("mockito testing");
Country country = new Country();
country.setId(1);
country.setCountryName("Afghanistan");
country.setShortName("AF");
Mockito.when(this.countryRepository.findAll()).thenReturn((Collections.singletonList(country)));
RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/api/countries").accept(MediaType.APPLICATION_JSON_UTF8);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
System.out.println("result is"+result.getResponse().getContentAsString());
String expected = "[{id:1,shortName:AF,countryName:Afghanistan}]";
JSONAssert.assertEquals(expected, result.getResponse().getContentAsString(), false);
}

spring unit testing controller not resolving WebAppContext

I have read online tutorials on unit testing spring MVC, I have copied from tutorials but WebAppContext.class never resolves as a type. What should this resolve too?
package com.doyleisgod.springmavenexample.controllers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.util.Arrays;
import static org.hamcrest.Matchers.*;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {TestContext.class, WebAppContext.class})
#WebAppConfiguration
public class HomeControllerTest {
private MockMvc mockMvc;
#Test
public void indexTest() {
mockMvc.perform(get("/index.htm", 1L))
.andExpect(status().isOk())
.andExpect(view().name("index"))
.andExpect(forwardedUrl("/WEB-INF/views/index.jsp"));
}
}
Eclipse shows WebAppContext cannot be resolved to a type
How do i fix this?
Are you referring to
org.springframework.web.context.WebApplicationContext; or
org.springframework.test.context.web.WebAppConfiguration;
You need spring-test dependencies to resolve these.

Spring controller tests with mocks

So I'm having some issues coming up with a solution for a test.
This is the method I want to test(I'm new to this). It clears all fields on a web page each time it's loaded.
#RequestMapping("/addaddressform")
public String addAddressForm(HttpSession session)
{
session.removeAttribute("firstname");
session.removeAttribute("surname");
session.removeAttribute("phone");
session.removeAttribute("workno");
session.removeAttribute("homeno");
session.removeAttribute("address");
session.removeAttribute("email");
return "simpleforms/addContact";
}
and here's what i have so far for the test
package ControllerTests;
import java.text.AttributedCharacterIterator.Attribute;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration (classes = {SimpleFormsControllerTest.class})
public class SimpleFormsControllerTest {
#Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
#Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
#Test
public void addAddressForm_ExistingContactDetailsInForm_RemovalFromSession() throws Exception{
MockHttpSession mockSession = new MockHttpSession();
mockSession.putValue("firstname", "test");
mockSession.putValue("surname", "test");
mockSession.putValue("phone", "test");
mockSession.putValue("workno", "test");
mockSession.putValue("homeno", "test");
mockSession.putValue("address", "test");
mockSession.putValue("email", "test");
mockMvc.perform(get("simpleForms/addaddressform").session(mockSession));
}
As this is the first time I've ever had to do this kind of thing I don't have much clue where to go with this.
Then you have to do is only assert the values, e.g.:
assertNull(mockSession.getAttribute("firstname"));
If you want to make sure it is the case, you can do:
assertNotNull(mockSession.getAttribute("firstname"));
before you fire the GET request.

Resources