简体   繁体   中英

How to mock org.springframework.core.io.Resource object?

In my service method, I have a dependency on org.springframework.core.io.Resource reference and I want to write a test case for one of service method with below code

The code below is as follows:

@Service
public class EmailServiceImpl implements EmailService{

 @Value("classpath:email_template.html")
 private Resource emailTemplateResource;

 private String getEmailTemplate() {

        String template = null;
        try {
            template = new BufferedReader(new InputStreamReader(emailTemplateResource.getInputStream()))
                    .lines().collect(Collectors.joining("\n"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return template;
    }

}

Here, I'm not able to mock emailTemplateResource object in my test case method. I tried with @Mock and @Spy but each time I'm getting NullPointerException on emailTemplateResource object.

So, what is the right way to mock this emailTemplateResource object?

You can do constructor injection in EmailServiceImpl . That way in your mock class when create EmailServiceImpl you can pass your own Resource object in the constructutor.

The overhead with this approach is that @InjectMocks is of no use as now you are creating your object on your own inside before hook of the test case.

example:

@RunWith(MockitoJUnitRunner.class)
public class EmailServiceImplTest{

    EmailServiceImpl  emailServiceImpl ;

    Resource emailTemplateResource;

       @Before
       public void before() {
            emailTemplateResource = //your impl here
           emailServiceImpl  = new EmailServiceImpl(resource);
       }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM