简体   繁体   中英

Mockup JNDI datasource for JUnit test

I'm trying to mockup JNDI datasource into JUnit test but for some reason it's not working:

I use these imports:

import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doReturn;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;    
import javax.activation.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.xml.bind.JAXBException;    
import org.junit.BeforeClass;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.mock.jndi.SimpleNamingContextBuilder;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@SpringBootTest(classes = Application.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class BinCountryCheckFilterImplTest    {

    ..........

    @MockBean
    private static DataSource dataSource;

    @BeforeClass
    public static void setupJndi() throws Exception {
        SimpleNamingContextBuilder.emptyActivatedContextBuilder();
        Context context = new InitialContext();
        context.bind("java:global/production_gateway", dataSource);
    }

    @BeforeEach
    public void beforeEachTest() throws IOException {    
        ........          
    }

    @Test
    public void testBinCountryCheckFilterImpl(){
    .....

}

Is there some way to solve this? Do you see some issues with the imported packages? I need to use JUnit5.

The problem is that you are mixing JUnit 4 with JUnit 5 aka Jupiter. @RunWith and @BeforeClass are from JUnit 4, @BeforeEach is from Jupiter; @Test might be from either depending on the import.

If you replace @BeforeEach with @Before your setup could work; at least you'll be closer to something working. Make sure that all your imports are either from org.junit or from org.junit.jupiter.api

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