标签: mockito

Junit等待并处理异常后断言

在第一次和第二次通话时抛出的方法:

public void foo() throws Exception
Run Code Online (Sandbox Code Playgroud)

测试:

@test
public void testFooThrowsAtFirstAndSecondTime(){
    boolean thrown;
    try {
       foo();
    } catch (Exception e) {
       thrown = true;
    }
    assertTrue(thrown);

    thrown = false;
    try {
       foo();
    } catch (Exception e) {
       thrown = true;
    }
    assertTrue(thrown);

    foo();
}
Run Code Online (Sandbox Code Playgroud)

你能帮我找到更好的解决方案吗?使用Mockito获得更好的解决方案也是可以接受的.

我的意思是更好,如果我可以在我的测试中避免尝试/捕获甚至多次尝试/捕获.在其他语言或jAssert我认为即使在春天也有如下陈述:

assertThrows(method(..)) //PseudoCode
Run Code Online (Sandbox Code Playgroud)

我认为与Mockito或JUnit 4.x有类似的事情.

我知道

@Test(expected=Exception)
Run Code Online (Sandbox Code Playgroud)

但是,如果我期待一次投掷并且测试结束之后,这将是可接受的.

java junit assert exception-handling mockito

0
推荐指数
1
解决办法
1816
查看次数

无法验证模拟输出流中的写入值

我的TcpTransport类中有以下方法:

public synchronized void send(Envelope envelope) throws IOException {
    ensureSocketOpen();
    String envelopeString = envelopeSerializer.serialize(envelope);

    if (traceWriter != null &&
            traceWriter.isEnabled()) {
        traceWriter.trace(envelopeString, TraceWriter.DataOperation.SEND);
    }

    try {
        byte[] envelopeBytes = envelopeString.getBytes("UTF-8");
        outputStream.write(envelopeBytes);
        outputStream.flush();
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException("Could not convert the serialized envelope to a UTF-8 byte array", e);
    }
}
Run Code Online (Sandbox Code Playgroud)

并测试它:

// Arrange
TcpTransport target = getAndOpenTarget(); // gets a valid instance
Envelope envelope = mock(Envelope.class);
String serializedEnvelope = DataUtil.createRandomString(200);
when(envelopeSerializer.serialize(envelope)).thenReturn(serializedEnvelope);

// Act
target.send(envelope);

// …
Run Code Online (Sandbox Code Playgroud)

java junit mockito

0
推荐指数
1
解决办法
376
查看次数

由于代理而导致Spring Bean注入失败

Spring版本:3.2.4.RELEASE和3.2.9.RELEASE

Mockito版本:1.8.5

我一直在尝试将H2测试引入到旧项目进行集成测试,我遇到了一些问题.由于事务的传播方式,我需要模拟一个自动连接的类.我以前做过这个,但我现在遇到了严重的问题.初始化测试时抛出以下错误消息:

org.springframework.beans.factory.BeanCreationException:创建名为'com.stuff.XMLITCase'的bean时出错:注入资源依赖关系失败; 嵌套异常是org.springframework.beans.factory.BeanNotOfRequiredTypeException:名为'TheProcessor'的Bean必须是[com.stuff.XMLBatchFileProcessor]类型,但实际上是 org.springframework.context.annotation.CommonAnnotationBeanPostProcessor中的[$ Proxy118]类型. postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:307)

深入研究这个问题,事实证明这个bean实际上是一个代理.如果我们检查AbstractBeanFactory(第239轮),我们可以看到代理:

sharedInstance = {$ Proxy117 @ 7035}"com.stuff.XMLBatchFileProcessor@66c540d0"h = {org.springframework.aop.framework.JdkDynamicAopProxy@7039}

唯一的问题是,我不知道这是从哪里来的.我已经查看了配置和依赖项,并且无法找到应该发生的任何地方.

项目设置

不幸的是,我无法为此提供示例项目,但我将介绍我的测试配置.我有一个我为测试扩展的根类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/spring/spring-test-context.xml"})
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
public abstract class AbstractIntegrationTest {
}
Run Code Online (Sandbox Code Playgroud)

这只是在一些spring配置中加载并在每次测试后回滚事务.

spring配置也没什么奇怪的,虽然我的另一个模块和这个模块之间有一个区别.这是事务管理器和会话工厂:

