mercredi 12 février 2020

Can I set some attribute to a Mockito.mock(Class.class)?

I'm currently working on unit-testing services with mockito and Junit 5.
Here is the problematic part of my ServiceTest.java :

...

archiveMeasure=Mockito.mock(ArchiveMeasure.class);
previsionHMeasure=Mockito.mock(PrevisionHMeasure.class);
ruleOccupationRate=Mockito.mock(Rule.class);
calculateIndicatorService=Mockito.mock(CalculateIndicatorService.class);

@Test
    public void DefiniteSectionThatBecomesDark_returnTrue() {
        //Arrange
        ruleOccupationRate.setThreshold(25);
        archiveMeasure.setOccupationRate(30);
        previsionHMeasure.setOccupationRate(30);
        boolean expected = true; 
        //Act

        boolean found = definiteSectionStateCongestionService.DefiniteSectionThatBecomesDark(archiveMeasure,previsionHMeasure,ruleOccupationRate);
        //Assert
        assertEquals(found,expected);
    }

And the service method to test is :

public boolean DefiniteSectionThatBecomesBright (       ArchiveMeasure archiveMeasure,
                                                        PrevisionHMeasure previsionHMeasure,
                                                        Rule ruleOccupationRate) {
        if ( calculateIndicatorsService.calculateActualCongestion(ruleOccupationRate.getThreshold(), archiveMeasure.getOccupationRate())==true || 
            previsionHMeasure.getOccupationRate() < ruleOccupationRate.getThreshold()) {
                return true;
            }
        else {
                return false;
            }

My problem is that I get a NullPointerException when I run the test, at ruleOccupationRate.getThreshold() I guess. I think that I can overcome this difficulty using lots of when().theReturn() for each getter involved in the Service.

So my question is : Why the setters I used on the //Arrange part of my test aren't working ?
Is it possible to set properties to a mock object, to avoid the mocking of every call of the getters ?
If so, how may i proceed ?

Aucun commentaire:

Enregistrer un commentaire