How to properly use DoThrow()

Solid_Metal :

Just start unit-testing currently, so I have two questions regarding this error within this question, I hope its ok.

  1. I have a class that has one positive test and three negative tests and one of this negative case is using doThrow to simulate failed repository, but it also causes the positive test to fail, is there any way to fix this?

  2. Ideally, do the negative case and positive case must be separated into two class?

I already googled about this but can't find any reference or even the same problem as me, already ask on discord, while I do find some fix for it, by making new class JUST for the negative doThrow case, but i'm looking for additional opinion.

here is the example of the negative case

@Test(expected = DAOException.class)
    public void testFail() throws ObjectNotEncypted, ObjectNotFound {
        List<Long> ids = new ArrayList<Long>();
        ids.add(id);

        Mockito.when(tempRepo.tempfunction(var)).thenReturn(Optional.of(expectedvalue));
        Mockito.when(tempRepo.tempfunction(var)).thenReturn(expectedvalue);
        Mockito.when(tempRepo.tempfunction(var)).thenReturn(null);
        Mockito.when(tempRepo.tempfunction(var)).thenReturn(1);
        Mockito.when(tempRepo.tempfunction(var)).thenReturn(1);
        Mockito.doThrow(DAOException.class).when(tempRepo).tempfunctionthatshouldfail(var);

        service.dofunction(ids);
    }

-- ADDITIONAL CODE heres how i construct the config and declare the variable

@Configuration
    static class classConfig {
        @Bean
        public service accountService() {
            return new serviceImpl();
        }

        @Bean
        public TempRepo tempRepo () {
            return Mockito.mock(TempRepo.class);
        }
}

@Autowired
    private Service service;

    @Autowired
    private TempRepo tempRepo ;

The expected result is all test cases should run, but i got one error, and the trace only one line, its this com.project.common.exception.DAOException and this is the positive case part of the code.

Thank you in advance

Solid_Metal :

So just trying it out again, after some debugging, for some reason my negatif case run BEFORE the positive case, thankfully theres order annotation for junit, since i use JUnit 4, i use order based on class name, but if you use Junit 5, you can use order by number, ex @Order(1) , and it works like intended now

just to be clear, solution with @Before and resetting the mock each time for some reason didn't work even thought technically it should work

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326604&siteId=1