File tree Expand file tree Collapse file tree
main/java/com/codecentric/sample/store/service
test/java/com/codecentric/sample/store/service Expand file tree Collapse file tree Original file line number Diff line number Diff line change 66import org .springframework .beans .factory .annotation .Autowired ;
77import org .springframework .stereotype .Service ;
88
9+ import java .io .IOException ;
910import java .util .List ;
1011
1112@ Service
@@ -25,4 +26,19 @@ public int getAveragePriceForAllItems() {
2526
2627 return (sumOfPrices / items .size ()) * StaticService .getMultiplicator ();
2728 }
29+
30+ public String readItemDescription (String fileName ) {
31+
32+ String ret = "" ;
33+
34+ try {
35+ ret = StaticService .readFile (fileName );
36+ } catch (IOException e ) {
37+ // Do some logging and proceed
38+ }
39+
40+ return ret ;
41+ }
42+
43+
2844}
Original file line number Diff line number Diff line change 11package com .codecentric .sample .store .service .tools ;
22
3+ import java .io .IOException ;
34
45public class StaticService {
56
67
78 public static int getMultiplicator () {
89 return 10 ;
910 }
11+
12+ public static String readFile (String fileName ) throws IOException {
13+
14+ // Read file here
15+ return "file content" ;
16+ }
1017}
Original file line number Diff line number Diff line change 1313import org .powermock .core .classloader .annotations .PrepareForTest ;
1414import org .powermock .modules .junit4 .PowerMockRunner ;
1515
16+ import java .io .IOException ;
1617import java .util .ArrayList ;
1718import java .util .List ;
1819
20+ import static org .hamcrest .CoreMatchers .equalTo ;
1921import static org .hamcrest .CoreMatchers .is ;
2022import static org .junit .Assert .assertThat ;
2123import static org .mockito .Mockito .times ;
@@ -57,4 +59,34 @@ public void calculationOfAveragePriceForAllItems() {
5759
5860 assertThat (averagePriceForAllItems , is (2000 *5 ));
5961 }
62+
63+ @ Test
64+ public void readItemDescriptionWithoutIOException () throws IOException {
65+
66+ String fileName = "DummyName" ;
67+
68+ mockStatic (StaticService .class );
69+ when (StaticService .readFile (fileName )).thenReturn ("Dummy" );
70+
71+ String value = itemService .readItemDescription (fileName );
72+
73+ verifyStatic ();
74+
75+ assertThat (value , equalTo ("Dummy" ));
76+ }
77+
78+ @ Test
79+ public void readItemDescriptionWithIOException () throws IOException {
80+
81+ String fileName = "DummyName" ;
82+
83+ mockStatic (StaticService .class );
84+ when (StaticService .readFile (fileName )).thenThrow (IOException .class );
85+
86+ String value = itemService .readItemDescription (fileName );
87+
88+ verifyStatic ();
89+
90+ assertThat (value , equalTo ("" ));
91+ }
6092}
You can’t perform that action at this time.
0 commit comments