<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="hibernateSessionFactory"/>
</bean>

<bean id="hibernateSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
...
</bean>
Run Code Online (Sandbox Code Playgroud)

在我的其他模块中,我使用的是entityManagerFactory,以及不同的事务管理器:

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
...
</bean>
Run Code Online (Sandbox Code Playgroud)

实际的类有一些自动装配的字段,以及通常的@Service注释:

@Service(value = "TheProcessor")
public final class XMLBatchFileProcessor extends BatchFileProcessor implements IXMLBatchProcessor …
Run Code Online (Sandbox Code Playgroud)

java junit spring hibernate mockito

0
推荐指数
1
解决办法
3208
查看次数

为什么我需要mockito来测试Spring应用程序?

我试图了解所有事情都与Spring有关.但是我不明白为什么在单元测试弹簧代码时会使用mockito?无法弹簧处理与mockito相同的DI吗?什么是mockito贡献的纯净春天是不可能的?

澄清:我的想法是,我可以使用不同的应用程序上下文来测试我在哪里创建我需要的存根bean作为虚拟对象.

java spring mockito

0
推荐指数
1
解决办法
130
查看次数

Mockito当/然后没有返回预期值

我正在尝试使用'any'匹配器来存根这个getKeyFromStream方法.我已经尝试过更明确且更不明确(anyObject()),但似乎无论我尝试什么,这个存根都不会在我的单元测试中返回fooKey.

我想知道是不是因为它受到了保护,或者还有其他我遗漏或做错的事情.我有其他什么时候/然后在整个测试中的语句正在工作,但由于某种原因在这里,它不是.

注意:getKeyFromStream通常使用byteArrayInputStream,但我试图将它与Inp​​utStream匹配,我试过两个都无济于事.

public class FooKeyRetriever() //Mocked this guy
{
    public FooKey getKey(String keyName) throws KeyException {

        return getKeyFromStream(getKeyStream(keyName, false), keyName);
    }

    //Stubbed this method to return a key object which has been mocked
    protected FooKey getKeyFromStream(InputStream keyStream, String keyName){
        //Some code
        return fooKey;
    }
}
Run Code Online (Sandbox Code Playgroud)

单元测试

@Mock
private FooKeyRetriever mockKeyRetriever;

@Mock
private FooKey fooKey;

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

@Test
public void testGetFooKey() throws Exception {



    when(foo.getKeyFromStream(any(InputStream.class),any(String.class))).thenReturn(fooKey);

    FooKey fooKey = mockKeyRetriever.getKey("irrelevant_key");

    assertNotNull(fooKey);
}
Run Code Online (Sandbox Code Playgroud)

java unit-testing mockito stubbing

0
推荐指数
1
解决办法
2万
查看次数

如何在此模拟对象中设置值

如何在下面的模拟对象中设置值.我知道如何获取值但是如何使用mock设置值?

    public class AUTest
    {

    Set<String> permissionIds = new HashSet<String>();

    @Mock 
    UserService userservice;

    @Mock
    PermissionService permissionservice;

    Set<String> emailid = new HashSet<String>();


    @Test
    public void getSuperUserPermissions()
    {
        List<Permissions> allPermissions = permissionservice.getAllPermissions();
        PermissionService permission = Mockito.mock(PermissionService.class);
        Mockito.when(permission.getPermissionById(5L)).thenReturn(pemission);
        Assert.assertNotNull(allPermissions);
    }

}
Run Code Online (Sandbox Code Playgroud)

java mockito

0
推荐指数
1
解决办法
1万
查看次数

错误:类型不匹配:无法从Test转换为Annotation

我是junit Mockito框架的新手,我使用powermock框架嘲笑了依赖注入,但是我在@Test注释的eclipse中得到错误错误是"类型不匹配:无法从Test转换为Annotation"

package org.singh.util.MockitoDemo;

import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.doNothing;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.powermock.api.support.membermodification.MemberMatcher.method;

import org.junit.*;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ExampleUtil.class, ExamplePojo.class})
public class ExamplePojoTest{

