在这里,我使用Junit和Mockito编写了一个简单的测试用例。

import org.jbehave.core.annotations.Given;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

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

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

import com.test.dao.login.LoginDao;
import com.test.mapping.user.User;
import com.test.service.login.LoginService;
import com.test.service.login.impl.LoginServiceImpl;
import com.test.util.common.Common;

public class UserLoginSteps {
    @Mock
    Common common;

    @Mock
    LoginDao loginDao;

    @InjectMocks
    LoginService loginService =new LoginServiceImpl();

    @BeforeClass
    public static void beforeClass() {
        System.out.println("@BeforeClass");
    }

    @Before
    public void before() {
        System.out.println("@Before");
        MockitoAnnotations.initMocks(this);
    }

    @After
    public void after() {
        System.out.println("@After");
    }

    @AfterClass
    public static void afterClass() {
        System.out.println("@AfterClass");
    }


    @Given("$username username and $password password")
    @Test
    public void checkUser(String username, String password) throws Exception{

        when(common.checkNullAndEmpty("admin")).thenReturn(true);
        when(common.checkNullAndEmpty("password")).thenReturn(true);
        when(loginDao.getUser("admin","password")).thenReturn(new User());

        assertEquals(true,loginService.checkValidUser(username, password));
    }
}


我已经在before()函数中初始化了Mock对象。
但是在运行测试用例时不会触发该功能。

我正在使用以下依赖项。

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>2.8.9</version>
    <scope>test</scope>
</dependency>


我已经看到了与此情况类似的问题。
但是以下建议不能解决问题。

有谁能描述它发生的原因以及如何解决此问题,这将对您大有帮助。
提前致谢。

After-before-not-working-in-testcase

Simple-junit-class-is-not-calling-the-before-method

Why-isnt-my-beforeclass-method-running

最佳答案

您应该使用@RunWith(MockitoJUnitRunner.class)注释您的班级,这样MickitoJunitRunner将处理您的模拟和测试。但是,它将无法与JBehave一起使用。您必须决定是否要使用JBehave或MockitoJUnitRunner。

在JBehave中,要使用的正确注释是:@BeforeScenario @AfterScenario @BeforeStory @AfterStory请查看jbehave doc:http://jbehave.org/reference/stable/annotations.html

10-07 19:12
查看更多