I am writing unit tests for service class. Let’s call it MyService
, which is in the following format:
public class MyService {
private final HttpHeaders headers = new HttpHeaders();
public MyService(MyRepository myRepository) {
headers.setBasicAuth(myRepository.getValue("login"), myRepository.getValue("password"));
}
// OTHER PARTS OF THE CODE
}
In the constructor of MyService
class, I am setting values to headers
field. When writing unit tests, I am facing the problem which will be described below:
@ContextConfiguration(classes = MyService.class)
class MyServiceTest {
@Autowired
private MyService myService;
@BeforeEach
void init() {
mockValue("login", "login_value");
mockValue("password", "password_value");
}
// OTHER PARTS OF THE CODE
}
I have a method mockValue
which mocks the values appropriately. the problem is:
THE CONSTRUCTOR OF MyService
WORKS BEFORE THE init()
METHOD OF MyServiceTest
. AS A RESULT, myRepository.getValue("login")
IS RETURNING NULL, AND headers.setBasicAuth()
METHOD IS THROWING EXCEPTION : “Username must not be null”.
HOW TO HANDLE IT? HOW TO MOCK VALUES BEFORE THE CONSTUCTOR OF MyService WORKS.
I TRIED TO CREATE ANOTHER CLASS, INSIDE WHICH I CAN MOCK VALUES. AND INJECT IT TO MY TEST CLASS.
IT DIDN’T WORK AS I EXCEPTED.
Laziz is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.