I am trying to reach high % coverage using EclEmma on a piece of code and I am having problem covering the following:
public class foo() {
ReadWriteLock compositeLock;
#VisibleForTesting
#Guardedby("compositeLock")
public class String far() {
compositeLock.getLock().unlock();
try {
//code..
return answer;
} finally {
compositeLock.getLock().lock();
}
}
}
I am missing coverage on the finally part, should I use mockito and mock the ReadWriteLock? Or is mocking not needed?
Related
Please, help me write a JUnit test for this code using Mockito.
class A{
private BlockingQueue<Runnable> jobQueue;
public void methodA(List<String> messages) {
try {
jobQueue.put(() -> methodB(message));
} catch(InterruptedException e) {}
}
private void methodB(Message message) {
//other logic
}
}
Your example lacks context as to what it is methodB is doing... Without knowing what the functionality is that you want to verify, just verifying that methodB gets called wouldn't be a particularly useful test, nor is mocking the BlockingQueue. I'm going to go out on a limb and assume that methodB interacts with another object, and it's this interaction that you really want to verify, if that's the case my code and test would look something like:
class A {
private BlockingQueue<Runnable> jobQueue;
private B b;
public void methodA(Message message) {
try {
jobQueue.put(() -> methodB(message));
} catch (InterruptedException e) {
}
}
private void methodB(Message message) {
b.sendMethod(message);
}
}
class B {
public void sendMethod(Message message) {
// other logic
}
}
And my test would potentially look something like:
class Atest {
private A testSubject;
#Mock
private B b;
#Test
public void testASendsMessage() {
Message message = new Message("HELLO WORLD");
testSubject.methodA(message);
verify(b, timeout(100)).sendMethod(message);
}
#Before
public void setup() throws Exception {
testSubject = new A();
}
}
In general you want to avoid needing to verifying bits with multiple threads in a unit test, save tests with multiple running threads mainly for integration tests but where it is necessary look at Mockito.timeout(), see example above for how to use. Hopefully this helps?
I am making a framework for making fractals in processing, however, I need to use functions as parameters for a constructor of a class.
Something like:
class Fractal {
String name;
void initialize;
Fractal(String Name, void setup) {
...
}
}
I'm going to guess you're coming from a JavaScript background?
Traditionally, Java didn't really have a way to do this. Instead you'd pass an anonymous instance of an interface, like this:
interface Runner{
public void run();
}
class Fractal {
String name;
Runner initialize;
Fractal(String name, Runner setup) {
...
}
}
Runner r = new Runner(){
public void run(){
// whatever
}
}
Fractal fractal = new Fractal("name here", r);
Note that Java provides a Runnable interface that you can use instead of creating your own, but I wanted to spell it out here to make it more obvious.
As of Java 8, you can pass a reference to a function as a parameter. This is called a lambda function. Googling "Java lambda function" will return a ton of results.
From this answer:
public void pass() {
run(()-> System.out.println("Hello world"));
}
public void run(Runnable function) {
function.run();
}
Depending on how you're using Processing, you might be stuck with the first approach though, since I don't think the Processing editor supports Java 8 yet.
I trying to repeat login_logout.class 10 times. Why can't I repeat this 10 times?
#RunWith(Suite.class)
#SuiteClasses({login_logout.class})
public class AllTests {
#Parameters
public static Collection<Object[]> getData(){
Object[][] data = new Object[10][0];
return Arrays.asList(data);
}
}
My understanding is "new Object[10][0]" is to construct an two-dimension array:
(1) [10][0] mean the array has 10 lines that each line holds zero object
==> Is it supposed to be "[10][1]" ?
(2) As only the code you uploaded, you didn't actually create any real object,
because the "new Object[10][0]" only make an array not any real object
The Suite test runner doesn't support parameters. You could rewrite login_logout as a parameterized test:
#RunWith(Parameterized.class)
public class LoginLogoutTest {
#Parameterized.Parameters
public static Collection<Object[]> values() {
return Arrays.asList(
new Object[10][1]);
}
public LoginLogoutTest(Object ignored) {
}
#Test
public void doSomething() {
}
}
That being said, I can't think of too many use cases for running the exact same test ten times.
I am newbie to junit.
I need to do junit for the following method. kindly guide me
public boolean binlist(params hpproxy, calendarparam cpxproxy)
{
Getbinresponse binresponse;
cpproxy.setid(hpproxy.getId());
binresponse= cpproxy.getBinlist(); // resturns a list calling webservice
if (binresponse.size>0)
{
result=true;
}
else
{
result=false;
}
return result;
}
I have tried to test the binlist method using mock object.
class testbin
{
#test
public void testbinlist()
{
Testbin mocktestbin=mock(testbin.class);
calendarproxy cpproxy=mock(calendarproxy.class);
params hpproxy= mock(cparams.class);
hpproxy.setId("123");
stub(cpproxy.getBinList()).toReturn(gettestbins()) // mocked getbinlist()
boolen result= mocktestbin.binlist();
assertTrue(result);
}
}
how to test the webservice inside a method?
I think you are pretty spot on in your test. I think you do not need to mock the Testbin since that is the class under test. Just create a mock of the calendarproxy that is being passed on as an argument.
So your test method to test bin would look something like what is below.
class testbin
{
#test
public void testbinlist()
{
Testbin mocktestbin= new Testbin();
calendarproxy cpproxy=mock(calendarproxy.class);
params hpproxy= mock(cparams.class);
hpproxy.setId("123");
when(cpproxy.getBinList()).thenReturn(gettestbins()); // mocked getbinlist()
boolen result= mocktestbin.binlist(hpproxy,cpproxy);
assertTrue(result);
}
}
Is there an equivalent to NUnit's ExpectedException or Assert.Throws<> in jUnit?
You might also consider taking a look at the ExpectedException class which provides richer exception matching.
https://github.com/junit-team/junit/wiki/Exception-testing
Not only you can match the exception class but also you can apply custom matchers to its message.
junit4:
#Test(expected = org.dom4j.DocumentException.class)
void shouldThrowException() {
getFile(null);
}
junit3:
void testShouldThrowException() {
try {
getFile(null);
fail("Expected Exception DocumentException");
} catch(DocumentException e) {}
}
If you are using Groovy for your junit tests you can use shouldFail.
Here is an example using junit3 style:
void testShouldThrowException() {
def message = shouldFail(DocumentException) {
documentService.getFile(null)
}
assert message == 'Document could not be saved because it ate the homework.'
}