coreexample.MockitoTest.java Source code

Java tutorial

Introduction

Here is the source code for coreexample.MockitoTest.java

Source

/*
 * Copyright 2012 Eng Kam Hon (kamhon@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package coreexample;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * This test cases are testing on how to apply Mockito into unit test
 */
public class MockitoTest {
    @Mock
    static ExampleDao exampleDao;

    @Mock
    static Example2Dao example2Dao;

    ApplicationContext context;

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
        context = new AnnotationConfigApplicationContext(MockitoExampleAppConfig.class);
        when(exampleDao.getExampleName()).thenReturn("bbb");
        when(example2Dao.getName()).thenReturn("ddd");
    }

    @Test
    public void testGetMockExampleDao() {
        ExampleDao dao = context.getBean(ExampleDao.BEAN_NAME, ExampleDao.class);
        assertEquals("bbb", dao.getExampleName());
    }

    @Test
    public void testGetMockExample2Dao() {
        Example2Dao dao = context.getBean(Example2Dao.BEAN_NAME, Example2Dao.class);
        assertEquals("ddd", dao.getName());
    }
}