#Spring unit tests

5 messages · Page 1 of 1 (latest)

gray helm
#

Hello , i have a small spring application developed with springboot , im currenty trying to test this method of one of my beans:

    public void init() {
        if(this.currentCard!=null || this.currentDeck !=null) {
            return;
        }
        Map<String, String> params;
        FacesContext context = FacesContext.getCurrentInstance();
        params = context.getExternalContext().getRequestParameterMap();
        long id = Long.parseLong(params.get("id"));
        ...
        ...
        ...
    }```

my problem is that this method takes a parameter it needs from context (id) : 
```        Map<String, String> params;
        FacesContext context = FacesContext.getCurrentInstance();
        params = context.getExternalContext().getRequestParameterMap();```

normally the parameter is passed trough clicking a button in the web interface
and i have no idea how to mock this parameter while doing unit tests.

this is the beginning of my test:

```    @DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD)
    @Test
    @DisplayName("Testing if the bean is correctly initialized")
    @WithMockUser(username = "admin", authorities = {"ADMIN", "STUDENT"})
     void testInit() {
        this.applicationContext.getAutowireCapableBeanFactory().autowireBean(this.bean);
        bean.init();
        ....
        ....
    }```
this is the error im getting :
```java.lang.NullPointerException: Cannot invoke "javax.faces.context.FacesContext.getExternalContext()" because "context" is null```

ive looked online for solutions but im somewhat at a loss as i only recently started using spring , would be really thankfull for any help

thank you
craggy glacierBOT
#

This post has been reserved for your question.

Hey @gray helm! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

gray helm
#

this is a solution im trying

    @DisplayName("Testing if the bean is correctly initialized")
    @WithMockUser(username = "admin", authorities = {"ADMIN", "STUDENT"})
    void testInit() {
        FacesContext context = mock(FacesContext.class);
        ExternalContext externalContext = mock(ExternalContext.class);
        Map<String, String> params = new HashMap<>();
        params.put("id", "1");

        when(context.getExternalContext()).thenReturn(externalContext);
        when(externalContext.getRequestParameterMap()).thenReturn(params);
        FacesContext.setCurrentInstance(context);
        
        this.applicationContext.getAutowireCapableBeanFactory().autowireBean(this.bean);
        ...```
but  ```  FacesContext.setCurrentInstance(context);``` is protected so i cannot use it here : /
last karma