我有两个与我想要比较的相同类型对象的集合.在这种情况下,我想基于不考虑equals()
对象的属性来比较它们.在我的例子中,我使用名称的排名集合,例如:
public class Name {
private String name;
private int weightedRank;
//getters & setters
@Override
public boolean equals(Object obj) {
return this.name.equals(obj.name); //Naive implementation just to show
//equals is based on the name field.
}
}
Run Code Online (Sandbox Code Playgroud)
我想比较两个集合来断言,对于i
每个集合weightedRank
中的位置,该位置的每个名称都是相同的值.我做了一些谷歌搜索,但没有在Commons Collections或任何其他API中找到合适的方法,所以我想出了以下内容:
public <T> boolean comparatorEquals(Collection<T> col1, Collection<T> col2,
Comparator<T> c)
{
if (col1 == null)
return col2 == null;
if (col2 == null)
return false;
if (col1.size() != col2.size())
return false;
Iterator<T> i1 = col1.iterator(), i2 …
Run Code Online (Sandbox Code Playgroud) 我有一个实现InvocationHandler的类,如下所示:
public class MyProxyClass implements InvocationHandler
{
public Object invoke (Object proxy, Method method, Object[] args) throws Throwable
{
//Do something interesting here
}
}
Run Code Online (Sandbox Code Playgroud)
使用PowerMock和Mockito,我试图在我的单元测试类中传入一个模拟的方法对象:
@RunWith(PowerMockRunner.class)
@PrepareForTest({Method.class})
public class MyProxyTest
{
MyProxy underTest;
@Test
public void testInvoke() throws Throwable
{
Method mockMethod = mock(Method.class);
//...
}
}
Run Code Online (Sandbox Code Playgroud)
由于方法是final
,我已经完成了@PrepareForTest
诀窍,但似乎没有削减它.这是因为它是自助的吗?我只是错了吗?
我一直在看下面的链接,但那里没有任何确定性:
我想知道用powermock(和mockito)模拟org.apache.log4j最简单,最简洁的方法是什么.
我尝试了一些方法(我在这里不会说明),但还没有找到实现我想要的方法.我在下面创建了一个简单的类来测试,我想调用run方法并验证是否已经调用了log.info消息.我该怎么做呢?我相信当你知道怎么做时,这很容易!
(我正在使用@Rule,因为我想在弹簧测试下运行,但这应该没有区别).
感谢millon正确的代码.
import org.apache.log4j.Logger;
import org.junit.Rule;
import org.junit.Test;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.rule.PowerMockRule;
public class MockLog4JTest
{
@Rule
public PowerMockRule rule = new PowerMockRule();
private static class ClassUnderTest
{
private static Logger logger = Logger.getLogger(ClassUnderTest.class);
public void run() {
logger.info("Hello.");
}
}
@Test
public void testLog()
{
ClassUnderTest classUnderTest = new ClassUnderTest();
classUnderTest.run();
}
}
Run Code Online (Sandbox Code Playgroud) 我担心答案可能是“拆分项目”,但这里是......
我有一个项目,现在需要输出没有log4j.xml 配置的 jar 文件版本。我想如果我能有双重输出那就太好了:一个带有 log4j.xml 的 jar 和一个没有 log4j.xml 的重复 jar。我不想将项目拆分为一个文件。我已经尝试过 Assembly 插件,但我认为我还没有找到正确的配置。
java ×2
mockito ×2
powermock ×2
unit-testing ×2
collections ×1
comparator ×1
equals ×1
junit ×1
maven ×1
mocking ×1