    @Test
    public void testMethodMakingPrivateMethodCall() throws Exception {
        ExamplePojo spyExamplePojo = PowerMockito.spy(new ExamplePojo());
        when(spyExamplePojo, method(ExamplePojo.class, "privateMethod", String.class)).withArguments(anyString()).thenReturn("test test");
        String result = spyExamplePojo.methodMakingPrivateMethodCall("test");
        Assert.assertEquals("test test", result);
    }

}
Run Code Online (Sandbox Code Playgroud)

maven依赖是

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito</artifactId>
            <version>1.6.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId> …
Run Code Online (Sandbox Code Playgroud)

java junit mockito powermock powermockito

0
推荐指数
1
解决办法
4474
查看次数

使用ArgumentCaptor <List>和hamcrest.hasSize

我正在使用Mockito和Hamcrest在Java中进行单元测试.

我经常使用Hamcrests hasSize断言某些集合具有一定的大小.几分钟前,我正在编写一个测试,我正在捕获一个List调用(替换名称):

public void someMethod(A someObject, List<B> list)
Run Code Online (Sandbox Code Playgroud)

考试:

@Test
public void test() {
    // (...)
    ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class);
    verify(someMock).someMethod(same(otherObject), captor.capture());
    assertThat(captor.getValue().size(), is(2)); // This works
    assertThat(captor.getValue(), hasSize(2)); // This gives a compile error
    // TODO more asserts on the list
}
Run Code Online (Sandbox Code Playgroud)

问题: 测试运行绿色与第一个assertThat,并且可能有其他方法来解决这个问题(例如,实现ArgumentMatcher<List>),但因为我总是使用hasSize,我想知道如何解决这个编译错误:

The method assertThat(T, Matcher<? super T>) in the type MatcherAssert is not applicable for the arguments (List, Matcher<Collection<? extends Object>>)
Run Code Online (Sandbox Code Playgroud)

java hamcrest mockito

0
推荐指数
1
解决办法
720
查看次数

单元测试Java开关 - 案例逻辑 - 多个单独的函数或多个调用

下面是我必须编写单元测试的一个类中的示例switch语句.我从下面的代码中删除了每种情况下的逻辑.

switch (insurance.getInsuranceType()) {
                case None:{
                    break;}

                case Health: {

                    break;}

                case Auto:{
                    break;}

                case WorkersCompensation:{
                    break;}

                default:{}

            }
Run Code Online (Sandbox Code Playgroud)

我必须覆盖每个交换机路径,但要到达此交换点的功能进行测试,我必须放置10个小时和相应的验证语句(我使用Mockito进行模拟).为了覆盖每个路径,我可以选择编写与switch语句中的情况一样多的函数(对于各种InsuranceType数据)或者我编写单个函数并通过更改InsuranceType数据来重复相同的代码.测试代码以两种方式复制,第二种方式更容易出错,以验证对模拟对象的调用.我的问题是关于任何其他方式(即有助于避免重复的代码和干净的测试代码),怎么办经验的开发人员处理他们的单元测试switch语句(因为有在我的代码的情况下也有病例10秒)?代码是由其他一些开发人员编写的,我被要求编写单元测试以增加测试覆盖率并进行额外的单元测试.我需要知道是否存在关于多个逻辑分支的通用实践(不一定只有switch语句,但有时候有多个if - else if - else逻辑和3-4级深度嵌套条件).insurance.getInsuranceType()是一个枚举.请建议.

java junit unit-testing mockito

0
推荐指数
1
解决办法
1097
查看次数

如何模拟DriverManager.getConnection?

如何模拟DriverManager.getConnection()方法?

我想测试我的方法setUpConnectiontoDB()

我尝试使用PowerMock,easyMock和Mokito本身.我没有找到任何有用的东西.

我的代码:

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class MysqlDAO implements DAO {
    private final Properties properties = new Properties();

    public MysqlDAO(String configPath) {
        loadProperties(configPath);
    }

    private Properties loadProperties(String configPath) {
        try {
            properties.load(new FileInputStream(configPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return this.properties;
    }

    @Override
    public Connection setUpConnectionToDB() {
        try {
            Class.forName("com.mysql.jdbc.Driver");

            return DriverManager.getConnection(
                    properties.getProperty("url"),
                    properties.getProperty("user"),
                    properties.getProperty("passwd"));

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

java jdbc mocking mockito

0
推荐指数
1
解决办法
1307
查看次数