Skip to content

Commit a7bafc0

Browse files
Ahmed-Saiedpivovarit
authored andcommitted
spring boot test (eugenp#1322)
* spring boot test * testing in spring boot article
1 parent 6fbf90f commit a7bafc0

13 files changed

Lines changed: 337 additions & 1 deletion

File tree

‎spring-boot/pom.xml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,12 @@
106106
<version>${jquery.version}</version>
107107
</dependency>
108108

109+
<dependency>
110+
<groupId>com.google.guava</groupId>
111+
<artifactId>guava</artifactId>
112+
<version>18.0</version>
113+
</dependency>
114+
109115
<dependency>
110116
<groupId>org.apache.tomcat</groupId>
111117
<artifactId>tomcat-servlet-api</artifactId>
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package org.baeldung.boot.components;
2+
3+
import org.baeldung.boot.exceptions.CommonException;
4+
import org.baeldung.boot.exceptions.FooNotFoundException;
5+
import org.baeldung.boot.model.Foo;
6+
import org.baeldung.boot.repository.FooRepository;
7+
import org.slf4j.Logger;
8+
import org.springframework.beans.factory.annotation.Autowired;
9+
import org.springframework.stereotype.Component;
10+
11+
import com.google.common.base.Preconditions;
12+
13+
@Component
14+
public class FooComponent {
15+
16+
@Autowired
17+
private FooRepository fooRepository;
18+
19+
private final static Logger logger = org.slf4j.LoggerFactory.getLogger(FooComponent.class);
20+
21+
public Foo getFooWithId(Integer id) {
22+
23+
Foo foo = null;
24+
25+
try {
26+
foo = fooRepository.findOne(id);
27+
Preconditions.checkNotNull(foo);
28+
logger.info("Foo with Id {} found",id);
29+
}catch(NullPointerException ex){
30+
logger.error("Foo with Id {} was not found",id);
31+
throw new FooNotFoundException("The given foo Id was not found");
32+
} catch (Exception ex) {
33+
logger.error("Error while retrieving Foo with Id {} found",id,ex);
34+
throw new CommonException("Error while retrieving foo");
35+
}
36+
37+
return foo;
38+
}
39+
40+
public Foo getFooWithName(String name) {
41+
42+
Foo foo = null;
43+
44+
try {
45+
foo = fooRepository.findByName(name);
46+
Preconditions.checkNotNull(foo);
47+
logger.info("Foo with name {} found",name);
48+
}catch(NullPointerException ex){
49+
logger.error("Foo with name {} was not found",name);
50+
throw new FooNotFoundException("The given foo name was not found");
51+
} catch (Exception ex) {
52+
logger.error("Error while retrieving Foo with name {} found",name,ex);
53+
throw new CommonException("Error while retrieving foo");
54+
}
55+
56+
return foo;
57+
}
58+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package org.baeldung.boot.exceptions;
2+
3+
public class CommonException extends RuntimeException{
4+
5+
/**
6+
*
7+
*/
8+
private static final long serialVersionUID = 3080004140659213332L;
9+
10+
public CommonException(String message){
11+
super(message);
12+
}
13+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package org.baeldung.boot.exceptions;
2+
3+
public class FooNotFoundException extends RuntimeException{
4+
5+
/**
6+
*
7+
*/
8+
private static final long serialVersionUID = 9042200028456133589L;
9+
10+
public FooNotFoundException(String message){
11+
super(message);
12+
}
13+
}

‎spring-boot/src/main/java/org/baeldung/boot/model/Foo.java‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,13 @@ public Foo(String name) {
2121
this.name = name;
2222
}
2323

24+
25+
public Foo(Integer id, String name) {
26+
super();
27+
this.id = id;
28+
this.name = name;
29+
}
30+
2431
public Integer getId() {
2532
return id;
2633
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package org.baeldung.boot.service;
2+
3+
import org.baeldung.boot.components.FooComponent;
4+
import org.baeldung.boot.exceptions.CommonException;
5+
import org.baeldung.boot.exceptions.FooNotFoundException;
6+
import org.baeldung.boot.model.Foo;
7+
import org.springframework.beans.factory.annotation.Autowired;
8+
import org.springframework.http.HttpStatus;
9+
import org.springframework.http.MediaType;
10+
import org.springframework.http.ResponseEntity;
11+
import org.springframework.web.bind.annotation.ExceptionHandler;
12+
import org.springframework.web.bind.annotation.PathVariable;
13+
import org.springframework.web.bind.annotation.RequestMapping;
14+
import org.springframework.web.bind.annotation.RequestMethod;
15+
import org.springframework.web.bind.annotation.RequestParam;
16+
import org.springframework.web.bind.annotation.ResponseStatus;
17+
import org.springframework.web.bind.annotation.RestController;
18+
19+
@RestController
20+
public class FooService {
21+
22+
@Autowired
23+
private FooComponent fooComponent;
24+
25+
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
26+
public ResponseEntity<?> getFooWithId(@PathVariable Integer id) {
27+
28+
Foo foo = fooComponent.getFooWithId(id);
29+
30+
return new ResponseEntity<Foo>(foo, HttpStatus.OK);
31+
}
32+
33+
@RequestMapping(value = "/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
34+
public ResponseEntity<?> getFooWithName(@RequestParam String name) {
35+
36+
Foo foo = fooComponent.getFooWithName(name);
37+
38+
return new ResponseEntity<Foo>(foo, HttpStatus.OK);
39+
}
40+
41+
@ExceptionHandler(value = FooNotFoundException.class)
42+
@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Foo not found")
43+
public void handleFooNotFoundException() {
44+
45+
}
46+
47+
@ExceptionHandler(value = CommonException.class)
48+
@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR, reason = "Common exception")
49+
public void handleCommonException() {
50+
51+
}
52+
}
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package org.baeldung.boot;
2+
3+
import static org.junit.Assert.assertEquals;
4+
import static org.junit.Assert.assertNotNull;
5+
import static org.mockito.Matchers.anyInt;
6+
import static org.mockito.Mockito.doReturn;
7+
8+
import java.util.HashMap;
9+
import java.util.Map;
10+
11+
import org.baeldung.boot.components.FooComponent;
12+
import org.baeldung.boot.model.Foo;
13+
import org.junit.Before;
14+
import org.junit.Test;
15+
import org.junit.runner.RunWith;
16+
import org.springframework.beans.factory.annotation.Autowired;
17+
import org.springframework.boot.test.context.SpringBootTest;
18+
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
19+
import org.springframework.boot.test.mock.mockito.SpyBean;
20+
import org.springframework.boot.test.web.client.TestRestTemplate;
21+
import org.springframework.http.HttpStatus;
22+
import org.springframework.http.ResponseEntity;
23+
import org.springframework.test.context.junit4.SpringRunner;
24+
25+
@RunWith(SpringRunner.class)
26+
@SpringBootTest(classes = DemoApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
27+
public class FooComponentTests {
28+
29+
@Autowired
30+
private TestRestTemplate testRestTemplate;
31+
32+
@SpyBean
33+
private FooComponent fooComponent;
34+
35+
@Before
36+
public void init() {
37+
Foo foo = new Foo();
38+
foo.setId(5);
39+
foo.setName("MOCKED_FOO");
40+
41+
doReturn(foo).when(fooComponent).getFooWithId(anyInt());
42+
43+
// doCallRealMethod().when(fooComponent).getFooWithName(anyString());
44+
}
45+
46+
@Test
47+
public void givenInquiryingFooWithId_whenFooComponentIsMocked_thenAssertMockedResult() {
48+
Map<String, String> pathVariables = new HashMap<String, String>();
49+
pathVariables.put("id", "1");
50+
ResponseEntity<Foo> fooResponse = testRestTemplate.getForEntity("/{id}", Foo.class, pathVariables);
51+
52+
assertNotNull(fooResponse);
53+
assertEquals(HttpStatus.OK, fooResponse.getStatusCode());
54+
assertEquals(5, fooResponse.getBody().getId().longValue());
55+
assertEquals("MOCKED_FOO", fooResponse.getBody().getName());
56+
}
57+
58+
@Test
59+
public void givenInquiryingFooWithName_whenFooComponentIsMocked_thenAssertMockedResult() {
60+
Map<String, String> pathVariables = new HashMap<String, String>();
61+
pathVariables.put("name", "Foo_Name");
62+
ResponseEntity<Foo> fooResponse = testRestTemplate.getForEntity("/?name={name}", Foo.class, pathVariables);
63+
64+
assertNotNull(fooResponse);
65+
assertEquals(HttpStatus.OK, fooResponse.getStatusCode());
66+
assertEquals(1, fooResponse.getBody().getId().longValue());
67+
}
68+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package org.baeldung.boot;
2+
import java.util.HashMap;
3+
import java.util.Map;
4+
5+
import org.baeldung.boot.DemoApplication;
6+
import org.baeldung.boot.model.Foo;
7+
import org.junit.Assert;
8+
import org.junit.Test;
9+
import org.junit.runner.RunWith;
10+
import org.springframework.beans.factory.annotation.Autowired;
11+
import org.springframework.boot.test.context.SpringBootTest;
12+
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
13+
import org.springframework.boot.test.web.client.TestRestTemplate;
14+
import org.springframework.http.HttpStatus;
15+
import org.springframework.http.ResponseEntity;
16+
import org.springframework.test.context.junit4.SpringRunner;
17+
18+
@RunWith(SpringRunner.class)
19+
@SpringBootTest(classes=DemoApplication.class,webEnvironment = WebEnvironment.RANDOM_PORT)
20+
public class FooIntegrationTest {
21+
22+
@Autowired
23+
private TestRestTemplate testRestTemplate;
24+
25+
26+
@Test
27+
public void givenInquiryingFooWithId_whenIdIsValid_thenHttpStatusOK(){
28+
Map<String,String> pathVariables = new HashMap<String,String>();
29+
pathVariables.put("id", "1");
30+
ResponseEntity<Foo> fooResponse = testRestTemplate.getForEntity("/{id}", Foo.class, pathVariables);
31+
Assert.assertNotNull(fooResponse);
32+
Assert.assertEquals(HttpStatus.OK,fooResponse.getStatusCode());
33+
}
34+
35+
@Test
36+
public void givenInquiryingFooWithName_whenNameIsValid_thenHttpStatusOK(){
37+
Map<String,String> pathVariables = new HashMap<String,String>();
38+
pathVariables.put("name", "Foo_Name");
39+
ResponseEntity<Foo> fooResponse = testRestTemplate.getForEntity("/?name={name}", Foo.class, pathVariables);
40+
Assert.assertNotNull(fooResponse);
41+
Assert.assertEquals(HttpStatus.OK,fooResponse.getStatusCode());
42+
}
43+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package org.baeldung.boot;
2+
3+
import static org.junit.Assert.assertEquals;
4+
import static org.junit.Assert.assertNotNull;
5+
6+
import org.baeldung.boot.model.Foo;
7+
import org.baeldung.boot.repository.FooRepository;
8+
import org.junit.Test;
9+
import org.junit.runner.RunWith;
10+
import org.springframework.beans.factory.annotation.Autowired;
11+
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
12+
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
13+
import org.springframework.test.context.junit4.SpringRunner;
14+
15+
@RunWith(SpringRunner.class)
16+
@DataJpaTest
17+
public class FooJPATest {
18+
19+
@Autowired
20+
private TestEntityManager entityManager;
21+
22+
@Autowired
23+
private FooRepository repository;
24+
25+
@Test
26+
public void findFooByName() {
27+
this.entityManager.persist(new Foo("Foo_Name_2"));
28+
Foo foo = this.repository.findByName("Foo_Name_2");
29+
assertNotNull(foo);
30+
assertEquals("Foo_Name_2",foo.getName());
31+
// Due to having Insert query for Foo with Id 1, so TestEntityManager generates new Id of 2
32+
assertEquals(2l,foo.getId().longValue());
33+
}
34+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package org.baeldung.boot;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
5+
import org.baeldung.boot.model.Foo;
6+
import org.junit.Test;
7+
import org.junit.runner.RunWith;
8+
import org.springframework.beans.factory.annotation.Autowired;
9+
import org.springframework.boot.test.autoconfigure.json.JsonTest;
10+
import org.springframework.boot.test.json.JacksonTester;
11+
import org.springframework.test.context.junit4.SpringRunner;
12+
13+
@RunWith(SpringRunner.class)
14+
@JsonTest
15+
public class FooJsonTest {
16+
17+
@Autowired
18+
private JacksonTester<Foo> json;
19+
20+
21+
@Test
22+
public void testSerialize() throws Exception {
23+
Foo foo = new Foo(3, "Foo_Name_3");
24+
assertThat(this.json.write(foo)).isEqualToJson("expected.json");
25+
assertThat(this.json.write(foo)).hasJsonPathStringValue("@.name");
26+
assertThat(this.json.write(foo)).extractingJsonPathStringValue("@.name").isEqualTo("Foo_Name_3");
27+
}
28+
29+
@Test
30+
public void testDeserialize() throws Exception {
31+
String content = "{\"id\":4,\"name\":\"Foo_Name_4\"}";
32+
assertThat(this.json.parseObject(content).getName()).isEqualTo("Foo_Name_4");
33+
assertThat(this.json.parseObject(content).getId()==4);
34+
}
35+
}

0 commit comments

Comments
 (0)