我怎样才能基于Qualifier模拟出私人成员?

时间:2018-11-24 03:18:08

标签: java spring mockito

为什么会产生NullPointerException

package com.mycompany.app;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.springframework.beans.factory.annotation.Autowired;
import static org.mockito.Mockito.*;
import org.mockito.InjectMocks;
import org.springframework.beans.factory.annotation.Qualifier;

import org.junit.Before;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

class MemberA
{
    public void doSomething(MemberB b)
    {
    }
}

class MemberB
{
    public void doSomething()
    {
    }
}

class MyClass
{
    @Autowired
    @Qualifier("tag1")
    private MemberA a1;

    @Autowired
    @Qualifier("tag2")
    private MemberA a2;

    @Autowired
    private MemberB b;

    public void doSomethingA1()
    {
    a1.doSomething(b);
    }

    public void doSomethingA2()
    {
    a2.doSomething(b);
    }
}

public class AppTest 
    extends TestCase
{
    @Mock(name = "tag1")
    private MemberA x1;

    @Mock(name = "tag2")
    private MemberA x2;

    @Mock
    private MemberB b;

    @InjectMocks
    private MyClass sot;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    public AppTest( String testName )
    {
        super( testName );
    }

    public static Test suite()
    {
        return new TestSuite( AppTest.class );
    }

    public void testDoSomethingA1()
    {
        sot.doSomethingA1();
        verify(x1, times(1)).doSomething(b);
    }

    public void testDoSomethingA2()
    {
        sot.doSomethingA2();
        verify(x2, times(1)).doSomething(b);
    }
}

0 个答案:

没有答案