如何使用Spring容器测试PostConstruct的这个init()方法?

时间:2018-05-24 19:06:03

标签: java nullpointerexception autowired init

我使用最新的spring-boot-gradle-plugin 2.0来编写单元测试。简而言之,我想在下面的类中为init()postConstruct写一个单元测试:

@Service
public class UserIdService implements IUserIdService
{
    // Local store
    private Map<String, Map<String, String>> store = new TreeMap<>();

    @Autowired
    private ResourceLoader resourceLoader;

    private static final String CSV_FILE_LOCATION = "data/userid-data.csv";

    @PostConstruct
    public void init()
    {
        System.out.println("Loading data from CSV file to UserID Store...");
        int totalRecords = 0;
        Resource resource = resourceLoader.getResource("classpath:" + CSV_FILE_LOCATION);
        try
        {
            InputStream inputStream = resource.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(inputStreamReader);

            for (CSVRecord record : records)
            {
                totalRecords++;
                String number = record.get(0);
                String context = record.get(1);
                String name = record.get(2);

                number = PhoneNumberHelper.convertPhoneNumber(number);

                //add only valid numbers to store
                if(!number.equals(PhoneNumberHelper.INVALID_INPUT))
                {
                    add(new UserId(name, number, context));
                }
            }
        }
        catch (Exception e)
        {
            System.err.println("Can't load or parse CSV file: " + CSV_FILE_LOCATION);
        }
        System.out.println("Loaded total [ " + store.size() + " / " + totalRecords + " ] records.");
    }

    public boolean add(UserId record)
    {
        if (null == store.get(record.getNumber()))
        {
            Map<String, String> newContext = new TreeMap<>();
            newContext.put(record.getContext(), record.getName());
            store.put(record.getNumber(), newContext);
        }
        else
        {
            Map<String, String> currentContext = store.get(record.getNumber());
            if (currentContext.get(record.getContext()) == null)
            {
                currentContext.put(record.getContext(), record.getName());
            }
            else
            {
                //context already exists for the phone number, throw error
                System.err.println("Context already exists for the phone number: " + record.toString());
                return false;
            }

        }
        return true;
    }

    public List<UserId> get(String number)
    {
        List<UserId> result = new ArrayList<>();

        if (null != store.get(number))
        {
            Map<String, String> currentContext = store.get(number);
            for (Map.Entry<String, String> entry : currentContext.entrySet())
            {
                UserId record = new UserId(entry.getValue(), number, entry.getKey());
                result.add(record);
            }
        }
        return result;
    }

    public boolean contains(String number)
    {
        return store.containsKey(number);
    }

}

我创建的测试类看起来像这样:

    @SpringBootApplication
    public class UserIdServiceTest {

        @Autowired
        private UserIdService userIdService;

        @Test
        public void testInit() throws Exception {
            userIdService.init();
            // assert things here..
        }

        @Test
        public void testAdd() {
        }

        @Test
        public void testGet() {
        }

        @Test
        public void testContains() {
        }
    }

当我尝试运行它时,测试失败了:

  

UserIdServiceTest&gt; testInit失败       显示java.lang.NullPointerException           在UserIdServiceTest.testInit(UserIdServiceTest.java:21)

我已经好几天了。我错过了什么? - 我希望能够为所描述的方法创建测试,但无论我在哪里引用userIdService,我总是得到相同的NullPointerException。

感谢您的光临。

0 个答案:

没有答案
相关问题