java - How to mock a file required by a Bean at initialization in JUnit tests -


i have bean reading file @ initialization. file environment specific , generated during installation of system. path of file hardcoded final static variable in code.

private static final string file_path = "/etc/project/file.path"; private string decryptedpassword = "";  @autowired public classtobetested(@value("${pass}") string encryptedpassword) {     string decryptedpassword = staticclass.decrypt(encryptedpassword, file_path); } 

i need somehow mock file in junit tests can test rest of functionalities. @before annotation not useful because run after initialization of beans according tests.

one dirty way can used add parameter autowired function can indicate if call unit test or not. not clean way this. example:

private static final string file_path = "/etc/project/file.path"; private string decryptedpassword = "";  @autowired public classtobetested(@value("${pass}") string encryptedpassword,         @value("${istest}") boolean istest) {     if (istest)         decryptedpassword = encryptedpassword;     else         decryptedpassword = staticclass.decrypt(encryptedpassword, file_path); } 

any ideas how can mock file @ file_path not have use workaround or force property in autowired function without changing bean constructor?

you can use tool whitebox swap file_path in test context.

public class myclass {    private static  string my_string = "hello";     public void whatsmystring() {        system.out.println(my_string);    } } 

note my_string not final

@test     public void testwhiteboxswap() {         myclass test = new myclass();         test.whatsmystring();          string testcontextstring = "\tgoodbye";         whitebox.setinternalstate(myclass.class, testcontextstring);         test.whatsmystring();     } 

console output:

hello     goodbye 

you may still need play @before or @beforeclass in test structure timing right, whitebox can facilitate behavior you're looking for.

be aware not threadsafe solution. if multiple tests change static reference last 1 win!

i use maven project sample. i've attached pom addition below.

<dependency>     <groupid>org.powermock.tests</groupid>     <artifactid>powermock-tests-utils</artifactid>     <version>1.5.4</version> </dependency> 

Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -