I have a service class which uses a dependency -
MyService
@Service
@ToString
public class MyService{
Dependency dependency;
public MyService(Dependency dependency) {
System.out.println("started MyService constructor");
this.dependency = dependency;
System.out.println("ended MyService constructor with dependency = " + this.dependency);
}
public void myMethod() {
System.out.println("printing in myMethod : " + dependency.someMethod());
}
public void setDependency(Dependency dependency) {
this.dependency = dependency;
System.out.println("called setter with dependency = " + this.dependency);
}
}
Dependency
@Component
public class Dependency {
public String someMethod() {
return "calling dependency someMethod";
}
}
I wrote 2 test cases for MyService class -
@SpringBootTest
@ContextConfiguration(classes = {MyService.class})
class MyServiceTest {
@InjectMocks
MyService myService;
@MockBean
Dependency dependency;
@Value("${someproperty}")
private String someProperty;
@BeforeEach
void beforeEach() {
System.out.println("beforeEach");
}
@Test
void test1() {
System.out.println("test1 start");
when(dependency.someMethod()).thenReturn("calling mock dependency 1 someMethod");
myService.myMethod();
System.out.println("test1 end");
}
@Test
void test2() {
System.out.println("test2 start");
when(dependency.someMethod()).thenReturn("calling mock dependency 2 someMethod");
myService.myMethod();
System.out.println("test2 end");
}
}
I tried making MyService and Dependency static/non static in MyServiceTest and got following results -
- MyService static, Dependency static
Constructor for MyService runs with dependency = null
first test runs and fails
setDependency is called and dependency is set to a mock object
second test runs fine - MyService static, Dependency non static
Constructor for MyService runs with dependency = null
first test runs and fails
second test runs and fails - MyService non static, Dependency static
Constructor for MyService runs with dependency = null
first test runs and fails
Constructor for MyService runs with dependency = some mock object
second test runs fine - MyService non static, Dependency non static
Constructor for MyService runs with dependency = null
first test runs and fails
Constructor for MyService runs with dependency = null
second test runs fine
Can someone please help me understand these behaviors.